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.execution_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.clone(),
519                        run: task.execution_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_for_effects(&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_for_effects(&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 task.stale_question(q) {
887        ActionStanding::Stale
888    } else if q.chosen_action().is_none() {
889        ActionStanding::NoAction
890    } else if task.action_applied(&q.id) {
891        ActionStanding::Applied
892    } else if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
893        ActionStanding::Stale
894    } else if matches!(
895        task.status,
896        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
897    ) {
898        ActionStanding::Busy
899    } else {
900        ActionStanding::Pending
901    }
902}
903
904/// What [`decide_action`] concluded about one answered question.
905#[derive(Debug, Clone, PartialEq, Eq)]
906enum ActionDecision {
907    /// Nothing to do now (no action, already applied, or the task is busy).
908    Skip,
909    /// Continue the named run instead of competing again.
910    Resume(String),
911    /// Requeue as a fresh competition.
912    Requeue,
913    /// Hold the task by explicit operator choice.
914    Hold,
915    /// Close the task as done.
916    Done,
917    /// The question is about an earlier attempt than the task's latest; it
918    /// is recorded as handled and changes nothing.
919    Stale,
920    /// The action cannot be carried out; hold the task and say why. Never
921    /// falls back to something else, because the operator chose this one.
922    Refuse(String),
923}
924
925/// Decide what the choice answered on `q` means for `task`. `load` reads a
926/// run's state, as with [`unfinished_run_with`]. `home` must name that same
927/// store for driver leases and question checkpoints.
928///
929/// `Resume` only fires on the task's *latest* run, and only while that run
930/// could actually make progress ([`RunStatus::resumable`], not released, review
931/// budget left); an answer naming anything else is refused rather than
932/// reinterpreted as a fresh competition.
933fn decide_action<F>(
934    home: &Path,
935    task: &Task,
936    q: &ask::Question,
937    p: &Phrases,
938    load: F,
939) -> ActionDecision
940where
941    F: FnOnce(&str) -> Result<RunState>,
942{
943    if task.stale_question(q) {
944        return ActionDecision::Stale;
945    }
946    let Some(action) = q.chosen_action() else {
947        return ActionDecision::Skip;
948    };
949    if task.action_applied(&q.id)
950        || matches!(
951            task.status,
952            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
953        )
954    {
955        return ActionDecision::Skip;
956    }
957    // A question about an earlier attempt must not act on a newer one. A
958    // conductor question is keyed by the task id, not a run, so it is exempt.
959    if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
960        return ActionDecision::Stale;
961    }
962    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
963    let stopping = q.node == land::APPROVAL_NODE
964        && q.resolution()
965            .as_deref()
966            .is_some_and(crate::merge_decision::stops);
967    // An answer is the owner's decision as of when it was given: a manual hold
968    // placed before it (even after the question was asked) was seen and
969    // overruled by it, while a hold or release after it supersedes it.
970    let decision_at = q.answered_at.unwrap_or(q.asked_at);
971    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
972        return if repair || stopping {
973            ActionDecision::Refuse(format!(
974                "{} 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 {}`",
975                if repair { "repair" } else { "stop" },
976                q.id,
977                q.run,
978                task.id
979            ))
980        } else {
981            ActionDecision::Stale
982        };
983    }
984    match action {
985        a if a.maintenance() => ActionDecision::Skip,
986        ask::ChoiceAction::RecoverBase { .. }
987        | ask::ChoiceAction::ResumeRun { .. }
988        | ask::ChoiceAction::ReleaseTask { .. }
989        | ask::ChoiceAction::RerunChecks { .. }
990        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
991        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
992        ask::ChoiceAction::Hold => ActionDecision::Hold,
993        ask::ChoiceAction::Done => ActionDecision::Done,
994        ask::ChoiceAction::Resume { run } => {
995            if task.execution_runs().last() != Some(run) {
996                return ActionDecision::Refuse((p.resume_not_latest)(
997                    q.short(),
998                    ask::short_id(run),
999                ));
1000            }
1001            match load(run) {
1002                Ok(s) if stopping => {
1003                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1004                        || !s
1005                            .land_approval
1006                            .as_ref()
1007                            .is_some_and(|binding| binding.question == q.id)
1008                    {
1009                        ActionDecision::Stale
1010                    } else if s.liveness_under(home, false) == Liveness::Live {
1011                        ActionDecision::Skip
1012                    } else if s.status == RunStatus::Landing
1013                        && !s.released()
1014                        && s.retired_to.is_none()
1015                    {
1016                        ActionDecision::Resume(run.clone())
1017                    } else {
1018                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1019                    }
1020                }
1021                Ok(s)
1022                    if q.node == land::APPROVAL_NODE
1023                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1024                {
1025                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1026                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1027                    {
1028                        // A live/manual driver already consumed or superseded
1029                        // this answer. Do not hold its fresh approval wait.
1030                        ActionDecision::Stale
1031                    } else if s.liveness_under(home, false) == Liveness::Live {
1032                        ActionDecision::Skip
1033                    } else if s.status != RunStatus::Landing
1034                        || s.released()
1035                        || s.reviews.is_empty()
1036                        || !implementers_match(task, &s)
1037                        || !s
1038                            .land_approval
1039                            .as_ref()
1040                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1041                    {
1042                        ActionDecision::Refuse(format!(
1043                            "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",
1044                            q.id, run, run
1045                        ))
1046                    } else {
1047                        ActionDecision::Resume(run.clone())
1048                    }
1049                }
1050                Ok(s) if s.liveness_under(home, false) == Liveness::Live => {
1051                    ActionDecision::Refuse("run already has a live driver".into())
1052                }
1053                Ok(s) => match crate::handover::resume_refusal_under(&s, Some(home)) {
1054                    None => ActionDecision::Resume(run.clone()),
1055                    Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1056                        q.short(),
1057                        ask::short_id(run),
1058                        &reason.diagnostic(&s),
1059                    )),
1060                },
1061                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1062                    q.short(),
1063                    ask::short_id(run),
1064                    &format!("{e:#}"),
1065                )),
1066            }
1067        }
1068    }
1069}
1070
1071/// The fixed prose the daemon writes into [`Task::last_error`] and
1072/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1073/// `triage::Wording` and `land::Words`: only English and Japanese are
1074/// translated, anything else falls back to English.
1075///
1076/// Rendered when the reason is *generated*, so a reason keeps the language it
1077/// was written in if the setting changes later. The notification frame
1078/// (`Task <id> is held:`) is not here and stays English.
1079///
1080/// Deliberately **not** translated, because other code reads them back by
1081/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1082/// and `gate red`. IDs, node names, paths and external error text are embedded
1083/// as they are.
1084struct Phrases {
1085    /// `{}` = status label, then the detail.
1086    graph_stopped: fn(&str, &str) -> String,
1087    quorum_lost: &'static str,
1088    /// Followed by the seats' names.
1089    quota_took_out: &'static str,
1090    /// Followed by the status label.
1091    run_ended: &'static str,
1092    /// Followed by the question's short id.
1093    waiting_for_answer: &'static str,
1094    recovered_running: &'static str,
1095    no_run_to_recover: &'static str,
1096    could_not_start: &'static str,
1097    resume_not_latest: fn(&str, &str) -> String,
1098    resume_cannot_progress: fn(&str, &str, &str) -> String,
1099    resume_unreadable: fn(&str, &str, &str) -> String,
1100    /// A takeover refusal: the operator-facing text. English is the error's own
1101    /// `Display`; a translation keeps the machine detail apart in parentheses.
1102    handover_refused: fn(&crate::handover::Refused) -> String,
1103    /// Appended to a refused handover's hold reason (leading space included).
1104    handover_hint: &'static str,
1105    /// (seats that never answered, review rounds) for the review loop's
1106    /// "refusing to call it clean" stop.
1107    reviewers_never_answered: fn(usize, usize) -> String,
1108}
1109
1110const PHRASES_EN: Phrases = Phrases {
1111    graph_stopped: |status, detail| {
1112        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1113    },
1114    quorum_lost: "the judging panel lost its quorum",
1115    quota_took_out: "; quota took out ",
1116    run_ended: "run ended ",
1117    waiting_for_answer: " - waiting for operator answer to question ",
1118    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1119    no_run_to_recover: "task was `running` with no live daemon and no readable \
1120                        run to recover; held for a human to check what happened",
1121    could_not_start: "could not start the run: ",
1122    resume_not_latest: |q, run| {
1123        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1124    },
1125    resume_cannot_progress: |q, run, reason| {
1126        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1127    },
1128    resume_unreadable: |q, run, e| {
1129        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1130    },
1131    handover_refused: |r| r.to_string(),
1132    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1133    reviewers_never_answered: |missing, rounds| {
1134        format!(
1135            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1136             refusing to call it clean"
1137        )
1138    },
1139};
1140
1141const PHRASES_JA: Phrases = Phrases {
1142    graph_stopped: |status, detail| {
1143        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1144    },
1145    quorum_lost: "審査パネルが定足数を失いました",
1146    quota_took_out: "。クォータで脱落: ",
1147    run_ended: "run 終了: ",
1148    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1149    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1150    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1151                        何が起きたか人が確認するため保留にしました",
1152    could_not_start: "run を開始できませんでした: ",
1153    resume_not_latest: |q, run| {
1154        format!(
1155            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1156        )
1157    },
1158    resume_cannot_progress: |q, run, reason| {
1159        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1160    },
1161    resume_unreadable: |q, run, e| {
1162        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1163    },
1164    handover_refused: |r| {
1165        use crate::handover::Refused;
1166        match r {
1167            Refused::Foreign { branch, path, why } => format!(
1168                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1169                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1170                 から、やり直してください(詳細: {why})"
1171            ),
1172            Refused::Unsafe { branch, path, why } => format!(
1173                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1174                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1175                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1176            ),
1177            Refused::ReleaseFailed { branch, path, run } => format!(
1178                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1179                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1180                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1181            ),
1182        }
1183    },
1184    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1185    reviewers_never_answered: |missing, rounds| {
1186        format!(
1187            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1188             クリーンとは認めません"
1189        )
1190    },
1191};
1192
1193fn phrases(language: &str) -> &'static Phrases {
1194    if crate::lang::is_japanese(language) {
1195        &PHRASES_JA
1196    } else {
1197        &PHRASES_EN
1198    }
1199}
1200
1201/// The language of the repository a task belongs to, read best-effort for the
1202/// paths that have no run (and so no config of their own) to ask. An unreadable
1203/// config is English, not an error: a hold reason must still get written.
1204fn language_of(task: &Task, fallback: &Path) -> String {
1205    crate::lang::of_repo(&repo_for(task, fallback))
1206}
1207
1208/// The task an answered question speaks for: the one whose runs include the
1209/// question's run, or - for a conductor question, filed under the task's own
1210/// id - the task with that id.
1211pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1212    if q.node == crate::conduct::NODE {
1213        return tasks.iter().find(|t| t.id == q.run);
1214    }
1215    tasks.iter().find(|t| t.runs.contains(&q.run))
1216}
1217
1218/// Legacy conductor prose never becomes a maintenance command by inference.
1219/// Replace unsupported open labels under the question lock before dispatch.
1220fn repair_choice_offers(questions: &Questions) {
1221    let ownership = crate::task_chat::InquiryOwnership::default();
1222    for q in questions
1223        .list_for_effects_in(&ownership)
1224        .into_iter()
1225        .filter(|q| {
1226            q.status.open()
1227                && q.node == crate::conduct::NODE
1228                && q.choices
1229                    .iter()
1230                    .any(|c| crate::choice_effect::describe(q, c).is_none())
1231        })
1232    {
1233        let _ = questions.update_in(&q.id, &ownership, |current| {
1234            if current.status.open() {
1235                crate::choice_effect::executable_conductor(current);
1236                if let Some(deputy) = &mut current.deputy {
1237                    deputy.brief = crate::deputy::brief(
1238                        &current.run,
1239                        &current.detail,
1240                        &current.choices,
1241                        &current.actions,
1242                    );
1243                }
1244            }
1245            Ok(())
1246        });
1247    }
1248}
1249
1250/// Apply answered typed choices. Only the daemon calls this in production;
1251/// deputies settle the question and never execute its actions.
1252pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1253    apply_maintenance_choices(queue, questions, home).await;
1254    apply_task_choice_actions(queue, questions, home);
1255}
1256
1257/// Apply bounded maintenance effects independently of question ownership: a
1258/// release watcher need not have a queue task, and a predecessor is another run.
1259async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1260    let ownership = crate::task_chat::InquiryOwnership::default();
1261    for q in questions.list_for_effects_in(&ownership) {
1262        // Read again under the same fence used by explicit settlement.
1263        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1264            continue;
1265        };
1266        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1267            continue;
1268        };
1269        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1270            continue;
1271        };
1272        // Receipt paths use question IDs, whose format is independent of run
1273        // IDs. Apply the question store's filename safety rule to both eras.
1274        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1275            continue;
1276        }
1277        if queue.list().iter().any(|task| {
1278            (task.id == q.run
1279                || task.runs.contains(&q.run)
1280                || q.routed_task.as_deref() == Some(&task.id))
1281                && task.stale_question(&q)
1282        }) {
1283            continue;
1284        }
1285        if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1286            let tasks = queue.list();
1287            let owner = crate::task_chat::task_of(&q, &tasks);
1288            if let Some(owner) = owner
1289                && q.routed_task
1290                    .as_deref()
1291                    .is_none_or(|routed| routed == owner)
1292            {
1293                let result = crate::base_recovery_control::recover(
1294                    queue,
1295                    home,
1296                    crate::base_recovery_control::Request {
1297                        run: run.clone(),
1298                        head: stop.head.clone(),
1299                        actor: "decisions".into(),
1300                        request: q.id.clone(),
1301                        decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1302                        expected_stop: Some((stop.clone(), *episode)),
1303                    },
1304                )
1305                .await;
1306                if let Err(error) = result {
1307                    tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1308                    notices::raise_in(home, Notice::warn(
1309                        &format!("base-recovery:{}", q.id),
1310                        format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1311                    ).link(Link::Run { id: run.clone() }));
1312                }
1313            }
1314            continue;
1315        }
1316        let dir = home.join("choice-actions");
1317        if std::fs::create_dir_all(&dir).is_err() {
1318            continue;
1319        }
1320        let Ok(lock) = std::fs::OpenOptions::new()
1321            .create(true)
1322            .truncate(false)
1323            .write(true)
1324            .open(dir.join(format!("{}.lock", q.id)))
1325        else {
1326            continue;
1327        };
1328        if crate::pr_head::try_lock_file(&lock).is_err() {
1329            continue;
1330        }
1331        let fresh = !home
1332            .join("choice-actions")
1333            .join(format!("{}.json", q.id))
1334            .exists();
1335        let result = async {
1336            let receipt = dir.join(format!("{}.json", q.id));
1337            if receipt.exists() {
1338                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1339                anyhow::ensure!(
1340                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1341                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1342                );
1343                return Ok::<_, anyhow::Error>(());
1344            }
1345            // Never retry an uncertain external effect. The receipt is written
1346            // before calling gh, exactly like release_watch's rerun record.
1347            let record = |status: &str| -> anyhow::Result<()> {
1348                let tmp = receipt.with_extension("tmp");
1349                std::fs::write(
1350                    &tmp,
1351                    serde_json::to_vec(&serde_json::json!({
1352                        "action": action, "status": status,
1353                    }))?,
1354                )?;
1355                std::fs::rename(tmp, &receipt)?;
1356                Ok(())
1357            };
1358            let applied = async {
1359                match action {
1360                    ask::ChoiceAction::ResumeRun { run } => {
1361                        crate::resume::validate(home, run)?;
1362                        record("started")?;
1363                        let decided = q.answered_at.unwrap_or(q.asked_at);
1364                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1365                            crate::resume::validate_unqueued(home, run)?;
1366                            crate::resume::start(home, run.clone()).await?;
1367                        }
1368                    }
1369                    ask::ChoiceAction::ReleaseTask {
1370                        task,
1371                        held_at,
1372                        reason,
1373                    } => {
1374                        anyhow::ensure!(
1375                            queue.resolve_id(task)? == *task,
1376                            "task action requires an exact task ID"
1377                        );
1378                        let _claim = queue.claim(task)?;
1379                        let mut task = queue.get(task)?;
1380                        if task.action_applied(&q.id) {
1381                            return Ok(());
1382                        }
1383                        // Filing this conductor question temporarily wraps the
1384                        // original hold in a Blocked state. Restore only that
1385                        // exact blocker on the local copy before checking the
1386                        // hold binding; unrelated waits never authorize release.
1387                        if q.node == crate::conduct::NODE
1388                            && q.run == task.id
1389                            && task.status == TaskStatus::Blocked
1390                            && task.blocked_from == Some(TaskStatus::Held)
1391                            && task.blocked_by.as_slice() == [q.id.as_str()]
1392                        {
1393                            task.unblock(&q.id);
1394                        }
1395                        anyhow::ensure!(
1396                            task.status == TaskStatus::Held
1397                                && task.held_at == Some(*held_at)
1398                                && task.hold_reason.as_deref() == reason.as_deref()
1399                                && task
1400                                    .operator_decided_at
1401                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1402                            "task no longer has the hold this question names"
1403                        );
1404                        task.release_operator("choice", Some(&q.id));
1405                        task.mark_action_applied(&q.id);
1406                        queue.put(&mut task)?;
1407                    }
1408                    ask::ChoiceAction::AbandonRun { run } => {
1409                        record("started")?;
1410                        crate::driver::abandon_proven_dead(home, run)?;
1411                    }
1412                    ask::ChoiceAction::RerunChecks {
1413                        repo,
1414                        pr,
1415                        head,
1416                        runs,
1417                    } => {
1418                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1419                            .await?;
1420                    }
1421                    _ => unreachable!(),
1422                }
1423                Ok::<_, anyhow::Error>(())
1424            }
1425            .await;
1426            match applied {
1427                Ok(()) => record("applied"),
1428                Err(e) => {
1429                    record(&format!("refused or failed: {e:#}"))?;
1430                    Err(e)
1431                }
1432            }
1433        }
1434        .await;
1435        // Retire the originating blocker as well as the target operation.
1436        // A foreign resume leaves its issuer held instead of competing beside
1437        // the execution just started. Other successful maintenance lets the
1438        // original task retry its normal, guarded path.
1439        if home
1440            .join("choice-actions")
1441            .join(format!("{}.json", q.id))
1442            .exists()
1443            && let Some(listed) = task_of_question(&queue.list(), &q)
1444            && !listed.action_applied(&q.id)
1445            && let Ok(_claim) = queue.claim(&listed.id)
1446            && let Ok(mut origin) = queue.get(&listed.id)
1447        {
1448            if !origin.operator_held()
1449                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1450                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1451            {
1452                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1453                    origin.hold_machine(Some(format!(
1454                        "Maintenance choice {} settled; inspect its target before releasing this task",
1455                        q.id
1456                    )));
1457                } else {
1458                    origin.unblock(&q.id);
1459                }
1460            }
1461            origin.mark_action_applied(&q.id);
1462            let _ = queue.put(&mut origin);
1463        }
1464        if let Err(e) = result
1465            && fresh
1466        {
1467            notices::raise_in(
1468                home,
1469                Notice::warn(
1470                    &format!("action:{}", q.id),
1471                    format!("Choice action {} was not completed: {e:#}", q.id),
1472                )
1473                .link(if q.run_names_task() {
1474                    Link::Task { id: q.run.clone() }
1475                } else {
1476                    Link::Run { id: q.run.clone() }
1477                }),
1478            );
1479        }
1480    }
1481}
1482
1483/// Rerun the named failed workflow runs of a pull request, each at most once
1484/// per `request` (a question id, or a chat operation identity). The head,
1485/// lifecycle and failed state are re-read from the forge first; `started` is
1486/// called once those checks pass and before the first external call, and the
1487/// ledger entry is written before every `gh` call, so an uncertain result is
1488/// never repeated automatically.
1489pub(crate) async fn rerun_checks_once(
1490    home: &Path,
1491    request: &str,
1492    repo: &Path,
1493    pr: &str,
1494    head: &str,
1495    runs: &[String],
1496    started: impl FnOnce() -> anyhow::Result<()>,
1497) -> anyhow::Result<()> {
1498    use crate::release_watch::{GhForge, ReleaseForge};
1499    anyhow::ensure!(
1500        !runs.is_empty()
1501            && runs.len() <= 20
1502            && runs
1503                .iter()
1504                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1505            && !pr.starts_with('-'),
1506        "invalid rerun targets"
1507    );
1508    let snap = GhForge.snapshot(repo, pr).await?;
1509    anyhow::ensure!(
1510        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1511        "pull request head or lifecycle changed"
1512    );
1513    anyhow::ensure!(
1514        runs.iter().all(|r| snap
1515            .checks
1516            .iter()
1517            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1518        "named workflow is no longer failed on this pull request"
1519    );
1520    started()?;
1521    let dir = home.join("choice-actions");
1522    std::fs::create_dir_all(&dir)?;
1523    let rerun_lock = std::fs::OpenOptions::new()
1524        .create(true)
1525        .truncate(false)
1526        .write(true)
1527        .open(dir.join("reruns.lock"))?;
1528    crate::pr_head::try_lock_file(&rerun_lock)?;
1529    let ledger = dir.join("reruns.json");
1530    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1531        serde_json::from_slice(&std::fs::read(&ledger)?)?
1532    } else {
1533        Default::default()
1534    };
1535    for run in runs {
1536        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1537        if !recorded.insert(key) {
1538            continue;
1539        }
1540        let tmp = ledger.with_extension("tmp");
1541        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1542        std::fs::rename(tmp, &ledger)?;
1543        GhForge.rerun(repo, run).await?;
1544    }
1545    Ok(())
1546}
1547
1548/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1549///
1550/// Runs on every poll before the conductor looks at the queue. The task is
1551/// re-read under its claim, so a task somebody completed or held by hand in
1552/// the meantime is judged on what it is now. `Resume` releases the task and
1553/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1554/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1555/// ordinary `unfinished_run` logic resumes that same run.
1556pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1557    let tasks = queue.list();
1558    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1559    for q in questions.list_for_effects_in(&ownership) {
1560        // Read again under the same fence used by explicit settlement.
1561        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1562            continue;
1563        };
1564        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1565            continue;
1566        };
1567        // Dismissal is committed by the question writer, never a resume.
1568        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1569            continue;
1570        }
1571        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1572            continue;
1573        }
1574        let Some(listed) = task_of_question(&tasks, &q) else {
1575            if q.node == land::APPROVAL_NODE
1576                && q.resolution().as_deref().is_some_and(|choice| {
1577                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1578                })
1579            {
1580                notices::raise_in(
1581                    home,
1582                    Notice::warn(
1583                        &format!("repair-owner:{}", q.id),
1584                        format!(
1585                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1586                            q.run, q.run
1587                        ),
1588                    ).link(Link::Run { id: q.run.clone() }),
1589                );
1590            }
1591            continue;
1592        };
1593        if listed.action_applied(&q.id) {
1594            continue;
1595        }
1596        let Ok(_claim) = queue.claim(&listed.id) else {
1597            continue;
1598        };
1599        let Ok(mut task) = queue.get(&listed.id) else {
1600            continue;
1601        };
1602        // Work only on this local copy until the action can be committed.
1603        // In particular, a fresh lease below leaves the persisted task blocked.
1604        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1605            let blockers: Vec<_> = task
1606                .blocked_by
1607                .iter()
1608                .filter(|id| {
1609                    crate::queue::dependency(queue, questions, id)
1610                        == crate::queue::Dependency::Question(q.id.clone())
1611                })
1612                .cloned()
1613                .collect();
1614            if !blockers.is_empty() {
1615                for id in blockers {
1616                    task.unblock(&id);
1617                }
1618                let answer = match &q.answer {
1619                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1620                    None => String::new(),
1621                };
1622                task.record_answer(q.summary.clone(), answer);
1623            }
1624        }
1625        let language = language_of(&task, Path::new("."));
1626        let decision = decide_action(home, &task, &q, phrases(&language), |id| {
1627            RunState::load_under(id, home)
1628        });
1629        let ran = matches!(
1630            decision,
1631            ActionDecision::Resume(_)
1632                | ActionDecision::Requeue
1633                | ActionDecision::Hold
1634                | ActionDecision::Done
1635        );
1636        if ran && asker_may_still_read(questions, &q, home) {
1637            // The asking process or its seat can still take the word; act
1638            // once it has gone quiet. Bound on the remaining window: the
1639            // check is not atomic with the write below, so an asker that
1640            // takes the word in between (at most one poll, never more than
1641            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1642            // and `Task::actions_applied` under the claim keeps the action to
1643            // one application. The waiter does not deliver an answer that
1644            // carries an action (`waiter::decide_owned`), so it cannot race.
1645            continue;
1646        }
1647        let done = matches!(decision, ActionDecision::Done);
1648        // Resume owes an execution pass; only these task-local effects finish
1649        // in this write. Stale/refused actions never acquire an effect receipt.
1650        let completed = matches!(
1651            decision,
1652            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1653        );
1654        match decision {
1655            ActionDecision::Skip => continue,
1656            ActionDecision::Resume(run) => {
1657                task.release_operator("choice", Some(&q.id));
1658                task.resume_override = Some(crate::queue::OperatorResume {
1659                    question_id: q.id.clone(),
1660                    at: Timestamp::now(),
1661                    conductor_rehold: None,
1662                    forced: true,
1663                    pinned_run: Some(run),
1664                });
1665            }
1666            ActionDecision::Stale => {}
1667            ActionDecision::Requeue => {
1668                task.release_operator("choice-requeue", Some(&q.id));
1669                task.requeue();
1670            }
1671            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1672            ActionDecision::Done => task.succeed(),
1673            ActionDecision::Refuse(why) => {
1674                let _ =
1675                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1676                if task.operator_held() {
1677                    // A rejected answer does not release the operator's hold
1678                    // or reclassify it as recoverable by the conductor.
1679                    task.hold_reason = Some(match task.hold_reason.take() {
1680                        Some(reason) => format!("{reason}\n\n{why}"),
1681                        None => why,
1682                    });
1683                } else {
1684                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1685                    task.hold_machine(Some(why));
1686                }
1687                notices::raise(
1688                    Notice::warn(
1689                        &format!("action:{}", q.id),
1690                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1691                    )
1692                    .link(Link::Task {
1693                        id: task.id.clone(),
1694                    }),
1695                );
1696            }
1697        }
1698        task.mark_action_applied(&q.id);
1699        if completed {
1700            task.decision_effects.insert(
1701                q.id.clone(),
1702                format!("decision: {}", q.resolution().expect("answered action")),
1703            );
1704        }
1705        // The applied id travels with the transition, so a failed save loses
1706        // neither and the answer is acted on at the next poll.
1707        record(queue, &mut task);
1708        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1709            supersede_prior_runs(&task, home);
1710        }
1711        // Delivery is only a note of who has read the answer; the task's own
1712        // mark above is the authority. Best effort.
1713        let _ = questions.update_in(&q.id, &ownership, |r| {
1714            r.answer_delivered = true;
1715            Ok(())
1716        });
1717    }
1718}
1719
1720/// Whether something may still read the answer to `q`: a fresh lease, or the
1721/// asking seat still listed as active in its run (its CLI can outlive the
1722/// `magi ask` that was killed).
1723fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1724    let now = Timestamp::now();
1725    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1726        return true;
1727    }
1728    q.node != crate::conduct::NODE
1729        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1730            s.seats_active()
1731                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1732        })
1733}
1734
1735/// Retire an unanswered conductor question after its task no longer refers to
1736/// it. Conductor questions use the task id in `Question::run`, so run-based
1737/// cleanup cannot observe a manual release or completion.
1738///
1739/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1740/// own question also carries a `run`, and a run id that happens to collide
1741/// with some task's id is not this loop's business — only a conductor
1742/// question actually uses the task id that way. One `Questions::list()` scan
1743/// is taken up front and matched against the in-memory task set, rather than
1744/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1745fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1746    let tasks = queue.list();
1747    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1748    let by_id: std::collections::BTreeMap<&str, &Task> =
1749        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1750    let referenced: Vec<&str> = tasks
1751        .iter()
1752        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1753        .collect();
1754
1755    for mut question in questions.list_for_effects_in(&ownership) {
1756        if !question.status.open()
1757            || question.node != crate::conduct::NODE
1758            || questions.held_reply_in(&question.id, &ownership)
1759        {
1760            continue;
1761        }
1762        // Keep questions a task still names, including when the reference
1763        // moved to a dependent task.
1764        // Preserve even ambiguous references: retiring a possibly referenced
1765        // question is unsafe until the operator disambiguates it.
1766        if referenced
1767            .iter()
1768            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1769        {
1770            continue;
1771        }
1772        let Some(task) = by_id.get(question.run.as_str()) else {
1773            continue;
1774        };
1775        question.abandon(format!(
1776            "task {} no longer waits for this answer",
1777            task.short()
1778        ));
1779        if let Err(e) = questions.put_in(&mut question, &ownership) {
1780            tracing::warn!(
1781                "could not retire question {} for task {}: {e:#}",
1782                question.short(),
1783                task.short()
1784            );
1785        }
1786    }
1787}
1788
1789/// What a finished run tells the queue about the task it came from.
1790///
1791/// A struct rather than a fourth and fifth boolean argument: the two flags
1792/// answer different questions about the same run, and a call site passing
1793/// `(…, true, false)` is one transposition away from refunding attempts
1794/// forever.
1795#[derive(Debug, Clone, Copy)]
1796pub struct Verdict {
1797    /// Where the graph stopped.
1798    pub status: RunStatus,
1799    /// The run opened a pull request.
1800    pub left_pr: bool,
1801    /// At least one seat was lost to a rate limit.
1802    pub quota_hit: bool,
1803    /// The run parked at a node boundary because it was asked to.
1804    pub parked: bool,
1805    /// The run never produced a single candidate a judge could look at.
1806    ///
1807    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1808    /// still have another candidate worth judging, in which case the loss was
1809    /// not the reason nothing came of the run. This is `true` only when the
1810    /// implement wave ended with nothing viable at all.
1811    pub no_viable_candidates: bool,
1812}
1813
1814/// Record a finished run against the task it came from.
1815///
1816/// Kept pure and separate from the loop because this mapping *is* the retry
1817/// policy, and a policy that can only be exercised by spawning a graph is a
1818/// policy nobody checks. The table:
1819///
1820/// | run status                           | task becomes        | attempt spent |
1821/// |---------------------------------------|---------------------|---------------|
1822/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1823/// | `Merged`, `Ready`                      | `Done`               | yes          |
1824/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1825/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1826/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1827/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1828/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1829/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1830/// | `Blocked` with a PR                    | `Held`               | yes          |
1831/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1832/// | `VerifiedNoop`                          | `Held`               | yes          |
1833/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1834///
1835/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1836/// deliberately: every candidate agreeing there is nothing to write is not a
1837/// machine fact about a rate limit, it is an unverified claim about the
1838/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1839/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1840/// claim could be wrong (a misread instruction, a stale check), and closing
1841/// the task automatically on an implementer's say-so would be the exact
1842/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1843/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1844/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1845/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1846/// claim regardless of whether the one already-spent attempt is refunded, and
1847/// [`Task::release`] resets the count to zero anyway the moment a human looks
1848/// at the evidence and lets it run again.
1849///
1850/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1851/// twice, together. A quorum lost to rate limits is a property of the machine
1852/// and not of the task, so the attempt is refunded and a reset quota picks
1853/// the work up where it stopped — and that is just as true when every
1854/// implement seat lost the same race and `after_implement` bails with nothing
1855/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1856/// machine fact. The `no_viable_candidates` guard is what keeps that row
1857/// narrow: a `Failed` run that produced a real candidate which then lost for
1858/// some other reason still spends the attempt, exactly like the quorum lost
1859/// to judges that answered with the wrong shape is ordinary flakiness, and
1860/// refunding *that* takes the bound off the retry loop entirely: run e633
1861/// stalled with `quota: []` after two judges wrote unusable JSON, was
1862/// refunded, and the next attempt paid for a fresh hour-long implement wave
1863/// before it could fail the same way. `max_attempts` exists precisely so
1864/// that cannot repeat forever.
1865///
1866/// A non-terminal status means `execute` returned while the graph was still
1867/// mid-flight, which is a bug rather than a verdict; it is treated as a
1868/// failure so that a task cannot loop on it either.
1869///
1870/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1871/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1872pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1873    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1874}
1875
1876/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1877fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1878    // A parked run is the operator's own doing, and its work is intact on
1879    // disk. The task goes back in line with its attempt refunded so the next
1880    // loop resumes the same run - which `one_task` prefers over competing
1881    // again - and so that swapping the binary a few times cannot exhaust a
1882    // budget meant for agents that actually misbehaved.
1883    if verdict.parked {
1884        task.park(detail);
1885        return;
1886    }
1887    match verdict.status {
1888        RunStatus::Merged | RunStatus::Ready
1889            if task.pr_recovery.as_ref().is_some_and(|s| {
1890                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1891            }) =>
1892        {
1893            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()));
1894        }
1895        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1896        RunStatus::AlreadyInBase => task.already_landed(detail),
1897        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1898        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1899            task.stall(detail)
1900        }
1901        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1902        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1903        RunStatus::Blocked => task.fail(detail, max_attempts),
1904        RunStatus::VerifiedNoop => task.handed_off(detail),
1905        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1906    }
1907}
1908
1909/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1910/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1911/// itself has actually finished *and* its own last attempt is provably why:
1912/// this loads that run and requires `Merged`/`Ready` before touching
1913/// anything earlier in `runs`, since `Task::succeed` can also be called
1914/// directly on a task whose last attempt never landed at all.
1915///
1916/// Called right after whatever call set `task.status` to
1917/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1918/// `reclaim`'s, but also every other place a task can be closed by hand
1919/// without the loop ever settling it itself: `magi task done`
1920/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1921/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1922/// GitHub merge, say, exactly the workflow this repository's own
1923/// "Landing a run's winner by hand" documents — is just as much "this task's
1924/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1925/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1926/// forever, which is the exact backlog this status exists to clear. `pub`
1927/// for those two out-of-module callers; everything else about this stays
1928/// internal bookkeeping.
1929///
1930/// A run something is still actually driving is left alone: a
1931/// task cannot be `Done` while one of its *own* attempts is still in flight,
1932/// so a live one at this point can only be an unrelated process — a manual
1933/// `--resume` of this old, now-moot run — and rewriting under it would just
1934/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1935/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1936/// pair `run_report`/`run_detail` use for the same question elsewhere:
1937/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1938/// --resume` invoked by hand outside it, which `liveness` also checks via
1939/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1940/// (already terminal in some other way, or itself mid-run) is left untouched
1941/// too.
1942///
1943/// Best-effort, like the rest of this module's bookkeeping: a load or save
1944/// failure here is a `tracing::warn`, not a failed settle, and the next time
1945/// this same task's completion is recorded — or a daemon restart replays
1946/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1947/// separate reconciliation pass; if that gap ever matters in practice, one
1948/// can be added then.
1949///
1950/// `home` is a parameter, not the process-global [`crate::run::home`], for
1951/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1952/// calls this with `ui.home`, which is `crate::run::home()` in a real
1953/// process but a fixture's own directory under test — falling through to
1954/// the global there would read and write through whichever home some other
1955/// test in the same binary happened to pin into that `OnceLock` first, not
1956/// the run this call actually means.
1957pub fn supersede_prior_runs(task: &Task, home: &Path) {
1958    let now = Timestamp::now();
1959    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1960    // right behind a `Merged`/`Ready` verdict) from one set directly by
1961    // `magi task done`/its web equivalent/the conductor on a task whose last
1962    // recorded attempt never actually landed - that requires reading the
1963    // run itself, which is exactly what this does before trusting anything
1964    // in `runs` is safe to relabel.
1965    let last_run_succeeded = task
1966        .runs
1967        .last()
1968        .and_then(|id| RunState::load_under(id, home).ok())
1969        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1970    for id in task.superseded_attempts(last_run_succeeded) {
1971        let mut state = match RunState::load_under(id, home) {
1972            Ok(s) => s,
1973            Err(e) => {
1974                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1975                continue;
1976            }
1977        };
1978        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1979            continue;
1980        }
1981        let daemon_claims = is_working_on(home, id, now);
1982        if state.liveness(daemon_claims) == Liveness::Live {
1983            continue;
1984        }
1985        state.status = RunStatus::Superseded;
1986        if let Err(e) = state.save_under(home) {
1987            tracing::warn!("could not mark run {id} superseded: {e:#}");
1988        }
1989    }
1990}
1991
1992/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1993/// finish the moment it was called, because one of its earlier attempts was
1994/// still live then - a `magi run --resume` invoked by hand on an old run,
1995/// most likely.
1996///
1997/// That skip is correct at the time (rewriting under a run something is
1998/// still actively saving would just be undone), but a task only ever
1999/// reaches `Done` once, so without this nothing would ever look at it
2000/// again: if that manual process later ends anywhere other than
2001/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
2002/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
2003/// backlog this status exists to clear. Called on the same idle-only
2004/// cadence as [`janitor`], next to it rather than folded into it: this
2005/// walks `queue` and `janitor` never otherwise needs one.
2006///
2007/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
2008/// more than one attempt, every pass: each call is a handful of local file
2009/// reads bounded by that task's own attempt count, the same order of cost
2010/// [`clean::fold_due`] already pays scanning every run on disk on the same
2011/// cadence, and a task already fully resolved costs one failed liveness
2012/// check turned no-op the moment its lingering attempt is no longer live.
2013fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2014    for task in queue.list() {
2015        if task.status != TaskStatus::Done || task.runs.len() < 2 {
2016            continue;
2017        }
2018        supersede_prior_runs(&task, home);
2019    }
2020}
2021
2022/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
2023/// task ends up held.
2024///
2025/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
2026/// dead daemon never got back to) share this, so the two cannot drift into
2027/// disagreeing about which held tasks get a diagnostic.
2028fn settle_and_diagnose(
2029    task: &mut Task,
2030    verdict: Verdict,
2031    detail: &str,
2032    max_attempts: usize,
2033    state: &RunState,
2034) {
2035    let p = phrases(&state.config.graph.language);
2036    // Shared by normal completion and crash recovery, under the task claim.
2037    // No new attempt can own the task until the old driver has exited.
2038    if let Some(d) = &state.merge_decision {
2039        use crate::merge_decision as md;
2040        if task
2041            .execution_runs()
2042            .last()
2043            .is_some_and(|id| id != &state.id)
2044        {
2045            return;
2046        }
2047        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2048            task.succeed();
2049        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2050            if state.liveness(false) != Liveness::Dead {
2051                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2052                return;
2053            }
2054            let replacement = md::Replacement {
2055                question: d.question.clone(),
2056                run: state.id.clone(),
2057                pr: d.target.pr.clone(),
2058                agent: agent.to_owned(),
2059                context: format!(
2060                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2061                    d.target.pr,
2062                    state.id,
2063                    serde_json::to_string(&state.reviews).unwrap_or_default()
2064                ),
2065            };
2066            task.requeue();
2067            task.pr_recovery = None;
2068            task.review_of = None;
2069            task.replacement = Some(replacement);
2070        } else {
2071            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2072                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2073            } 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())) }));
2074        }
2075        task.mark_action_applied(&d.question);
2076        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2077            task.decision_effects
2078                .insert(d.question.clone(), format!("decision: {}", d.choice));
2079        }
2080        if let Some(pass) = state.passes.last() {
2081            task.record_pass_at(
2082                &state.id,
2083                pass.index,
2084                Some(pass.started_at),
2085                task.attempts,
2086                None,
2087            );
2088        }
2089        return;
2090    }
2091    if let Some(replacement) = &task.replacement
2092        && !state.parked
2093        && state.resource_block.is_none()
2094        && (state.viable().is_empty()
2095            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2096    {
2097        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)));
2098        return;
2099    }
2100    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2101        let mut agents: Vec<_> = state
2102            .quota
2103            .iter()
2104            .filter(|q| {
2105                q.cause == crate::agent::QuotaCause::Authentication
2106                    && state
2107                        .passes
2108                        .last()
2109                        .is_none_or(|pass| q.at >= pass.started_at)
2110            })
2111            .map(|q| q.agent.as_str())
2112            .collect();
2113        agents.sort_unstable();
2114        agents.dedup();
2115        if !agents.is_empty() {
2116            task.stall(detail);
2117            task.notice_cause("agent-authentication", None, None);
2118            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2119            return;
2120        }
2121    }
2122    let attempts_before = task.attempts;
2123    // A run that stopped because a shared resource stayed busy was never a
2124    // failure of the task or of an agent. Earlier nodes may have run; only
2125    // the blocked operation lacks a result. The attempt is
2126    // refunded and the task is held by the machine, under a reason `triage`
2127    // can re-check, so the same run resumes with the same agents once the
2128    // resource is free. A park request still wins (it is the operator's).
2129    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2130        task.notice_cause(
2131            &format!("resource:{}:{}", block.kind, block.node),
2132            None,
2133            None,
2134        );
2135        task.last_error = Some(detail.to_owned());
2136        task.diagnostic = None;
2137        task.attempts = task.attempts.saturating_sub(1);
2138        if block.kind == "agent authentication" {
2139            task.hold_machine(Some(format!(
2140                "[authentication] {}; no attempt was spent",
2141                block.detail
2142            )));
2143        } else if block.kind == "agent usage limit" {
2144            // Usage limits keep the existing cooldown-and-resume policy.
2145            if let Some(agent) = &state.config.graph.selected_implementer {
2146                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.")));
2147            } else {
2148                task.status = TaskStatus::Failed;
2149                task.last_error = Some(block.detail.clone());
2150            }
2151        } else if block.kind == "disk pressure" {
2152            task.hold_machine(Some(format!(
2153                "{}{}",
2154                crate::disk::RUNNING_PRESSURE,
2155                block.detail
2156            )));
2157        } else {
2158            task.hold_machine(Some(format!(
2159                "{}{}; no attempt was spent; resume to retry the affected operation",
2160                crate::cache::RESOURCE_HOLD,
2161                block.description()
2162            )));
2163        }
2164        if let Some(pass) = state.passes.last() {
2165            task.record_pass_at(
2166                &state.id,
2167                pass.index,
2168                Some(pass.started_at),
2169                attempts_before,
2170                None,
2171            );
2172        }
2173        return;
2174    }
2175    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2176        state.parked
2177            && state.status == RunStatus::Landing
2178            && state
2179                .pr_pushed_head
2180                .as_ref()
2181                .is_none_or(|h| h == &hold.head)
2182            && task.execution_runs().last() == Some(&state.id)
2183    }) {
2184        // Settlement and crash recovery share this idempotency key. A later
2185        // explicit resume is a new pass and may refund its own attempt once.
2186        let pass = state.passes.last().map_or(0, |p| p.index);
2187        if !task
2188            .passes
2189            .iter()
2190            .any(|p| p.run == state.id && p.pass_index == pass)
2191        {
2192            task.attempts = task.attempts.saturating_sub(1);
2193        }
2194        task.hold_machine(Some(format!(
2195            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2196            hold.question
2197        )));
2198        task.last_error = Some(detail.to_owned());
2199        task.diagnostic = None;
2200        task.record_pass_at(
2201            &state.id,
2202            pass,
2203            state.passes.last().map(|p| p.started_at),
2204            attempts_before,
2205            Some(crate::run::ParkCause::Question),
2206        );
2207        return;
2208    }
2209    let unresolved = task.hold_notice_cause.clone();
2210    if state.base_sync_blocked() {
2211        // No automatic retry may turn a retained sync stop into a new competition.
2212        task.hold_machine(Some(detail.to_owned()));
2213        task.last_error = Some(detail.to_owned());
2214    } else if !verdict.parked
2215        && task
2216            .pr_recovery
2217            .as_ref()
2218            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2219        && matches!(
2220            verdict.status,
2221            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2222        )
2223    {
2224        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2225            task.succeed();
2226        } else {
2227            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()));
2228        }
2229    } else if !verdict.parked
2230        && task.pr_recovery.is_some()
2231        && matches!(
2232            verdict.status,
2233            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2234        )
2235        && !verdict.quota_hit
2236    {
2237        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.")));
2238    } else {
2239        settle_in(task, verdict, detail, max_attempts, p);
2240    }
2241    if !verdict.parked
2242        && !verdict.quota_hit
2243        && matches!(
2244            verdict.status,
2245            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2246        )
2247    {
2248        task.recovery_failed(state);
2249    }
2250    if state.prep_failure.is_some() {
2251        // Minting a run whose candidates could not be prepared is not work
2252        // on a newly approved attempt. Keep the unresolved outcome anchor.
2253        task.hold_notice_cause = unresolved;
2254        task.startup_notice_cause("startup-candidates");
2255    }
2256    // Written here, where the refund (or not) is decided, so the history is a
2257    // fact and not a later guess from the run's status.
2258    if let Some(pass) = state.passes.last() {
2259        let parked = match &pass.end {
2260            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2261            _ => None,
2262        };
2263        task.record_pass_at(
2264            &state.id,
2265            pass.index,
2266            Some(pass.started_at),
2267            attempts_before,
2268            parked,
2269        );
2270    }
2271    if task.status == TaskStatus::Held {
2272        if state.base_sync_blocked() {
2273            task.base_sync_notice(state);
2274        } else if state.prep_failure.is_none() {
2275            task.notice_cause(
2276                label(verdict.status),
2277                Some(&state.id),
2278                state.passes.last().map(|p| p.index),
2279            );
2280        }
2281        task.diagnostic = diagnostic(state);
2282        note_open_question(task, &state.id, p);
2283    }
2284}
2285
2286/// If `task` is held with a `magi ask` question still open on `run`, name the
2287/// question in [`Task::hold_reason`] rather than leaving the hold reading
2288/// only [`describe`]'s run summary.
2289///
2290/// This is the shape task 20260928-191407-05fd left underspecified: an
2291/// implementer settled a verified no-op and filed a question for the
2292/// operator, and the hold that followed said nothing about the question
2293/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2294/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2295/// marker) and must keep seeing it unchanged.
2296///
2297/// Best-effort: an unreadable question store must not stop a run from
2298/// settling, so this is a no-op rather than a propagated error when
2299/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2300fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2301    let Some(home) = crate::run::try_home() else {
2302        return;
2303    };
2304    let open = Questions::at(home.join("questions")).open_for(run);
2305    let Some(q) = open.first() else {
2306        return;
2307    };
2308    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2309    decisions.sort_unstable();
2310    task.notice_cause(
2311        &format!("questions:{}", decisions.join(",")),
2312        Some(run),
2313        None,
2314    );
2315    let base = task.hold_reason.clone().unwrap_or_default();
2316    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2317}
2318
2319/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2320/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2321/// by some other means entirely, like a manual `magi run` resume that
2322/// finishes the graph outside the queue's bookkeeping.
2323///
2324/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2325/// `settle` is separate from `attempt`: a task recovered this way must land
2326/// exactly where a live daemon would have put it — the same policy table,
2327/// not a second one that quietly drifts from it — and that is only checkable
2328/// without spawning a real run.
2329fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2330    match last_run {
2331        Some(state) => {
2332            let verdict = Verdict {
2333                status: state.status,
2334                left_pr: state.pr.is_some(),
2335                quota_hit: state.quota.iter().any(|loss| {
2336                    state
2337                        .passes
2338                        .last()
2339                        .is_none_or(|pass| loss.at >= pass.started_at)
2340                }),
2341                parked: state.parked,
2342                no_viable_candidates: state.viable().is_empty(),
2343            };
2344            let detail = format!(
2345                "{}{}",
2346                phrases(&state.config.graph.language).recovered_running,
2347                describe(&state)
2348            );
2349            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2350        }
2351        None => {
2352            // No run, so no config of its own: `language` is the task's
2353            // repository's setting, read by the caller.
2354            let why = phrases(language).no_run_to_recover;
2355            task.last_error = Some(why.to_owned());
2356            // The phone shows `hold_reason`, so a task held by the machine
2357            // says why there too and not only in `last_error`.
2358            task.notice_cause("missing-run", None, None);
2359            task.hold_machine(Some(why.to_owned()));
2360        }
2361    }
2362}
2363
2364/// Find every task left at `running` that no live process is actually
2365/// driving, and settle each one against whatever its last run became.
2366///
2367/// # Why a claim is proof, not a guess
2368///
2369/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2370/// `running`, and the guard is held for the task's whole time in that status:
2371/// `attempt` does not return, and the loop does not move past the scope
2372/// holding the claim, until the run has settled. So a `running` task whose
2373/// lock is gone cannot have a live owner — this process or any other —
2374/// without needing a staleness threshold or a pid check the way
2375/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2376/// task that never got as far as `running` at all. Taking the claim here is
2377/// the whole test: it either fails, because something really does hold it
2378/// and the task is left alone, or it succeeds, which is the proof — and it is
2379/// kept for the rest of the decision so nothing else can start a competing
2380/// run while this one is being written.
2381///
2382/// Called on every poll, not only at startup, for the reason
2383/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2384/// keep noticing this, not only on the one morning it happened to restart.
2385fn reclaim_orphaned_running(
2386    queue: &Queue,
2387    max_attempts: usize,
2388    live_workers: &std::collections::BTreeSet<String>,
2389) -> Vec<String> {
2390    let mut reclaimed = Vec::new();
2391    for listed in queue.list() {
2392        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2393            continue;
2394        }
2395        let Ok(_claim) = queue.claim(&listed.id) else {
2396            continue;
2397        };
2398        // Re-read under the claim: a release or an edit landed by a human
2399        // between the listing above and the claim just taken must not be
2400        // clobbered by a decision based on the stale copy.
2401        let Ok(mut task) = queue.get(&listed.id) else {
2402            continue;
2403        };
2404        if task.status != TaskStatus::Running {
2405            continue;
2406        }
2407        let last_run = task
2408            .execution_runs()
2409            .last()
2410            .and_then(|id| RunState::load(id).ok());
2411        // `execute` normally abandons a run's own open questions the moment
2412        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2413        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2414        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2415        // with the question still `open`, because the process died before
2416        // reaching that call. `reclaim` itself stays pure on purpose (see its
2417        // own doc), so the same cleanup runs here instead, against the run
2418        // this reclaim is already reading. `settle_run` costs nothing when
2419        // `execute` already got there first.
2420        if let Some(state) = &last_run
2421            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2422        {
2423            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2424        }
2425        let language = if last_run.is_none() {
2426            language_of(&task, Path::new("."))
2427        } else {
2428            String::new()
2429        };
2430        reclaim(&mut task, last_run, max_attempts, &language);
2431        if task.status == TaskStatus::Done {
2432            supersede_prior_runs(&task, &crate::run::home());
2433        }
2434        record(queue, &mut task);
2435        reclaimed.push(task.id.clone());
2436    }
2437    reclaimed
2438}
2439
2440/// Find every run whose `run.json` is provably dead — every seat it still
2441/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2442/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2443/// not merely "no daemon claims it" — and fail it, clearing the leftover
2444/// active seats so the run stops reading as `implementing` (or whichever
2445/// node) forever.
2446///
2447/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2448/// `running`, using whatever `run.json` already says — but nothing in that
2449/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2450/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2451/// never got back to sits exactly where it was left: `active` full of seats
2452/// nobody will ever answer for, `status` stuck on whatever node was in
2453/// flight. `magi show` already tells an operator this in prose (`no live
2454/// daemon claims this run right now`); this is what makes that fact durable
2455/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2456/// stay stuck once nothing is driving it.
2457///
2458/// Runs on every poll, not only at startup, for the reason
2459/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2460/// daemon up for days must keep noticing a run some other, now-dead, daemon
2461/// left behind just as readily as one it trips over on the way up.
2462///
2463/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2464/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2465/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2466/// `runs` directory instead: `home` here is a parameter precisely so a test
2467/// can point it away from the operator's real history (see [`drive`]'s own
2468/// doc), and a scan that fell through to the global home anyway would walk
2469/// whichever directory some *other* process or test pinned into that
2470/// `OnceLock` first — mutating runs this call was never handed.
2471fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2472    reclaim_abandoned_runs_with(
2473        home,
2474        now,
2475        crate::proc::pid_status,
2476        crate::proc::process_started_at,
2477    )
2478}
2479
2480/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2481/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2482/// for the identical reason: this sweep's real damage (wiping a run's active
2483/// seats and failing it) has to be provable against an injected answer in a
2484/// test, not just the real process table.
2485fn reclaim_abandoned_runs_with<F, G>(
2486    home: &Path,
2487    now: Timestamp,
2488    query: F,
2489    identity: G,
2490) -> Vec<String>
2491where
2492    F: Fn(u32) -> Option<bool>,
2493    G: Fn(u32) -> Option<String>,
2494{
2495    let mut abandoned = Vec::new();
2496    for entry in std::fs::read_dir(home.join("runs"))
2497        .into_iter()
2498        .flatten()
2499        .flatten()
2500    {
2501        let id = entry.file_name().to_string_lossy().into_owned();
2502        if !crate::run::is_run_id(&id) {
2503            continue;
2504        }
2505        // Serialize the proof and save with claims and takeover: a new
2506        // execution must not be overwritten after the liveness observation.
2507        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2508            continue;
2509        };
2510        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2511        // that module's docs for why a run this cannot parse is left alone
2512        // rather than guessed at. A different schema number is not that: this
2513        // touches only `status` and `active`, never a field whose meaning a
2514        // schema bump changed, so an old record's values serve this exactly
2515        // as well as a current one's (see `clean::read_state`'s own doc for
2516        // the same reasoning applied to folding).
2517        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2518            continue;
2519        };
2520        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2521            continue;
2522        };
2523        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2524            continue;
2525        }
2526        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2527        // it", which is also the normal, healthy shape of a manual `magi
2528        // run` / `magi review` sharing this same home — this scan walks
2529        // every run on disk, not only ones this daemon itself started. Such
2530        // a run's active seats can legitimately sit past their own timeout
2531        // for a little while (the CLI finishing up, its result still being
2532        // collected) without the process driving it having died. `liveness`
2533        // is what actually tells the two apart, by corroborating
2534        // `driver_pid` against the process it names — see its own doc. Only
2535        // its strongest, provable answer licenses wiping this run's active
2536        // seats and failing it out from under whatever is still running it.
2537        let daemon_claims = is_working_on(home, &id, now);
2538        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2539            != crate::run::Liveness::Dead
2540        {
2541            continue;
2542        }
2543        state.abandon("daemon");
2544        if let Err(e) = state.save_under(home) {
2545            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2546            continue;
2547        }
2548        // This run never passes through `Runner::execute` again, so its end
2549        // is announced here.
2550        if let Some(notice) = notices::run_ended(&state) {
2551            notices::raise_in(home, notice);
2552        }
2553        // The seat that asked is gone for good now, exactly like any other
2554        // door `graph::Runner::settle_questions` closes the moment `status`
2555        // lands somewhere non-resumable - see that method's own doc. Nothing
2556        // else reaches this one before the next `janitor()` startup pass
2557        // (`clean::abandon_settled_questions`), and a daemon that stays up
2558        // for days must not leave an open question badging the operator
2559        // until it happens to restart.
2560        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2561            tracing::warn!("abandon questions for {id}: {e:#}");
2562        }
2563        abandoned.push(id);
2564    }
2565    abandoned
2566}
2567
2568#[derive(Debug, Clone, Serialize, Deserialize)]
2569struct TaskWorker {
2570    opts: Opts,
2571    queue: PathBuf,
2572    task: String,
2573    #[serde(default)]
2574    lane: PermitKind,
2575    #[serde(default)]
2576    standalone: bool,
2577}
2578
2579fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2580    Ok(crate::worker::active(home)?
2581        .into_iter()
2582        .filter(|job| job.kind == "task")
2583        .collect())
2584}
2585
2586fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2587    task_jobs(home)?
2588        .into_iter()
2589        .filter_map(
2590            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2591                Ok(request) if !request.standalone => Some(Ok(job)),
2592                Ok(_) => None,
2593                Err(error) => Some(Err(error.into())),
2594            },
2595        )
2596        .collect()
2597}
2598
2599/// Whether an independent scheduler can be controlled without its web parent.
2600#[must_use]
2601pub fn managed(home: &Path) -> bool {
2602    match crate::worker::active(home) {
2603        Err(error) => {
2604            tracing::error!("cannot determine scheduler ownership: {error:#}");
2605            true
2606        }
2607        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2608        Ok(_) => {
2609            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2610                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2611        }
2612    }
2613}
2614
2615/// Start a detached, singleton scheduler using this executable generation.
2616pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2617    anyhow::ensure!(
2618        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2619        "the scheduler is stopping; wait for retirement before starting it again"
2620    );
2621    crate::worker::spawn(
2622        home,
2623        "scheduler",
2624        "scheduler",
2625        serde_json::to_value(opts.absolute()?)?,
2626    )
2627    .await
2628}
2629
2630fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2631    home.join("worker-parks").join(format!("{}.json", job.id))
2632}
2633
2634fn request_task_park(
2635    home: &Path,
2636    job: &crate::worker::Job,
2637    cause: crate::run::ParkCause,
2638) -> Result<()> {
2639    let path = park_request_path(home, job);
2640    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2641    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2642    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2643}
2644
2645/// Stop dispatch immediately; only an explicit park reaches existing workers.
2646pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2647    if control == crate::worker::Control::Park {
2648        for job in owned_task_jobs(home)? {
2649            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2650        }
2651    }
2652    crate::worker::request(home, "scheduler", control)
2653}
2654
2655/// Replace the scheduler, leaving all active task and conversation jobs alone.
2656pub async fn restart_detached(home: &Path) -> Result<()> {
2657    let active = crate::worker::active(home)?;
2658    let prior = active.into_iter().find(|job| job.kind == "scheduler");
2659    if prior.is_none() && !managed(home) {
2660        return Ok(());
2661    }
2662    let opts: Opts = match prior {
2663        Some(job) => serde_json::from_value(job.payload)?,
2664        None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2665    };
2666    request_control(home, crate::worker::Control::Stop)?;
2667    loop {
2668        let reserved = crate::worker::active(home)?
2669            .iter()
2670            .any(|job| job.kind == "scheduler");
2671        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2672            break;
2673        }
2674        tokio::time::sleep(Duration::from_millis(100)).await;
2675    }
2676    spawn_detached(home, &opts).await?;
2677    Ok(())
2678}
2679
2680/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2681pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2682    let opts: Opts = serde_json::from_value(payload)?;
2683    let _ = home;
2684    serve_until(opts, Stop::new()).await
2685}
2686
2687/// Execute and settle one task with the queue claim owned by this process.
2688pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2689    let request: TaskWorker = serde_json::from_value(payload)?;
2690    let queue = Queue::at(request.queue);
2691    let key = format!("task:{}", request.task);
2692    let job = task_jobs(home)?
2693        .into_iter()
2694        .find(|job| job.key == key)
2695        .context("task worker reservation is missing")?;
2696    let park_path = park_request_path(home, &job);
2697    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2698    // our durable reservation. Never execute before that ownership hand-off.
2699    let _claim = loop {
2700        match queue.claim(&request.task) {
2701            Ok(claim) => break claim,
2702            // Only contention (the claim file exists) is worth waiting out; an
2703            // I/O failure must end this worker instead of pinning its lane.
2704            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2705                return Err(e.context("claim the task for its worker"));
2706            }
2707            Err(_) => {
2708                sweep_stale_claims(&queue, STALE_CLAIM);
2709                tokio::time::sleep(Duration::from_millis(50)).await;
2710            }
2711        }
2712    };
2713    let mut task = queue.get(&request.task)?;
2714    if !task.status.runnable()
2715        || (!request.standalone
2716            && request.lane
2717                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2718    {
2719        return Ok(());
2720    }
2721    let stop = Stop::new();
2722    let watcher = {
2723        let home = home.to_path_buf();
2724        let stop = stop.clone();
2725        let park_path = park_path.clone();
2726        tokio::spawn(async move {
2727            loop {
2728                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2729                    let cause = std::fs::read(&park_path)
2730                        .ok()
2731                        .and_then(|body| serde_json::from_slice(&body).ok())
2732                        .unwrap_or(crate::run::ParkCause::Operator);
2733                    stop.park(cause);
2734                    return;
2735                }
2736                tokio::time::sleep(Duration::from_millis(200)).await;
2737            }
2738        })
2739    };
2740    let quota = if request.standalone {
2741        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2742    } else {
2743        let status = Arc::new(Mutex::new(Status::new()));
2744        Box::pin(attempt(
2745            &request.opts,
2746            &queue,
2747            &status,
2748            &stop,
2749            crate::graph::Pause::new(),
2750            &mut task,
2751        ))
2752        .await
2753    };
2754    watcher.abort();
2755    let _ = std::fs::remove_file(park_path);
2756    persist_cooldown(home, &quota).await?;
2757    Ok(())
2758}
2759
2760/// Launch the standalone task worker with a claim-to-reservation handoff.
2761/// Returns only after the worker owns a durable execution reservation.
2762pub async fn spawn_claimed(
2763    home: &Path,
2764    opts: &Opts,
2765    queue: &Queue,
2766    task: &Task,
2767    claim: crate::queue::Claim,
2768) -> Result<crate::worker::Job> {
2769    let request = TaskWorker {
2770        opts: opts.absolute()?,
2771        queue: std::path::absolute(queue.root())?,
2772        task: task.id.clone(),
2773        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2774        standalone: true,
2775    };
2776    let job = crate::worker::spawn(
2777        home,
2778        "task",
2779        &format!("task:{}", task.id),
2780        serde_json::to_value(request)?,
2781    )
2782    .await?;
2783    drop(claim);
2784    Ok(job)
2785}
2786
2787/// Transfer a standalone caller's claim only after the detached worker is live,
2788/// then follow that worker to its final (non-automatically-retrying) outcome.
2789pub async fn run_detached_claimed(
2790    opts: &Opts,
2791    queue: &Queue,
2792    task: &mut Task,
2793    claim: crate::queue::Claim,
2794) -> Result<()> {
2795    let home = crate::run::home();
2796    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2797    loop {
2798        // Reconcile execution leases even without a scheduler. A dead worker
2799        // must become a reported failure, never an infinite persisted wait.
2800        crate::worker::active(&home)?;
2801        let current = crate::worker::get(&home, &job.id)?;
2802        if matches!(
2803            current.status,
2804            crate::worker::Status::Finished | crate::worker::Status::Failed
2805        ) {
2806            *task = queue.get(&task.id)?;
2807            anyhow::ensure!(
2808                current.status != crate::worker::Status::Failed,
2809                "task worker failed: {}",
2810                current.result.as_deref().unwrap_or("unknown failure")
2811            );
2812            return Ok(());
2813        }
2814        tokio::time::sleep(Duration::from_millis(200)).await;
2815    }
2816}
2817
2818async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2819    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2820        let _lease = loop {
2821            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2822                break lease;
2823            }
2824            tokio::time::sleep(Duration::from_millis(10)).await;
2825        };
2826        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2827            let path = home.join("task-quota-cooldown.json");
2828            let temporary = path.with_extension("json.tmp");
2829            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2830            std::fs::rename(temporary, path)?;
2831        }
2832    }
2833    Ok(())
2834}
2835
2836fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2837    match std::fs::read(home.join("task-quota-cooldown.json")) {
2838        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2839        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2840        Err(error) => Err(error.into()),
2841    }
2842}
2843
2844/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2845///
2846/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2847/// sets, so there is one loop body rather than two that drift apart the first
2848/// time the retry policy changes on only one of them.
2849pub async fn serve(opts: Opts) -> Result<()> {
2850    tracing::info!(
2851        "automatic update and restart requires magi web; standalone serve does not restart"
2852    );
2853    serve_until(opts, Stop::new()).await
2854}
2855
2856/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2857///
2858/// A stop retires dispatch promptly, including while a worker launch is being
2859/// acknowledged. Already reserved workers own their attempts independently and
2860/// finish with their started executable. Explicit park additionally forwards
2861/// durable park requests; neither scheduler retirement nor update does so.
2862///
2863/// While the queue is empty the stop is honoured within one wakeup rather than
2864/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2865/// caller that taps stop does not sit through the remainder of a sleep.
2866pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2867    let opts = opts.absolute()?;
2868    let home = crate::run::home();
2869    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2870        .context("another scheduler already owns this home")?;
2871    if let Some(reading) = read_status(&home)
2872        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2873    {
2874        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2875    }
2876    if !crate::worker::active(&home)?
2877        .iter()
2878        .any(|job| job.kind == "scheduler")
2879    {
2880        crate::worker::clear_control(&home, "scheduler")?;
2881    }
2882    std::fs::write(
2883        home.join("scheduler-options.json"),
2884        serde_json::to_vec(&opts)?,
2885    )?;
2886    let control = {
2887        let home = home.clone();
2888        let stop = stop.clone();
2889        tokio::spawn(async move {
2890            loop {
2891                match crate::worker::control(&home, "scheduler").ok().flatten() {
2892                    Some(crate::worker::Control::Park) => {
2893                        let _ = request_control(&home, crate::worker::Control::Park);
2894                        stop.park(crate::run::ParkCause::Operator);
2895                        break;
2896                    }
2897                    Some(crate::worker::Control::Stop) => {
2898                        stop.stop();
2899                        break;
2900                    }
2901                    None => {}
2902                }
2903                tokio::time::sleep(Duration::from_millis(100)).await;
2904            }
2905        })
2906    };
2907    let signal = {
2908        let stop = stop.clone();
2909        tokio::spawn(async move {
2910            if tokio::signal::ctrl_c().await.is_ok() {
2911                stop.stop();
2912                tracing::info!("scheduler shutdown requested; independent workers continue");
2913            }
2914        })
2915    };
2916
2917    let worktrees_root = opts
2918        .worktrees_root
2919        .clone()
2920        .unwrap_or_else(crate::run::default_worktree_root);
2921    let outcome = drive(
2922        &opts,
2923        &Queue::open(),
2924        &status_path(),
2925        &crate::run::home(),
2926        &worktrees_root,
2927        &stop,
2928    )
2929    .await;
2930
2931    signal.abort();
2932    control.abort();
2933    outcome
2934}
2935
2936/// The loop proper: setup, poll, teardown, with the queue and the status file
2937/// supplied rather than discovered.
2938///
2939/// All three of `home`, `worktrees_root` and the queue/status paths are
2940/// parameters rather than resolved here, for the same reason:
2941/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2942/// so a unit test that pinned it would fight every other test in the binary,
2943/// and a loop that resolved its own worktree bay could only be exercised
2944/// against the operator's real `~/wt/<repo>` - publishing over a live
2945/// daemon's status file, claiming tasks out of a live backlog, and, since
2946/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2947/// whatever the operator actually has on disk.
2948async fn drive(
2949    opts: &Opts,
2950    queue: &Queue,
2951    status_file: &Path,
2952    home: &Path,
2953    worktrees_root: &Path,
2954    stop: &Stop,
2955) -> Result<()> {
2956    // The status file is a *snapshot*, not a stream of events: a reader only
2957    // ever wants the latest values, and every tick rewrites the whole file
2958    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2959    // while an mpsc channel would force the loop to re-send unchanged fields on
2960    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2961    // for no gain. The lock is only ever held across a field assignment, never
2962    // across an await.
2963    let recovery_cfg = prepare(&opts.repo, opts).ok();
2964    let daemon_cfg = recovery_cfg
2965        .as_ref()
2966        .map(|c| c.daemon.clone())
2967        .unwrap_or_default();
2968    let reconciled = crate::driver::reconcile(home);
2969    if !reconciled.is_empty() {
2970        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2971    }
2972    let mut initial_status = Status::new();
2973    let owned = owned_task_jobs(home)?;
2974    initial_status.current = current_work(home, Timestamp::now())
2975        .into_iter()
2976        .filter(|current| {
2977            owned
2978                .iter()
2979                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2980        })
2981        .collect();
2982    initial_status.idle = initial_status.current.is_empty();
2983    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2984        recovery_cfg.as_ref(),
2985        daemon_cfg.max_deputies,
2986    ));
2987    let status = Arc::new(Mutex::new(initial_status));
2988    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2989    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2990
2991    // Read once at startup, not per task: how many runs this loop drives at
2992    // once is a property of the machine running it, not of whichever
2993    // repository a given task happens to name - see
2994    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
2995    // fact in the same sense the agent roster is.
2996    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2997
2998    tracing::info!(
2999        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3000        queue.root().display(),
3001        opts.poll.as_secs(),
3002        opts.max_attempts,
3003        concurrency,
3004        if daemon_cfg.pause_for_interrupts {
3005            ", interrupts enabled"
3006        } else {
3007            ""
3008        }
3009    );
3010
3011    let outcome = tokio::select! {
3012        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3013            max_concurrent: concurrency,
3014            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3015            recovery_cfg,
3016        }) => outcome,
3017        () = async {
3018            while !stop.stopped() {
3019                tokio::time::sleep(Duration::from_millis(25)).await;
3020            }
3021        } => {
3022            if stop.parking() {
3023                request_control(home, crate::worker::Control::Park)?;
3024            }
3025            Ok(())
3026        }
3027    };
3028
3029    stop.busy.store(0, Ordering::SeqCst);
3030    beat.abort();
3031    clear_status_at(status_file);
3032    outcome
3033}
3034
3035/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3036/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3037pub(crate) fn release_watch_settings_from_config(
3038    home: &Path,
3039    repo: &Path,
3040    cfg: &Config,
3041) -> (Vec<PathBuf>, u64) {
3042    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3043        .into_iter()
3044        .map(|r| r.path)
3045        .collect();
3046    // Repositories the daemon has worked in, wherever they live: a task may
3047    // name one outside `[repos] roots`, and its release PR must be watched too.
3048    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3049        .list()
3050        .into_iter()
3051        .map(|t| t.repo)
3052        .collect();
3053    let runs = home.join("runs");
3054    for id in crate::run::list_ids_in(&runs) {
3055        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3056            .ok()
3057            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3058            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3059        known.extend(repo);
3060    }
3061    for k in known {
3062        let k = k.canonicalize().unwrap_or(k);
3063        if k.join(".git").exists() && !paths.contains(&k) {
3064            paths.push(k);
3065        }
3066    }
3067    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3068    if !paths.contains(&own) {
3069        paths.push(own);
3070    }
3071    (paths, cfg.daemon.release_stall_minutes)
3072}
3073
3074/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3075const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3076
3077/// Refresh the status file on a fixed tick.
3078///
3079/// Separate from the loop because a run takes tens of minutes: a status file
3080/// written only between tasks would look stale for the whole of every run, and
3081/// a reader would report the daemon dead exactly while it was busiest.
3082async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3083    loop {
3084        tokio::time::sleep(HEARTBEAT).await;
3085        let snapshot = {
3086            let mut guard = lock(&status);
3087            guard.updated_at = Timestamp::now();
3088            guard.clone()
3089        };
3090        if let Err(e) = write_status_to(&path, &snapshot) {
3091            // A failed heartbeat must not take the daemon down: the loop is the
3092            // product, the status file is only the window onto it.
3093            tracing::warn!("could not refresh the daemon status file: {e:#}");
3094        }
3095    }
3096}
3097
3098/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3099/// if so, whether that wait is over.
3100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3101enum LandResume {
3102    /// The task's last run is not parked on a land approval; schedule it
3103    /// like any other candidate.
3104    NotLanding,
3105    /// Parked in `land`, waiting on a question nobody has answered yet.
3106    /// Left alone: attempting it now would only re-observe the same pull
3107    /// request and park again, spending a `gh` call on a decision that has
3108    /// not changed since the last time this was checked.
3109    StillWaiting,
3110    /// Parked in `land`, and the question is settled - answered or
3111    /// abandoned. Resuming this is the one kind of candidate that must not
3112    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3113    Ready,
3114}
3115
3116/// Classify a runnable candidate by whether it is parked on a land-merge
3117/// approval. Read-only - no claim taken, nothing written - so it is cheap
3118/// enough to call on every candidate, every poll.
3119fn land_resume_state(task: &Task) -> LandResume {
3120    let Some(run_id) = task.execution_runs().last() else {
3121        return LandResume::NotLanding;
3122    };
3123    let Ok(state) = RunState::load(run_id) else {
3124        return LandResume::NotLanding;
3125    };
3126    if !state.parked {
3127        return LandResume::NotLanding;
3128    }
3129    if state.status == RunStatus::Landing
3130        && state.land_approval.as_ref().is_some_and(|binding| {
3131            ask::Questions::open()
3132                .get_for_effects(&binding.question)
3133                .is_ok_and(|q| {
3134                    q.run == state.id
3135                        && q.resolution()
3136                            .as_deref()
3137                            .is_some_and(crate::merge_decision::stops)
3138                })
3139        })
3140    {
3141        return LandResume::Ready;
3142    }
3143    if !implementers_match(task, &state) {
3144        return LandResume::NotLanding;
3145    }
3146    // Parked in `land` on the merge approval, or at `merge` on the owner's
3147    // word about a title/body the posting gate withheld. Told apart by the
3148    // run's own record, not by a status both can share.
3149    let node = if state.status == RunStatus::Landing {
3150        land::APPROVAL_NODE
3151    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3152        crate::github_text::ASK_NODE
3153    } else {
3154        return LandResume::NotLanding;
3155    };
3156    let store = ask::Questions::open();
3157    let waiting = store
3158        .list_for_effects()
3159        .into_iter()
3160        .filter(|q| &q.run == run_id && q.node == node)
3161        .max_by(|a, b| a.id.cmp(&b.id));
3162    let Some(mut q) = waiting else {
3163        return LandResume::Ready;
3164    };
3165    if !q.status.open() {
3166        // Repair spends agent resources and must obey concurrency and quota
3167        // waits; only a merge/hold decision may use the decision-only lane.
3168        if q.resolution().as_deref() == Some(land::REPAIR) {
3169            return if state.liveness(false) == Liveness::Live {
3170                LandResume::StillWaiting
3171            } else {
3172                LandResume::NotLanding
3173            };
3174        }
3175        return LandResume::Ready;
3176    }
3177    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3178    // nobody ever answered; land's approval bypasses that wait entirely (see
3179    // `land::approval_gate`), so the same deadline has to be enforced here
3180    // instead, or `graph.answer_timeout` silently stops meaning anything for
3181    // a land approval and a run can sit `StillWaiting` forever with nobody
3182    // told to look at it.
3183    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3184    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3185    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3186        q.abandon(format!(
3187            "no answer within {}s of asking",
3188            timeout.as_secs().max(1)
3189        ));
3190        // If this can't be persisted, do not treat the wait as settled on a
3191        // guess: fall through and try again next poll.
3192        if store.put(&mut q).is_ok() {
3193            return LandResume::Ready;
3194        }
3195    }
3196    LandResume::StillWaiting
3197}
3198
3199/// How often the loop rechecks for new work while something it already
3200/// started is still running, rather than sleeping out the whole
3201/// [`Opts::poll`] interval.
3202///
3203/// Short on purpose: this is what lets a land-merge approval that comes back
3204/// while another task is mid-competition be noticed and resumed within a
3205/// fraction of a second, not within the next multi-second poll.
3206const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3207
3208/// How often [`poll`] rechecks the shared build cache against its cap at a
3209/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3210/// waiting for the queue to run dry.
3211///
3212/// A queue that never empties means the `janitor` call at the bottom of this
3213/// loop's fully-idle branch can go unreached for as long as the backlog
3214/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3215/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3216/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3217/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3218/// backlog of short tasks does not pay for that walk on every poll.
3219const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3220
3221/// State of [`poll`]'s own interrupt-scheduling sequence - see
3222/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3223/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3224/// both kept free of `Task`'s non-identity fields on purpose: every decision
3225/// here turns only on task ids and which ones are in flight, so the "never
3226/// more than one run at once" and "exactly one resume" invariants can be
3227/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3228/// queue - which is exactly the coverage this feature's first two attempts
3229/// were missing.
3230///
3231/// Persisted after every transition, so scheduler replacement preserves the
3232/// interrupt's exclusive turn and the interrupted task's priority resume.
3233#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3234enum Interrupt {
3235    /// No interrupt sequence in progress. Ordinary dispatch applies.
3236    Idle,
3237    /// `interrupt_task` is runnable and exactly one other run is in flight;
3238    /// `parked` names that one task's id. Dispatch is withheld from
3239    /// everyone, including `interrupt_task` itself, until it has left
3240    /// flight - only then is `interrupt_task` let through.
3241    ///
3242    /// `parked` is a `Vec` rather than a bare id for symmetry with
3243    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3244    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3245    /// when exactly one run is in flight, so it is guaranteed to hold
3246    /// exactly one entry in practice - see that branch's own doc for why
3247    /// more than one is deliberately never attempted.
3248    Parking {
3249        parked: Vec<String>,
3250        interrupt_task: String,
3251    },
3252    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3253    /// withheld from everyone until it leaves flight - merged, failed, held,
3254    /// it makes no difference - at which point the sequence moves to
3255    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3256    /// going straight to `Idle` would hand `parked` back to ordinary
3257    /// priority-order dispatch, where a higher-priority task filed in the
3258    /// meantime could start ahead of it.
3259    Running {
3260        parked: Vec<String>,
3261        interrupt_task: String,
3262    },
3263    /// `interrupt_task` left flight; `parked` still names the one run this
3264    /// sequence owes a resume. Dispatch is withheld from everyone except
3265    /// that task - see [`interrupt_gate`] - so the resume this feature
3266    /// promises is never raced by, or run alongside, an unrelated candidate.
3267    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3268    /// own doc on abandonment - the moment it is no longer runnable at all.
3269    Resuming { parked: Vec<String> },
3270}
3271
3272/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3273/// and `runnable` are read-only snapshots of this tick's reality, and the
3274/// only side effect the caller still owes the world is asking whichever
3275/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3276/// site.
3277///
3278/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3279/// accepted rather than a narrower type because that is what [`poll`] already
3280/// has on hand from [`runnable`], and building a second, smaller list on
3281/// every tick just to satisfy this signature would cost more than it proves.
3282///
3283/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3284/// back to a task they are waiting on no longer being [`runnable`] - held,
3285/// blocked, deleted, or finished by some other means entirely, all of which
3286/// an operator can do to a task sitting in the queue with no claim on it at
3287/// all, at any moment, interrupt sequence or not. Without this check the
3288/// sequence would wait forever for a dispatch that can never come, and
3289/// `interrupt_gate` would withhold every other task in the queue right along
3290/// with it - a single `magi task hold` on the wrong id turning into a
3291/// daemon that never dispatches anything again.
3292fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3293    match state {
3294        Interrupt::Idle => {
3295            // Not just "something to interrupt": exactly one thing. More
3296            // than one run in flight only happens above the default
3297            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3298            // one resume, never run alongside anything else" only because
3299            // it is only ever seeded with exactly one id - see
3300            // `Interrupt::Resuming`'s own doc on why releasing more than one
3301            // parked id back to ordinary dispatch cannot be made safe
3302            // against that same setting's own extra concurrency slots.
3303            // Waiting here for the herd to settle to one is the
3304            // simplification this feature's own constraints ask for rather
3305            // than a second concurrency model to reconcile with the first.
3306            if in_flight.len() != 1 {
3307                return Interrupt::Idle;
3308            }
3309            match runnable.iter().find(|t| t.interrupt) {
3310                Some(t) => Interrupt::Parking {
3311                    parked: in_flight.to_vec(),
3312                    interrupt_task: t.id.clone(),
3313                },
3314                None => Interrupt::Idle,
3315            }
3316        }
3317        Interrupt::Parking {
3318            parked,
3319            interrupt_task,
3320        } => {
3321            if in_flight.iter().any(|id| parked.contains(id)) {
3322                // Still waiting for what was in flight to actually stop.
3323                Interrupt::Parking {
3324                    parked,
3325                    interrupt_task,
3326                }
3327            } else if in_flight.contains(&interrupt_task) {
3328                Interrupt::Running {
3329                    parked,
3330                    interrupt_task,
3331                }
3332            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3333                // The parked run(s) are gone, but the interrupt task has not
3334                // been dispatched yet on this tick - `interrupt_gate` is
3335                // what lets it through next.
3336                Interrupt::Parking {
3337                    parked,
3338                    interrupt_task,
3339                }
3340            } else {
3341                // The interrupt task itself is no longer runnable - see this
3342                // function's own doc on abandonment. The parked run(s) still
3343                // get their guaranteed resume; there is simply no interrupt
3344                // to run ahead of them any longer.
3345                Interrupt::Resuming { parked }
3346            }
3347        }
3348        Interrupt::Running {
3349            parked,
3350            interrupt_task,
3351        } => {
3352            if in_flight.contains(&interrupt_task) {
3353                Interrupt::Running {
3354                    parked,
3355                    interrupt_task,
3356                }
3357            } else {
3358                // The interrupt task's own run reached a terminal status,
3359                // whichever one - this is the *only* trigger that moves the
3360                // sequence on, driven straight off the same in-flight
3361                // bookkeeping `poll` already reaps every tick, not a second,
3362                // independent poll of anything.
3363                Interrupt::Resuming { parked }
3364            }
3365        }
3366        Interrupt::Resuming { parked } => {
3367            if in_flight.iter().any(|id| parked.contains(id)) {
3368                // One of the parked runs has been dispatched - the resume
3369                // this sequence owed is fulfilled. Whatever else is left in
3370                // `parked` (ordinarily nothing, at the default concurrency
3371                // of one) rejoins ordinary priority-order dispatch, same as
3372                // any other runnable task.
3373                Interrupt::Idle
3374            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3375                Interrupt::Resuming { parked }
3376            } else {
3377                // Abandonment (see this function's own doc): nothing left in
3378                // `parked` is even runnable any longer.
3379                Interrupt::Idle
3380            }
3381        }
3382    }
3383}
3384
3385/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3386/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3387/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3388/// indistinguishable from any other runnable task - exactly the "off does
3389/// nothing" this feature promises.
3390fn advance_interrupt_tick(
3391    enabled: bool,
3392    state: Interrupt,
3393    in_flight: &[String],
3394    runnable: &[Task],
3395) -> Interrupt {
3396    if !enabled {
3397        return Interrupt::Idle;
3398    }
3399    advance_interrupt(state, in_flight, runnable)
3400}
3401
3402/// Which of this tick's runnable candidates the interrupt sequence actually
3403/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3404/// each half is assertable on its own: this is the half that keeps a
3405/// competition and an interrupt from ever running at the same moment.
3406fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3407    match state {
3408        Interrupt::Idle => candidates,
3409        Interrupt::Parking {
3410            parked,
3411            interrupt_task,
3412        } => {
3413            if in_flight.iter().any(|id| parked.contains(id)) {
3414                Vec::new()
3415            } else {
3416                candidates
3417                    .into_iter()
3418                    .filter(|t| &t.id == interrupt_task)
3419                    .collect()
3420            }
3421        }
3422        Interrupt::Running { .. } => Vec::new(),
3423        // At most one: even if `parked` names more than one id (more than
3424        // one run was in flight when the sequence began, only possible
3425        // above the default `max_concurrent_runs = 1`), only the first match
3426        // is offered. Capping this to a single candidate - not merely to
3427        // `parked`'s own ids - is what makes "exactly one resume, never two
3428        // dispatched together" true regardless of how many ordinary slots
3429        // happen to be free this tick.
3430        Interrupt::Resuming { parked } => candidates
3431            .into_iter()
3432            .find(|t| parked.contains(&t.id))
3433            .into_iter()
3434            .collect(),
3435    }
3436}
3437
3438/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3439/// bundled into one parameter so `poll`'s own signature stays readable -
3440/// see [`drive`]'s call site for where these are actually read.
3441struct DispatchLimits {
3442    /// How many *ordinary* candidates run at once. See
3443    /// [`crate::config::Daemon::max_concurrent_runs`].
3444    max_concurrent: usize,
3445    /// See [`crate::config::Daemon::pause_for_interrupts`].
3446    pause_for_interrupts: bool,
3447    recovery_cfg: Option<Config>,
3448}
3449
3450/// Which semaphore, if any, dispatching a candidate should draw its permit
3451/// from.
3452///
3453/// Pure and separate from [`poll`]'s loop body for the same reason
3454/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3455/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3456/// exactly the policy this feature adds, and a policy only exercisable by
3457/// running the whole loop is a policy nobody checks.
3458#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3459enum PermitKind {
3460    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3461    /// Checked first - a task can be both a land resume and marked
3462    /// [`Task::urgent`], and the resume's own "must not queue behind
3463    /// anything" guarantee takes precedence.
3464    None,
3465    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3466    /// (never in addition to trying) the ordinary pool. This is what lets
3467    /// an urgent task dispatch while every ordinary slot is already checked
3468    /// out, and what stops a second urgent task from opening a third run: it
3469    /// waits on this same one-slot semaphore rather than falling through to
3470    /// the ordinary one.
3471    Urgent,
3472    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3473    /// above.
3474    #[default]
3475    Ordinary,
3476}
3477
3478/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3479/// own boolean, already computed by the caller from [`land_resume_state`].
3480fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3481    if priority {
3482        PermitKind::None
3483    } else if urgent {
3484        PermitKind::Urgent
3485    } else {
3486        PermitKind::Ordinary
3487    }
3488}
3489
3490fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3491    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3492        (0usize, 0usize),
3493        |(ordinary, urgent), request| match request.lane {
3494            PermitKind::Ordinary => (ordinary + 1, urgent),
3495            PermitKind::Urgent => (ordinary, urgent + 1),
3496            PermitKind::None => (ordinary, urgent),
3497        },
3498    );
3499    (
3500        limit.saturating_sub(ordinary),
3501        1usize.saturating_sub(urgent),
3502    )
3503}
3504
3505struct DispatchClaim {
3506    task: Task,
3507    claim: crate::queue::Claim,
3508    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3509}
3510
3511/// Claim and re-read before choosing a lane: a queue listing may predate an
3512/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3513fn claim_dispatch(
3514    queue: &Queue,
3515    candidate: &Task,
3516    cooling_down: bool,
3517    ordinary: &Arc<tokio::sync::Semaphore>,
3518    urgent: &Arc<tokio::sync::Semaphore>,
3519) -> Option<DispatchClaim> {
3520    let Ok(claim) = queue.claim(&candidate.id) else {
3521        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3522        return None;
3523    };
3524    let task = match queue.get(&candidate.id) {
3525        Ok(t) if t.status.runnable() => t,
3526        Ok(_) => return None,
3527        Err(e) => {
3528            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3529            return None;
3530        }
3531    };
3532    let resume = land_resume_state(&task);
3533    if resume == LandResume::StillWaiting {
3534        return None;
3535    }
3536    let priority = resume == LandResume::Ready;
3537    if !priority && cooling_down {
3538        return None;
3539    }
3540    // Never borrow an ordinary slot when the single urgent slot is busy.
3541    // Keep scanning other candidates when either pool has no free slot.
3542    let permit = match permit_kind(priority, task.urgent) {
3543        PermitKind::None => None,
3544        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3545        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3546    };
3547    // Persist the dispatch order under the claim, before config discovery or
3548    // coordination waits can reorder concurrent starts.
3549    let stamp = Timestamp::now();
3550    let mut task = task;
3551    task.dispatched_at = Some(stamp);
3552    if let Err(e) = queue.modify(&task.id, |t| {
3553        t.dispatched_at = Some(stamp);
3554        true
3555    }) {
3556        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3557    }
3558    Some(DispatchClaim {
3559        task,
3560        claim,
3561        permit,
3562    })
3563}
3564
3565/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3566/// teardown and cannot skip the teardown on an early return.
3567///
3568/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3569/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3570/// land approval that has since been answered is dispatched outside that
3571/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3572/// the whole point of parking there is that it must not queue behind
3573/// whatever else the loop happens to be running, even at the default of one.
3574/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3575/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3576/// these exemptions is still subject to the interrupt gate below, urgent
3577/// included: a land-resume or urgent candidate is exactly as much "something
3578/// else running" as an ordinary one from the interrupt sequence's point of
3579/// view, and letting either slip through while a run is being parked, or
3580/// while the interrupt task itself has the floor, is precisely the second
3581/// run 75dd's own "at most one run, ever, at once" guarantee must never
3582/// allow - see [`Interrupt`]'s own doc.
3583#[derive(Serialize, Deserialize)]
3584struct ServiceWorker {
3585    opts: Opts,
3586    queue: PathBuf,
3587    worktrees_root: PathBuf,
3588    operation: String,
3589}
3590
3591fn load_conductor(home: &Path) -> Result<Conductor> {
3592    match std::fs::read(home.join("conductor-state.json")) {
3593        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3594        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3595        Err(error) => Err(error.into()),
3596    }
3597}
3598
3599fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3600    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3601        .into_iter()
3602        .map(|c| c.task)
3603        .collect();
3604    let stalled = stalled_tasks(queue, home, Timestamp::now());
3605    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3606    let finished = finished_tasks(queue)
3607        .into_iter()
3608        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3609        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3610        .collect();
3611    let queued = queued_tasks(queue)
3612        .into_iter()
3613        .filter(|t| !live.contains(&t.id))
3614        .collect();
3615    (queued, stalled, finished)
3616}
3617
3618// Separate latest dispatch and worker receipts expose version handoff and skips
3619// without erasing the last completed scan or treating observations as authority.
3620fn retention_service_receipt(
3621    home: &Path,
3622    operation: &str,
3623    phase: &str,
3624    outcome: &str,
3625    detail: &str,
3626    cfg: Option<&Config>,
3627) {
3628    if !matches!(operation, "housekeeping" | "disk-pressure") {
3629        return;
3630    }
3631    let receipt = serde_json::json!({"checked_at": Timestamp::now(),
3632        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
3633        "operation": operation, "outcome": outcome, "detail": detail,
3634        "auto_fold": cfg.map(|c| c.disk.auto_fold),
3635        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
3636    if let Err(error) = crate::fold_evidence::atomic_write(
3637        &home.join(format!("source-eviction-{operation}-{phase}.json")),
3638        &serde_json::to_vec(&receipt).expect("service receipt"),
3639    ) {
3640        tracing::warn!("retention service receipt failed: {error:#}");
3641    }
3642}
3643
3644async fn start_service(
3645    home: &Path,
3646    opts: &Opts,
3647    queue: &Queue,
3648    worktrees_root: &Path,
3649    operation: &str,
3650    cfg: Option<&Config>,
3651    busy: bool,
3652) -> Result<()> {
3653    // Fetch policy is live configuration, unlike question recovery capacity.
3654    // Reload before both cadence and eligibility, including disabled -> enabled.
3655    let fetch_cfg = if operation == "fetch" {
3656        match prepare(&opts.repo, opts) {
3657            Ok(cfg) => Some(cfg),
3658            Err(error) => {
3659                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3660                return Ok(());
3661            }
3662        }
3663    } else {
3664        None
3665    };
3666    let cfg = fetch_cfg.as_ref().or(cfg);
3667    let ticks = home.join("service-ticks");
3668    std::fs::create_dir_all(&ticks)?;
3669    let receipt = ticks.join(format!("daemon-{operation}"));
3670    let last = std::fs::read(&receipt)
3671        .ok()
3672        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3673    let interval = match operation {
3674        "disk-pressure" => 30,
3675        "cache" => CACHE_CHECK_INTERVAL_SECS,
3676        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3677        _ => opts.poll.as_secs().max(1),
3678    };
3679    let now = Timestamp::now();
3680    if !cache_check_due(last, now, interval) {
3681        retention_service_receipt(
3682            home,
3683            operation,
3684            "dispatch",
3685            "skipped",
3686            "cadence not due",
3687            cfg,
3688        );
3689        return Ok(());
3690    }
3691    let key = format!("service:daemon-{operation}");
3692    if crate::worker::active(home)?
3693        .iter()
3694        .any(|job| job.key == key)
3695    {
3696        retention_service_receipt(
3697            home,
3698            operation,
3699            "dispatch",
3700            "skipped",
3701            "service worker already active",
3702            cfg,
3703        );
3704        return Ok(());
3705    }
3706    let eligible = match operation {
3707        "conductor" => {
3708            let (queued, stalled, finished) = conductor_work(queue, home);
3709            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3710                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3711        }
3712        "maintenance" => Questions::at(home.join("questions"))
3713            .list_for_effects()
3714            .iter()
3715            .any(|q| {
3716                q.chosen_action().is_some_and(|action| action.maintenance())
3717                    && !home
3718                        .join("choice-actions")
3719                        .join(format!("{}.json", q.id))
3720                        .exists()
3721            }),
3722        "housekeeping" => !busy && runnable(queue).is_empty(),
3723        "cache" => {
3724            !busy
3725                && !runnable(queue).is_empty()
3726                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3727        }
3728        "disk-pressure" => busy,
3729        "fetch" => {
3730            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3731        }
3732        _ => false,
3733    };
3734    if !eligible {
3735        retention_service_receipt(
3736            home,
3737            operation,
3738            "dispatch",
3739            "skipped",
3740            if operation == "housekeeping" {
3741                "active work or runnable task queue"
3742            } else {
3743                "no active work; idle housekeeping owns scan"
3744            },
3745            cfg,
3746        );
3747        return Ok(());
3748    }
3749    retention_service_receipt(
3750        home,
3751        operation,
3752        "dispatch",
3753        "launching",
3754        "eligible and cadence due",
3755        cfg,
3756    );
3757    let request = ServiceWorker {
3758        opts: opts.absolute()?,
3759        queue: std::path::absolute(queue.root())?,
3760        worktrees_root: std::path::absolute(worktrees_root)?,
3761        operation: operation.to_owned(),
3762    };
3763    if let Err(error) =
3764        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3765    {
3766        retention_service_receipt(
3767            home,
3768            operation,
3769            "dispatch",
3770            "error",
3771            &format!("worker launch: {error:#}"),
3772            cfg,
3773        );
3774        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3775    }
3776    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3777    Ok(())
3778}
3779
3780/// Finite maintenance jobs survive scheduler replacement without duplicating
3781/// agent calls or cancelling an operation between its effect and receipt.
3782pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3783    let request: ServiceWorker = serde_json::from_value(payload)?;
3784    let opts = &request.opts;
3785    let queue = Queue::at(request.queue);
3786    let questions = Questions::at(home.join("questions"));
3787    match request.operation.as_str() {
3788        "maintenance" => apply_maintenance_choices(&queue, &questions, home).await,
3789        "conductor" => {
3790            let path = home.join("conductor-state.json");
3791            let mut conductor = load_conductor(home)?;
3792            let (queued, stalled, finished) = conductor_work(&queue, home);
3793            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3794                && conductor.worth_a_look(&queue, &stalled, &finished)
3795            {
3796                let cfg = prepare(&opts.repo, opts)?;
3797                conductor
3798                    .maybe_run(
3799                        &cfg,
3800                        &opts.repo,
3801                        &queue,
3802                        &questions,
3803                        home,
3804                        &queued,
3805                        &stalled,
3806                        &finished,
3807                        opts.max_attempts,
3808                    )
3809                    .await;
3810                let temporary = path.with_extension("json.tmp");
3811                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3812                std::fs::rename(temporary, path)?;
3813            }
3814        }
3815        "fetch" => {
3816            let cfg = prepare(&opts.repo, opts)?;
3817            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3818                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3819                tracing::debug!("fetch origins: {outcome:?}");
3820            }
3821        }
3822        "cache" => {
3823            if task_jobs(home)?.is_empty() {
3824                let mut checked = None;
3825                maybe_prune_cache_between_runs(
3826                    &opts.repo,
3827                    opts,
3828                    home,
3829                    &Stop::new(),
3830                    &mut checked,
3831                    Timestamp::now(),
3832                )
3833                .await;
3834            }
3835        }
3836        "disk-pressure" => {
3837            if let Ok(cfg) = prepare(&opts.repo, opts) {
3838                retention_service_receipt(
3839                    home,
3840                    "disk-pressure",
3841                    "worker",
3842                    "running",
3843                    "retention sweep",
3844                    Some(&cfg),
3845                );
3846                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3847                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3848                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3849                }
3850                for current in current_work(home, Timestamp::now()) {
3851                    if let Ok(state) = RunState::load_under(&current.run, home)
3852                        && let Some(reason) = disk_gate(&state.repo, &state.config)
3853                    {
3854                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
3855                            job.key.strip_prefix("task:") == Some(current.task.as_str())
3856                        }) {
3857                            request_task_park(
3858                                home,
3859                                &job,
3860                                crate::run::ParkCause::Interrupt {
3861                                    reason: reason.clone(),
3862                                },
3863                            )?;
3864                        }
3865                        notices::raise_in(
3866                            home,
3867                            Notice::warn(
3868                                "disk:pressure",
3869                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
3870                            ),
3871                        );
3872                    }
3873                }
3874            } else {
3875                retention_service_receipt(
3876                    home,
3877                    "disk-pressure",
3878                    "worker",
3879                    "error",
3880                    "configuration could not be loaded",
3881                    None,
3882                );
3883            }
3884        }
3885        "housekeeping" => {
3886            if task_jobs(home)?.is_empty() {
3887                match prepare(&opts.repo, opts) {
3888                    Ok(cfg) => {
3889                        retention_service_receipt(
3890                            home,
3891                            "housekeeping",
3892                            "worker",
3893                            "running",
3894                            "retention sweep",
3895                            Some(&cfg),
3896                        );
3897                        crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3898                    }
3899                    Err(error) => retention_service_receipt(
3900                        home,
3901                        "housekeeping",
3902                        "worker",
3903                        "error",
3904                        &format!("configuration: {error:#}"),
3905                        None,
3906                    ),
3907                }
3908                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
3909                resweep_superseded_attempts(&queue, home);
3910                triage_held(&queue, home, opts).await;
3911            } else {
3912                retention_service_receipt(
3913                    home,
3914                    "housekeeping",
3915                    "worker",
3916                    "skipped",
3917                    "task worker became active",
3918                    None,
3919                );
3920            }
3921        }
3922        operation => bail!("unknown daemon service {operation}"),
3923    }
3924    Ok(())
3925}
3926
3927/// Only a different request under the same key is a dispatch handoff race.
3928/// Our own unacknowledged reservation is a startup failure, not competing work:
3929/// stop dispatch without fencing it, so an already detached child may still run.
3930fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
3931    let key = format!("task:{}", request.task);
3932    let payload = serde_json::to_value(request)?;
3933    if crate::worker::active(home)?
3934        .iter()
3935        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
3936    {
3937        tracing::warn!(
3938            "task {} acquired a competing worker reservation: {error:#}",
3939            crate::run::short_of(&request.task)
3940        );
3941        return Ok(());
3942    }
3943    tracing::error!("task worker startup stopped dispatch: {error:#}");
3944    notices::raise_in(
3945        home,
3946        Notice::error(
3947            "loop:worker-startup",
3948            // Startup diagnostics may contain private child-process details;
3949            // keep them in the local error/log rather than the chat or notifier.
3950            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),
3951        ).link(Link::Task { id: request.task.clone() }),
3952    );
3953    Err(error).with_context(|| {
3954        format!(
3955            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
3956            crate::run::short_of(&request.task)
3957        )
3958    })
3959}
3960
3961async fn poll(
3962    opts: &Opts,
3963    queue: &Queue,
3964    status: &Arc<Mutex<Status>>,
3965    home: &Path,
3966    worktrees_root: &Path,
3967    stop: &Stop,
3968    limits: DispatchLimits,
3969) -> Result<()> {
3970    let mut attempted = Vec::new();
3971    let mut settling_once_services = false;
3972    let interrupt_path = home.join("scheduler-interrupt.json");
3973    let mut interrupt = match std::fs::read(&interrupt_path) {
3974        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
3975        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
3976        Err(error) => return Err(error.into()),
3977    };
3978    let mut previous = std::collections::BTreeSet::<String>::new();
3979    while !stop.stopped() {
3980        let jobs: Vec<_> = crate::worker::active(home)?
3981            .into_iter()
3982            .filter(|job| job.kind == "task")
3983            .collect();
3984        let requests: Vec<_> = jobs
3985            .iter()
3986            .map(|job| {
3987                serde_json::from_value::<TaskWorker>(job.payload.clone())
3988                    .with_context(|| format!("read live task worker {}", job.id))
3989            })
3990            .collect::<Result<_>>()?;
3991        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
3992        let owned: std::collections::BTreeSet<_> = requests
3993            .iter()
3994            .filter(|r| !r.standalone)
3995            .map(|r| r.task.clone())
3996            .collect();
3997        let current: Vec<_> = requests
3998            .iter()
3999            .zip(&jobs)
4000            .filter(|(request, _)| !request.standalone)
4001            .map(|(request, job)| Current {
4002                worker: Some(job.id.clone()),
4003                task: request.task.clone(),
4004                run: queue
4005                    .get(&request.task)
4006                    .ok()
4007                    .and_then(|task| task.execution_runs().last().cloned())
4008                    .unwrap_or_default(),
4009            })
4010            .collect();
4011        {
4012            let mut snapshot = lock(status);
4013            snapshot.polls += 1;
4014            snapshot.completed += previous.difference(&owned).count();
4015            snapshot.current = current;
4016            snapshot.idle = owned.is_empty();
4017        }
4018        previous = owned.clone();
4019        stop.busy.store(owned.len(), Ordering::SeqCst);
4020
4021        // Slots are reconstructed from durable reservations and OS-held worker
4022        // leases, not this scheduler's lifetime or mutable task urgency.
4023        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4024        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4025        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4026        let mut permits = Vec::new();
4027        sweep_stale_claims(queue, STALE_CLAIM);
4028        reclaim_orphaned_running(queue, opts.max_attempts, &live);
4029        reclaim_abandoned_runs(home, Timestamp::now());
4030        let questions = Questions::at(home.join("questions"));
4031
4032        // Deterministic: no model, run before the conductor sees anything so
4033        // its input reflects the queue's current, already-resolved state.
4034        crate::task_chat::sweep(
4035            queue,
4036            &crate::talk::Talks::at(home.join("talks")),
4037            &questions,
4038            home,
4039        );
4040        if let Err(error) = crate::task_inquiry::Outbox::at(home)
4041            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4042        {
4043            tracing::warn!("task inquiry delivery remains pending: {error:#}");
4044        }
4045        repair_choice_offers(&questions);
4046        resolve_blockers(queue, &questions);
4047        apply_task_choice_actions(queue, &questions, home);
4048        triage::apply_answers(queue, &questions);
4049        reconcile_task_questions(queue, &questions);
4050        let talks = crate::talk::Talks::at(home.join("talks"));
4051        crate::chat_notify::sweep(queue, &talks, home);
4052        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4053        crate::chat_watch::sweep(home, &talks);
4054        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4055            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4056        }
4057        let mut turns = tokio::task::JoinSet::new();
4058        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4059        // start_turns dispatches detached turns; no paid work lives in this set.
4060        while turns.join_next().await.is_some() {}
4061
4062        crate::consult::start_services(
4063            home,
4064            &opts.repo,
4065            limits.recovery_cfg.as_ref(),
4066            opts.config.as_deref(),
4067        )
4068        .await?;
4069        for operation in [
4070            "conductor",
4071            "maintenance",
4072            "housekeeping",
4073            "disk-pressure",
4074            "cache",
4075            "fetch",
4076        ] {
4077            // Once an idle --once drain starts settling services, subsequent
4078            // scans only consume their effects. An expired cadence receipt
4079            // must not start another service and keep the drain alive.
4080            if settling_once_services {
4081                break;
4082            }
4083            start_service(
4084                home,
4085                opts,
4086                queue,
4087                worktrees_root,
4088                operation,
4089                limits.recovery_cfg.as_ref(),
4090                !live.is_empty(),
4091            )
4092            .await?;
4093        }
4094        let latest = crate::worker::active(home)?;
4095        if latest.iter().any(|job| job.key == "service:daemon-cache")
4096            || latest
4097                .iter()
4098                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4099        {
4100            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4101            continue;
4102        }
4103        let candidates: Vec<Task> = runnable(queue)
4104            .into_iter()
4105            .filter(|task| !live.contains(&task.id))
4106            .filter(|task| !opts.once || !attempted.contains(&task.id))
4107            .collect();
4108        let in_flight: Vec<_> = owned.iter().cloned().collect();
4109        let prior_interrupt = std::mem::discriminant(&interrupt);
4110        interrupt = advance_interrupt_tick(
4111            limits.pause_for_interrupts,
4112            interrupt,
4113            &in_flight,
4114            &candidates,
4115        );
4116        // Same-variant transitions preserve their identities. Only an actual
4117        // transition needs a durable write, atomically before sending controls.
4118        if prior_interrupt != std::mem::discriminant(&interrupt) {
4119            let temporary = interrupt_path.with_extension("json.tmp");
4120            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4121            std::fs::rename(temporary, &interrupt_path)?;
4122        }
4123        if let Interrupt::Parking {
4124            parked,
4125            interrupt_task,
4126        } = &interrupt
4127        {
4128            for job in jobs.iter().filter(|job| {
4129                parked
4130                    .iter()
4131                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4132            }) {
4133                if crate::worker::control(home, &job.key)?.is_none() {
4134                    request_task_park(
4135                        home,
4136                        job,
4137                        crate::run::ParkCause::Interrupt {
4138                            reason: format!(
4139                                "task {} asked to run first",
4140                                crate::run::short_of(interrupt_task)
4141                            ),
4142                        },
4143                    )?;
4144                }
4145            }
4146        }
4147        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4148        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4149        let mut started = false;
4150        let mut resync = false;
4151        for candidate in candidates {
4152            if stop.stopped() {
4153                break;
4154            }
4155            let Some(DispatchClaim {
4156                task,
4157                claim,
4158                permit,
4159            }) = claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem)
4160            else {
4161                continue;
4162            };
4163            if crate::worker::active(home)?
4164                .iter()
4165                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4166            {
4167                drop(claim);
4168                resync = true;
4169                break;
4170            }
4171            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4172            let request = TaskWorker {
4173                opts: opts.absolute()?,
4174                queue: std::path::absolute(queue.root())?,
4175                task: task.id.clone(),
4176                lane,
4177                standalone: false,
4178            };
4179            // Keep the claim until spawn acknowledges the worker's durable
4180            // reservation. The worker then claims and re-reads before attempt.
4181            if let Err(error) = crate::worker::spawn(
4182                home,
4183                "task",
4184                &format!("task:{}", task.id),
4185                serde_json::to_value(&request)?,
4186            )
4187            .await
4188            {
4189                task_worker_spawn_error(home, &request, error)?;
4190                drop(claim);
4191                resync = true;
4192                break;
4193            }
4194            drop(claim);
4195            permits.extend(permit);
4196            attempted.push(task.id);
4197            started = true;
4198        }
4199        if started || resync {
4200            continue;
4201        }
4202        if owned.is_empty() && opts.once {
4203            settling_once_services = true;
4204            // These finite services can own queue claims or publish answers.
4205            // A skipped claim is not an idle queue until they have finished;
4206            // scan again afterwards so their changes are actually scheduled.
4207            if crate::worker::active(home)?.iter().any(|job| {
4208                job.kind == "daemon-service"
4209                    && matches!(
4210                        job.key.as_str(),
4211                        "service:daemon-housekeeping"
4212                            | "service:daemon-conductor"
4213                            | "service:daemon-maintenance"
4214                    )
4215            }) {
4216                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4217                continue;
4218            }
4219            break;
4220        }
4221        stop.idle(if live.is_empty() {
4222            opts.poll
4223        } else {
4224            RECHECK_WHILE_BUSY.min(opts.poll)
4225        })
4226        .await;
4227    }
4228    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4229    // every queue claim and Runner driver lease through outcome settlement.
4230    stop.busy.store(0, Ordering::SeqCst);
4231    Ok(())
4232}
4233
4234/// A maintenance pass may briefly own the same record while a worker starts.
4235/// Wait without blocking the executor or charging an agent attempt, then read
4236/// ownership again under the acquired lock. Other I/O failures still fail closed.
4237async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4238    let busy = |error: &anyhow::Error| {
4239        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4240            error.kind() == std::io::ErrorKind::WouldBlock
4241                || cfg!(windows) && error.raw_os_error() == Some(33)
4242        })
4243    };
4244    match crate::pr_head::owner_lock(home, id) {
4245        Ok(lock) => return Ok(lock),
4246        Err(error) if busy(&error) => {}
4247        Err(error) => return Err(error),
4248    }
4249    let wait = RunState::load_under(id, home)?
4250        .config
4251        .graph
4252        .timeout_resource_wait;
4253    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4254}
4255
4256/// Historical successors do not revoke a still-resumable public owner. Scan
4257/// under the same lock as publication/driver claims, and fail closed on unknown
4258/// history before spending another attempt.
4259async fn public_resume_owner(
4260    home: &Path,
4261    runs: &[String],
4262    repo: &Path,
4263) -> Result<Option<RunState>> {
4264    let mut owner = None;
4265    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4266        let _lock = resume_owner_lock(home, id).await?;
4267        let state = RunState::load_under(id, home)?;
4268        if state.released()
4269            || state.retired_to.is_some()
4270            || state.pr_taken_over_by.is_some()
4271            || !crate::handover::landing_checkpoint(&state)
4272        {
4273            continue;
4274        }
4275        anyhow::ensure!(
4276            crate::git::toplevel(&state.repo).await?.canonicalize()?
4277                == crate::git::toplevel(repo).await?.canonicalize()?,
4278            "public owner repository differs; inspect run lineage"
4279        );
4280        anyhow::ensure!(
4281            owner.is_none(),
4282            "multiple retained public owners; inspect run lineage"
4283        );
4284        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4285            anyhow::bail!(reason.diagnostic(&state));
4286        }
4287        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4288        anyhow::ensure!(
4289            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4290            "public owner's driver is live or unknown; wait before retrying"
4291        );
4292        owner = Some(state);
4293    }
4294    Ok(owner)
4295}
4296
4297/// Run one claimed task to a terminal status and record the outcome.
4298///
4299/// Every transition is flushed to the queue as it happens, so the state on disk
4300/// is what actually occurred rather than what this process still intends to
4301/// write.
4302async fn attempt(
4303    opts: &Opts,
4304    queue: &Queue,
4305    status: &Arc<Mutex<Status>>,
4306    stop: &Stop,
4307    interrupt_pause: crate::graph::Pause,
4308    task: &mut Task,
4309) -> Vec<QuotaLoss> {
4310    let repo = repo_for(task, &opts.repo);
4311    tracing::info!(
4312        "task {} — {} (repo {})",
4313        task.short(),
4314        task.title,
4315        repo.display()
4316    );
4317
4318    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4319        Ok(owner) => owner,
4320        Err(e) => {
4321            task.hold_machine(Some(format!(
4322                "Cannot verify existing public owner: {e:#}; no attempt started."
4323            )));
4324            record(queue, task);
4325            return Vec::new();
4326        }
4327    };
4328    let resume_runs = public_owner
4329        .as_ref()
4330        .map(|s| vec![s.id.clone()])
4331        .unwrap_or_else(|| task.execution_runs().to_vec());
4332
4333    // A stop spends no agent resources and uses the saved landing owner.
4334    // Current roster edits, missing attachments or a failed config fetch must
4335    // never turn it into a new implementation, or prevent a PR from closing.
4336    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4337        && previous
4338            .merge_decision
4339            .as_ref()
4340            .is_some_and(|decision| !decision.closed)
4341        && previous.status != RunStatus::Landing
4342        && !crate::merge_decision::resumable_hold(&previous)
4343    {
4344        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)));
4345        record(queue, task);
4346        return Vec::new();
4347    }
4348    let stop_owner = resume_runs
4349        .last()
4350        .and_then(|id| RunState::load(id).ok())
4351        .filter(|state| {
4352            crate::merge_decision::resumable_hold(state)
4353                || state.status == RunStatus::Landing
4354                    && state.land_approval.as_ref().is_some_and(|binding| {
4355                        Questions::open()
4356                            .get_for_effects(&binding.question)
4357                            .is_ok_and(|q| {
4358                                q.run == state.id
4359                                    && q.resolution()
4360                                        .as_deref()
4361                                        .is_some_and(crate::merge_decision::stops)
4362                            })
4363                    })
4364        });
4365    if let Some(owner) = stop_owner {
4366        let mut runner = match Runner::resume(&owner.id) {
4367            Ok(runner) => runner,
4368            Err(e) => {
4369                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4370                record(queue, task);
4371                return Vec::new();
4372            }
4373        };
4374        runner.on_pause(stop.pause());
4375        runner.watch_interrupt(interrupt_pause);
4376        let quota_before = runner.state.quota.clone();
4377        let before_start = task.clone();
4378        task.start(owner.id.clone());
4379        if let Err(error) = queue.put(task) {
4380            *task = before_start;
4381            let error = runner.fail_startup("task-start", error);
4382            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4383                task.record_startup_failure(failure.clone());
4384            }
4385            task.hold_manual(Some(format!(
4386                "Could not persist task start; no agents dispatched: {error:#}"
4387            )));
4388            record(queue, task);
4389            return Vec::new();
4390        }
4391        lock(status).current.push(Current {
4392            worker: None,
4393            task: task.id.clone(),
4394            run: owner.id,
4395        });
4396        runner.state.carry_dispatched_resumes(task);
4397        runner.state.next_pass_task_entry = true;
4398        let result = runner.execute().await;
4399        return finish_attempt(
4400            opts.max_attempts,
4401            queue,
4402            task,
4403            &runner.state,
4404            &quota_before,
4405            result,
4406        );
4407    }
4408
4409    if let Some(owner) = &public_owner
4410        && (task.fresh_start || !may_resume_run(owner, task))
4411    {
4412        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)));
4413        record(queue, task);
4414        return Vec::new();
4415    }
4416
4417    if let Some(state) = task
4418        .execution_runs()
4419        .last()
4420        .and_then(|id| RunState::load(id).ok())
4421        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4422    {
4423        task.hold_machine(Some(reason));
4424        record(queue, task);
4425        return Vec::new();
4426    }
4427
4428    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4429        && !task.fresh_start
4430        && task.pr_recovery.is_none()
4431    {
4432        // Authorization still takes the owner lock and execution lease and
4433        // rechecks liveness, retained HEAD and ownership before saving.
4434        let authorized = if crate::repair_budget::conflict_pending(task, &held) {
4435            true
4436        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4437            let home = queue.root().parent().expect("queue has a home");
4438            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4439                Ok(()) => true,
4440                Err(error) => {
4441                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4442                    false
4443                }
4444            }
4445        } else {
4446            false
4447        };
4448        if !authorized {
4449            task.hold_machine(Some(format!("Base synchronization remains stopped. {} A release without a new owner approval grants no additional synchronization budget and starts no replacement competition.", held.base_sync_next_action())));
4450            // Retain the existing stop identity when an old release reached the queue.
4451            task.base_sync_notice(&held);
4452            task.resume_override = None;
4453            record(queue, task);
4454            return Vec::new();
4455        }
4456    }
4457    let unfinished = (!task.fresh_start)
4458        .then(|| unfinished_run(&resume_runs, task.short()))
4459        .flatten()
4460        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4461    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4462    if !task.fresh_start
4463        && task.pr_recovery.is_none()
4464        && task.review_branch.is_none()
4465        && task.resume_override.is_none()
4466        && previous
4467            .as_ref()
4468            .is_some_and(|run| run.retired_to.is_some())
4469        && unfinished.is_none()
4470    {
4471        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()));
4472        record(queue, task);
4473        return Vec::new();
4474    }
4475
4476    let saved_recovery = previous.as_ref().filter(|run| {
4477        task.replacement.is_none()
4478            && task.pr_recovery.as_ref().is_some_and(|selected| {
4479                selected
4480                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4481                    .is_ok()
4482                    && selected_starter(selected, Some(run), unfinished.as_deref())
4483                        == Starter::Resume(run.id.clone())
4484            })
4485    });
4486
4487    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4488    // failure here is the network's or the operator's, not the task's: hold
4489    // without spending an attempt, never fall back to a possibly stale copy.
4490    let explicit = match &task.overrides {
4491        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4492        Some(_) => opts.config.as_deref(),
4493        None => opts.config.as_deref(),
4494    };
4495    let (mut config, layers) = if let Some(run) = saved_recovery {
4496        // A matching resume owns its resolved configuration and evidence;
4497        // current layers and inherited overrides only configure new work.
4498        let mut saved = run.clone();
4499        if let Err(e) = saved.configure_recovery_resume() {
4500            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4501            record(queue, task);
4502            return Vec::new();
4503        }
4504        (saved.config, Vec::new())
4505    } else {
4506        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4507            Ok(loaded) => loaded,
4508            Err(e) => {
4509                let reason = format!("[config] {e:#}");
4510                record_config_failure(task, &e);
4511                task.last_error = Some(reason.clone());
4512                task.hold_machine(Some(reason));
4513                record(queue, task);
4514                return Vec::new();
4515            }
4516        };
4517        if let Err(e) = apply_options(&mut config, opts, task) {
4518            task.hold_manual(Some(format!(
4519                "[config] {e:#}; correct the merge override before releasing the task"
4520            )));
4521            record(queue, task);
4522            return Vec::new();
4523        }
4524        if let Some(selected) = &task.pr_recovery
4525            && let Err(e) = selected.configure(&mut config)
4526        {
4527            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4528            record(queue, task);
4529            return Vec::new();
4530        }
4531        (config, layers)
4532    };
4533    let config_evidence = crate::pr_recovery::ConfigEvidence {
4534        layers,
4535        overrides: task.overrides.clone(),
4536        daemon_merge: task
4537            .overrides
4538            .as_ref()
4539            .is_none_or(|o| o.inherit_daemon_options)
4540            .then(|| opts.merge.clone())
4541            .flatten(),
4542    };
4543    apply_task_implementers(&mut config, task);
4544    if let Some(replacement) = &task.replacement {
4545        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4546            old.liveness(false) == Liveness::Dead
4547                && old.merge_decision.as_ref().is_some_and(|d| {
4548                    d.closed
4549                        && d.question == replacement.question
4550                        && d.replacement_run.as_ref().is_none_or(|run| {
4551                            task.execution_runs().last() == Some(run)
4552                                && RunState::load(run).is_ok_and(|current| {
4553                                    current.replaces.as_ref().is_some_and(|pin| {
4554                                        pin.question == replacement.question
4555                                            && pin.agent == replacement.agent
4556                                    })
4557                                })
4558                        })
4559                })
4560        });
4561        if !safe {
4562            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()));
4563            record(queue, task);
4564            return Vec::new();
4565        }
4566        match config.agent(&replacement.agent) {
4567            Ok(agent) if crate::agent::installed(agent) => {}
4568            _ => {
4569                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)));
4570                record(queue, task);
4571                return Vec::new();
4572            }
4573        }
4574        config.graph.implementers = 1;
4575        config.graph.land_approval = true;
4576        config.merge.mode = MergeMode::Pr;
4577        config.graph.selected_implementer = Some(replacement.agent.clone());
4578    }
4579    let p = phrases(&config.graph.language);
4580    let start_failed = p.could_not_start;
4581    // Resolve once for both admission and settlement. The inputs are the
4582    // task's explicit sources (never prose), plus an explicit review source's
4583    // current head; review-only runs may rebase later, and neither fact can
4584    // refund a failed automatic generation.
4585    if let Ok(base) =
4586        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4587            .await
4588        && let Ok(head) =
4589            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4590    {
4591        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4592        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4593            let source = crate::git::rev_parse(&repo, branch)
4594                .await
4595                .unwrap_or_default();
4596            inputs.push_str(&format!(";review:{branch}:{source}"));
4597        }
4598        if let Some(reason) = task
4599            .recovery_exhausted(
4600                &head,
4601                &inputs,
4602                task.attempt_limit
4603                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4604            )
4605            .filter(|_| {
4606                !task.repair_grants.last().is_some_and(|receipt| {
4607                    RunState::load(&receipt.request.run)
4608                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4609                })
4610            })
4611        {
4612            task.hold_unrequested_retry(Some(reason));
4613            record(queue, task);
4614            return Vec::new();
4615        }
4616        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4617    }
4618
4619    // The free-space gate, checked *before* anything is minted: a task that
4620    // waits out a full disk costs nothing yet, and must not spend an attempt
4621    // or start a run the machine cannot finish. Held tasks stay in the list
4622    // for the human to see, and `magi task release` re-queues them when space
4623    // comes back - the same recovery as any other hold. A volume whose free
4624    // space cannot be measured closes the gate too: starting a run blind on a
4625    // disk that may be full is how the machine ends up with 6.7 GB free.
4626    if let Some(reason) = disk_gate(&repo, &config) {
4627        task.notice_cause("disk-space", None, None);
4628        task.last_error = Some(reason.clone());
4629        task.hold_machine(Some(reason.clone()));
4630        record(queue, task);
4631        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4632        // Stable wording - the free-space figures live in the task's hold
4633        // reason, and changing numbers would relight the bell every poll.
4634        notices::raise(
4635            Notice::warn(
4636                &format!("disk:{}", repo.display()),
4637                format!("Task {} held for want of free disk space: {reason}. Free some, then release it from the queue.", task.id),
4638            )
4639            .link(Link::Task {
4640                id: task.id.clone(),
4641            }),
4642        );
4643        return Vec::new();
4644    }
4645
4646    // A resumable run of this task is carried on, never re-competed. The
4647    // candidates are built and paid for, and a fresh competition races a
4648    // second implementation against them.
4649    //
4650    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4651    // started 3cbf on the same task a moment later, duplicating two and a
4652    // half hours of agent work. Then b25f stalled on a judge that timed out
4653    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4654    // was to blame for - and 4043 started **one second** later, buying three
4655    // fresh implementations to reach the same panel. `RunStatus::resumable`
4656    // rather than `!done()` is what catches the second case: a stall is
4657    // terminal, and its cheap recovery re-asks only the absent seats.
4658    //
4659    // A load failure is warned about rather than silently read as "not
4660    // resumable": the alternative is exactly what let a schema mismatch on
4661    // run `eba2` fall through to a full re-competition with nobody told why.
4662    // `crate::conduct` is what actually offers a better answer than
4663    // `Runner::start` here (see `Recovery::Review`), once this task's next
4664    // failure shows it up as `held`/`failed` with the run state unreadable.
4665    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
4666    // branch survived, and this reopens exactly that branch as a
4667    // review-only pass rather than resuming or competing again. Consumed
4668    // (cleared) here whichever way this goes, so it never outlives this one
4669    // attempt - see `queue::Task::review_branch`.
4670    let review_branch = if previous
4671        .as_ref()
4672        .is_some_and(|state| crate::repair_budget::pending(task, state))
4673    {
4674        None
4675    } else {
4676        take_review_branch(task, previous.as_ref())
4677    };
4678    let branch_exists = match &review_branch {
4679        Some(branch) => crate::git::branch_exists(&repo, branch)
4680            .await
4681            .unwrap_or(false),
4682        None => false,
4683    };
4684    // An explicit `magi review <branch>` is reviewed whatever happens to the
4685    // branch unless an explicit implementer change requires fresh work. An
4686    // unfinished run of the same task still wins, so a retry resumes.
4687    let proposed = review_retry_starter(
4688        task,
4689        previous.as_ref(),
4690        review_branch.as_deref(),
4691        branch_exists,
4692        unfinished.as_deref(),
4693    );
4694    let retry_selected = task.replacement.is_some()
4695        && task.resumption.is_some()
4696        && !task.fresh_start
4697        && previous.as_ref().is_some_and(|run| {
4698            run.replaces.is_some()
4699                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4700                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4701        });
4702    let stop_pin = task
4703        .resume_override
4704        .as_ref()
4705        .filter(|pin| {
4706            Questions::open()
4707                .get_for_effects(&pin.question_id)
4708                .is_ok_and(|q| {
4709                    q.node == land::APPROVAL_NODE
4710                        && q.resolution()
4711                            .as_deref()
4712                            .is_some_and(crate::merge_decision::stops)
4713                })
4714        })
4715        .and_then(|pin| pin.pinned_run.clone());
4716    let granted_run = task.repair_grants.last().and_then(|receipt| {
4717        let state = RunState::load(&receipt.request.run).ok()?;
4718        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
4719    });
4720    let starter = if let Some(run) = granted_run {
4721        Starter::Resume(run)
4722    } else if let Some(owner) = &public_owner {
4723        Starter::Resume(owner.id.clone())
4724    } else if let Some(run) = stop_pin {
4725        // Stop actions resume their exact owner even after seat-count edits;
4726        // they must never fall through to implementation or a takeover.
4727        Starter::Resume(run)
4728    } else if retry_selected {
4729        Starter::Resume(previous.as_ref().unwrap().id.clone())
4730    } else if let Some(selected) = &task.pr_recovery {
4731        if selected
4732            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4733            .is_ok()
4734        {
4735            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4736        } else {
4737            Starter::Review(selected.branch.clone())
4738        }
4739    } else {
4740        starter_with_implementers(task, previous.as_ref(), proposed)
4741    };
4742    // An explicit resume pin must never degrade into a new competition or
4743    // takeover, including when its run stops being eligible after the answer.
4744    if let Some(pin) = &task.resume_override
4745        && let Some(run) = &pin.pinned_run
4746        && starter != Starter::Resume(run.clone())
4747    {
4748        let run = run.clone();
4749        task.notice_cause("resume-owner", Some(&run), None);
4750        task.hold_machine(Some(format!(
4751            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4752            task.id
4753        )));
4754        record(queue, task);
4755        return Vec::new();
4756    }
4757    if task.replacement.is_some()
4758        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4759        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4760    {
4761        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()));
4762        record(queue, task);
4763        return Vec::new();
4764    }
4765    if let Some(reason) = retained_attempt_hold(
4766        task,
4767        &starter,
4768        config.disk.retained_attempt_limit,
4769        RunState::load,
4770    ) {
4771        // The review choice was consumed above. Preserve it across this hold
4772        // so a later release cannot silently become a fresh implementation.
4773        if let Starter::Review(branch) = &starter {
4774            task.review_branch = Some(branch.clone());
4775        }
4776        task.hold_unrequested_retry(Some(reason));
4777        record(queue, task);
4778        return Vec::new();
4779    }
4780    // Absolute paths of the files the task was filed with, re-read from the
4781    // task now so a file attached while it was held reaches a resumed run
4782    // too. A stored name whose file has gone is an error before any agent is
4783    // paid for, never a silent omission the implementer cannot notice.
4784    let attachments = match task_attachments(queue, task) {
4785        Ok(a) => a,
4786        Err(e) => {
4787            task.attempts += 1;
4788            task.fail_startup_target(
4789                "startup-attachments",
4790                e.name.clone(),
4791                format!("{start_failed}{e:#}"),
4792                opts.max_attempts,
4793            );
4794            record(queue, task);
4795            return Vec::new();
4796        }
4797    };
4798    let startup_pause = stop.pause();
4799    let startup_interrupt = interrupt_pause.clone();
4800    let wait = crate::repo_lock::WaitPolicy::new(
4801        Duration::from_secs(config.graph.timeout_resource_wait),
4802        move || startup_pause.parked() || startup_interrupt.parked(),
4803    );
4804    // Startup includes review takeover and recovery. Do not embed its large
4805    // future in both the wait scope and the surrounding attempt stack frame.
4806    let started = wait.scope(Box::pin(async { match &starter {
4807        Starter::Review(_) if task.pr_recovery.is_some() => {
4808            let selected = task.pr_recovery.clone().expect("selected recovery");
4809            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
4810                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4811                    .await
4812                    .map(|mut r| {
4813                        r.state.attachments = attachments.clone();
4814                        r
4815                    }),
4816                Err(e) => Err(e),
4817            }
4818        }
4819        Starter::Review(branch) => {
4820            tracing::info!(
4821                "task {} reopens `{branch}` as a review-only pass",
4822                task.short()
4823            );
4824            // Every earlier attempt is superseded by the one being minted
4825            // now, so a branch one of them still holds may be taken over.
4826            let takeover = crate::handover::Takeover {
4827                earlier: task.earlier_attempts().to_vec(),
4828                home: crate::run::home(),
4829                choice: take_divergence_answer(branch, &config.merge.remote, task),
4830                task_instruction: Some(instruction_for(task)),
4831            };
4832            Runner::review_taking_over(
4833                &repo,
4834                branch,
4835                config,
4836                Some(takeover),
4837                crate::run::Origin::queue(&task.id),
4838            )
4839            .await
4840        }
4841        Starter::Resume(id) => {
4842            tracing::info!("resuming run {id} rather than competing again");
4843            Runner::resume(id).and_then(|mut r| {
4844                if retry_selected {
4845                    // The explicit queue release retries this same pinned
4846                    // implementation, preserving the attempt and worktrees.
4847                    for candidate in &mut r.state.candidates {
4848                        candidate.failed = None;
4849                        candidate.empty = false;
4850                        candidate.commits = 0;
4851                    }
4852                    r.state.status = RunStatus::Implementing;
4853                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4854                }
4855                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4856                    r.state.sources = task.sources.clone();
4857                }
4858                if r.state.prep_failure.is_some() {
4859                    let approval = task
4860                        .resumption
4861                        .as_ref()
4862                        .context("preparation retry requires an explicit task release")?;
4863                    r.retry_preparation(approval.at)?;
4864                }
4865                if let Some(instruction) =
4866                    prepare_instruction(&starter, Some(&r.state.instruction), task)
4867                {
4868                    r.state.instruction = instruction;
4869                }
4870                r.state.attachments = attachments.clone();
4871                if task.replacement.is_some() {
4872                    r.state.config.merge.mode = MergeMode::Pr;
4873                    r.state.config.graph.land_approval = true;
4874                }
4875                // Replacements publish a new PR and ask again. Selected PR
4876                // recoveries keep their saved disposition; ordinary runs can
4877                // retain the task's merge override.
4878                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4879                    .overrides
4880                    .as_ref()
4881                    .and_then(|o| o.merge.as_deref())
4882                    .and_then(|m| merge_mode(m).ok())
4883                {
4884                    r.state.config.merge.mode = mode;
4885                }
4886                Ok(r)
4887            })
4888        }
4889        Starter::Start => {
4890            if let Some(branch) = &review_branch {
4891                tracing::warn!(
4892                    "conductor chose review for task {} but branch `{branch}` no longer \
4893                     exists; requeuing as a fresh competition instead",
4894                    task.short()
4895                );
4896            }
4897            let instruction = prepare_instruction(&starter, None, task)
4898                .unwrap_or_else(|| task.instruction.clone());
4899            Runner::start_naming(
4900                &repo,
4901                instruction,
4902                &task.title,
4903                config,
4904                crate::run::Origin::queue(&task.id),
4905            )
4906            .await
4907            .map(|mut r| {
4908                r.state.attachments = attachments.clone();
4909                r.state.sources = task.sources.clone();
4910                r
4911            })
4912        }
4913    }})).await;
4914    if let Err(error) = &started
4915        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
4916    {
4917        task.record_startup_failure(failure.clone());
4918    }
4919    let mut runner = match started {
4920        Ok(r) => r,
4921        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4922            task.last_error = Some(e.to_string());
4923            if stop.parking() || interrupt_pause.parked() {
4924                let attempts = task.attempts;
4925                task.park(e.to_string());
4926                // Startup has not spent an attempt to refund.
4927                task.attempts = attempts;
4928            } else {
4929                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4930            }
4931            record(queue, task);
4932            return Vec::new();
4933        }
4934        // A branch an earlier attempt still holds and magi will not release
4935        // by itself is the operator's call, not a failed attempt: hold the
4936        // task with the reason, spend nothing, and say so on the bell.
4937        Err(e) if task.pr_recovery.is_some() => {
4938            task.startup_notice_cause("startup-public-head");
4939            task.attempts += 1;
4940            task.last_error = Some(format!("{start_failed}{e:#}"));
4941            task.hold_unrequested_retry(Some(format!(
4942                "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."
4943            )));
4944            record(queue, task);
4945            return Vec::new();
4946        }
4947        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4948            let detail = match e.downcast_ref::<crate::handover::Refused>() {
4949                Some(r) => (p.handover_refused)(r),
4950                None => format!("{e:#}"),
4951            };
4952            task.startup_notice_cause("startup-handover");
4953            let reason = format!("{start_failed}{detail}");
4954            task.last_error = Some(reason.clone());
4955            // Consumed above by `take`; keep it so the released task retries
4956            // as a review of this same branch.
4957            let branch = match &starter {
4958                Starter::Review(branch) => Some(branch.clone()),
4959                _ => None,
4960            };
4961            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
4962            // one page; the guidance rides in the reason, fixed per state so a
4963            // re-put never changes the wording and relights it.
4964            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4965            record(queue, task);
4966            tracing::warn!(
4967                "holding {} for a branch it cannot take over: {e:#}",
4968                task.short()
4969            );
4970            return Vec::new();
4971        }
4972        // A branch that differs between here and the remote in ways magi
4973        // cannot prove are the same change is a decision for the owner, not a
4974        // failed attempt: ask with both sides laid out, spend no attempt, and
4975        // let the answer requeue the task.
4976        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4977            let d = e
4978                .downcast_ref::<crate::reconcile::Diverged>()
4979                .expect("checked by the guard");
4980            let mut q = ask::Question::new(
4981                task.id.clone(),
4982                crate::reconcile::NODE.to_owned(),
4983                crate::reconcile::SEAT.to_owned(),
4984                d.summary(),
4985                d.detail(),
4986                d.choices(),
4987            );
4988            match Questions::open().put(&mut q) {
4989                Ok(()) => {
4990                    task.last_error = Some(format!("{e:#}"));
4991                    // Consumed above by `take`; the answer has to reach a review
4992                    // of this same branch, so keep pointing the task at it.
4993                    task.review_branch = Some(d.branch.clone());
4994                    task.review_instruction = Some(task.instruction.clone());
4995                    task.block(vec![q.id.clone()], Some(d.summary()));
4996                }
4997                Err(put) => {
4998                    tracing::warn!("could not file the divergence question: {put:#}");
4999                    task.attempts += 1;
5000                    task.fail_startup(
5001                        "startup-question-store",
5002                        format!("{start_failed}{e:#}"),
5003                        opts.max_attempts,
5004                    );
5005                }
5006            }
5007            record(queue, task);
5008            return Vec::new();
5009        }
5010        Err(e) => {
5011            // The answer was stale and nothing was applied: keep pointing at
5012            // the branch so the next attempt asks again against its new tips.
5013            // Nothing went wrong with the task, so no attempt is spent: a
5014            // budget one short of its limit must not hold it instead of
5015            // letting the question be asked again.
5016            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5017                && let Starter::Review(branch) = &starter
5018            {
5019                task.review_branch = Some(branch.clone());
5020                task.review_instruction = Some(task.instruction.clone());
5021                task.last_error = Some(format!("{start_failed}{e:#}"));
5022                task.status = crate::queue::TaskStatus::Failed;
5023                record(queue, task);
5024                return Vec::new();
5025            }
5026            task.attempts += 1;
5027            task.last_error = Some(format!("{start_failed}{e:#}"));
5028            task.startup_notice_cause("startup-source");
5029            task.hold_unrequested_retry(Some(format!(
5030                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5031            )));
5032            record(queue, task);
5033            return Vec::new();
5034        }
5035    };
5036    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5037        runner.state.recovery_config = Some(config_evidence);
5038    }
5039    if let Some(replacement) = &task.replacement {
5040        if matches!(starter, Starter::Start) {
5041            runner.state.instruction.push_str(&format!(
5042                "\n\n# Replacement review context\n{}",
5043                replacement.context
5044            ));
5045        }
5046        runner.state.replaces = Some(replacement.clone());
5047        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5048        if let Ok(mut old) = RunState::load(&replacement.run)
5049            && let Some(d) = &mut old.merge_decision
5050        {
5051            d.replacement_run = Some(runner.state.id.clone());
5052            old.event(
5053                "replacement",
5054                format!(
5055                    "replacement run {} owns the next attempt; old PR remains closed",
5056                    runner.state.id
5057                ),
5058            );
5059            if let Err(e) = old.save() {
5060                let error = runner.fail_startup("replacement-history", e);
5061                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5062                    task.record_startup_failure(failure.clone());
5063                }
5064                task.hold_manual(Some(format!(
5065                    "Could not link replacement history: {error:#}; no agents dispatched"
5066                )));
5067                record(queue, task);
5068                return Vec::new();
5069            }
5070        }
5071    }
5072    runner.state.task_instruction = Some(task.instruction.clone());
5073    // The follow-up depth is fixed now, while the task certainly exists:
5074    // deleting it later must not reset the cap (`crate::followup`).
5075    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5076    if runner.state.origin_chat.is_none() {
5077        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5078    }
5079    // A stop that means "park" reaches the graph through this handle.
5080    runner.on_pause(stop.pause());
5081    // `poll`'s interrupt scheduler reaches this one run - and no other -
5082    // through this handle. See `Pause`'s own doc for why these are never
5083    // the same one.
5084    runner.watch_interrupt(interrupt_pause);
5085
5086    // `start` has minted the run, so the task can now point at it. Persisting
5087    // `Running` before `execute` is what makes a crash mid-run legible.
5088    let run = runner.state.id.clone();
5089    let before_start = task.clone();
5090    task.start(run.clone());
5091    if let Err(error) = queue.put(task) {
5092        *task = before_start;
5093        let error = runner.fail_startup("task-start", error);
5094        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5095            task.record_startup_failure(failure.clone());
5096        }
5097        task.hold_manual(Some(format!(
5098            "Could not persist task start; no agents dispatched: {error:#}"
5099        )));
5100        record(queue, task);
5101        return Vec::new();
5102    }
5103    lock(status).current.push(Current {
5104        worker: None,
5105        task: task.id.clone(),
5106        run,
5107    });
5108
5109    // `RunState::quota` is the run's whole history across every resume, so
5110    // only what this execution added may arm the cooldown or earn a refund.
5111    let quota_before = runner.state.quota.clone();
5112    runner.state.carry_dispatched_resumes(task);
5113    runner.state.next_pass_task_entry = true;
5114    let result = runner.execute().await;
5115    finish_attempt(
5116        opts.max_attempts,
5117        queue,
5118        task,
5119        &runner.state,
5120        &quota_before,
5121        result,
5122    )
5123}
5124
5125/// Settle `task` after its run executed: the verdict, the diagnosis, the
5126/// supersession of earlier attempts and the save. Shared by the loop and by
5127/// `magi run --resume`, so an attempt is counted one way wherever it ran.
5128/// Returns the quota losses this execution added to the run.
5129pub fn finish_attempt(
5130    max_attempts: usize,
5131    queue: &Queue,
5132    task: &mut Task,
5133    state: &RunState,
5134    quota_before: &[QuotaLoss],
5135    result: Result<()>,
5136) -> Vec<QuotaLoss> {
5137    let detail = match result {
5138        Ok(()) => describe(state),
5139        Err(e) => format!("{e:#}"),
5140    };
5141    let fresh = losses_this_attempt(quota_before, &state.quota);
5142    let verdict = Verdict {
5143        status: state.status,
5144        // A run that opened a pull request handed its work over, whatever the
5145        // gate then decided about merging it.
5146        left_pr: state.pr.is_some(),
5147        // Only a rate limit earns the task its attempt back - and only one
5148        // suffered now: a refund justified by a previous session's loss is
5149        // the same mistake as re-arming the cooldown from it. A stalled run
5150        // resumed without hitting quota again therefore spends its attempt,
5151        // like any other failure of the task's own.
5152        quota_hit: !fresh.is_empty(),
5153        // A run that parked was asked to stop; that is not a failure and must
5154        // not spend an attempt, or replacing the binary a few times would
5155        // exhaust a task's budget without an agent ever misbehaving.
5156        parked: state.parked,
5157        // A quota loss that left nothing viable is the same machine fact as a
5158        // `Stalled` quota loss; see `settle`'s doc table.
5159        no_viable_candidates: state.viable().is_empty(),
5160    };
5161    if let Some(replacement) = &state.replaces
5162        && let Some(pr) = &state.pr
5163        && let Ok(mut old) = RunState::load(&replacement.run)
5164        && let Some(d) = &mut old.merge_decision
5165    {
5166        d.replacement_pr = Some(pr.url.clone());
5167        let _ = old.save();
5168    }
5169    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5170    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5171        task.hold_unrequested_retry(Some(format!(
5172            "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.",
5173            task.short()
5174        )));
5175    }
5176    if task.status == TaskStatus::Done {
5177        supersede_prior_runs(task, &crate::run::home());
5178    }
5179    record(queue, task);
5180    tracing::info!(
5181        "task {} is {} after run {} ({})",
5182        task.short(),
5183        task.status.as_str(),
5184        state.short(),
5185        label(state.status)
5186    );
5187    fresh
5188}
5189
5190/// A task a hand-started run leaves runnable (failed with attempts to spare,
5191/// or requeued) is **held**: nobody asked for a retry, and a loop starting
5192/// later must not spend agent calls on it. `magi task release` retries.
5193pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5194    // Parked work (including legacy Failed records with a parked run) is a
5195    // checkpoint or owner handoff, not an unrequested retry.
5196    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5197        && !awaiting_resume_with(task, RunState::load)
5198        // A run parked on the owner's word about a withheld PR title/body
5199        // resumes via `land_resume_state`, including review-only tasks that
5200        // `awaiting_resume_with` does not consider.
5201        && withheld_text_wait(task).is_none()
5202        && !(task.fresh_start && task.replacement.is_some())
5203    {
5204        let why = task.last_error.clone().map_or_else(
5205            || "the run did not finish".to_owned(),
5206            |e| format!("the run did not finish: {e}"),
5207        );
5208        task.hold_unrequested_retry(Some(format!(
5209            "{why}. It was started by hand, so it is not retried \
5210             automatically; `magi task release` retries it."
5211        )));
5212        record(queue, task);
5213    }
5214}
5215
5216/// Whether an attempt at a task whose newest run is `run` would resume that
5217/// run rather than start a fresh competition. `magi run --resume` hands a run
5218/// to a live loop only when this holds.
5219#[must_use]
5220pub fn loop_would_resume(run: &str) -> bool {
5221    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5222}
5223
5224/// A loop in another process that is alive right now: a fresh heartbeat in
5225/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
5226/// carries the pid it published (`None` inside when it published none - a
5227/// fresh heartbeat is still evidence of a live loop).
5228///
5229/// The one judgement of "is somebody else serving this queue", shared by the
5230/// web UI's refusal to start a second loop and by `magi run` / `magi review`
5231/// deciding whether to hand a task to the loop. A claim file proves nothing
5232/// here: whether a claim succeeds says nothing about whether its owner lives.
5233#[must_use]
5234pub fn foreign_loop(
5235    reading: Option<&Reading>,
5236    now: Timestamp,
5237    own_pid: u32,
5238) -> Option<Option<u32>> {
5239    let reading = reading.filter(|r| r.running(now))?;
5240    match reading.pid {
5241        Some(pid) if pid == own_pid => None,
5242        pid => Some(pid),
5243    }
5244}
5245
5246fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5247    reading.worker_protocol != Some(1)
5248        && (foreign_loop(Some(reading), now, own_pid).is_some()
5249            || reading
5250                .pid
5251                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5252}
5253
5254/// Low-level claimed-task execution shared by the detached standalone worker
5255/// and focused lifecycle fixtures. The caller must retain the queue claim for
5256/// this entire call. CLI callers transfer ownership through
5257/// [`run_detached_claimed`] instead of executing inside their own runtime.
5258///
5259/// The one deliberate difference from the loop: a task the attempt leaves
5260/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5261/// Nobody asked for a retry, and a daemon starting later must not spend agent
5262/// calls re-running a hand-started task behind the operator's back;
5263/// `magi task release` is the explicit retry.
5264pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5265    run_claimed_until(opts, queue, task, &Stop::new()).await;
5266}
5267
5268async fn run_claimed_until(
5269    opts: &Opts,
5270    queue: &Queue,
5271    task: &mut Task,
5272    stop: &Stop,
5273) -> Vec<QuotaLoss> {
5274    let status = Arc::new(Mutex::new(Status::new()));
5275    // An attempt embeds startup and graph futures. Keep it off the standalone
5276    // caller's stack, on both the initial execution and withheld-text resume.
5277    let mut quota = Box::pin(attempt(
5278        opts,
5279        queue,
5280        &status,
5281        stop,
5282        crate::graph::Pause::new(),
5283        task,
5284    ))
5285    .await;
5286    // A run parked on the owner's word about a withheld PR title/body has no
5287    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5288    // here with the claim still held, and resume once the question is settled
5289    // (answered, or abandoned at its deadline -> the neutral text).
5290    // A rejected reply files one more question (the gate asks at most twice),
5291    // so after a resume the run may be waiting again: keep going, with a fresh
5292    // limit for the new question. `resumes` bounds it even if a resume parks
5293    // without asking anything new.
5294    let mut resumes = 0;
5295    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5296        let Some(timeout) = withheld_text_wait(task) else {
5297            break;
5298        };
5299        eprintln!(
5300            "waiting for the owner's answer on a withheld pull request text \
5301             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5302        );
5303        // The deadline abandons the question itself; the extra margin only
5304        // covers an abandon that could not be saved.
5305        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5306        let ready = loop {
5307            match land_resume_state(task) {
5308                LandResume::StillWaiting
5309                    if !stop.parking() && std::time::Instant::now() < limit =>
5310                {
5311                    tokio::time::sleep(WITHHELD_POLL).await;
5312                }
5313                LandResume::Ready => break true,
5314                _ => break false,
5315            }
5316        };
5317        if !ready || stop.parking() {
5318            break;
5319        }
5320        resumes += 1;
5321        quota.extend(
5322            Box::pin(attempt(
5323                opts,
5324                queue,
5325                &status,
5326                stop,
5327                crate::graph::Pause::new(),
5328                task,
5329            ))
5330            .await,
5331        );
5332    }
5333    hold_if_runnable(queue, task);
5334    quota
5335}
5336
5337/// Resumes an in-process run makes for withheld-text questions: the gate asks
5338/// at most twice, plus one for a resume that asks nothing new.
5339const MAX_WITHHELD_RESUMES: u32 = 3;
5340
5341/// How often an in-process run rechecks its withheld-text question.
5342const WITHHELD_POLL: Duration = Duration::from_secs(15);
5343
5344/// The `answer_timeout` (seconds) of the task's last run when that run is
5345/// parked on an unresolved withheld-text question; `None` otherwise.
5346fn withheld_text_wait(task: &Task) -> Option<u64> {
5347    let id = task.execution_runs().last()?;
5348    let s = RunState::load(id).ok()?;
5349    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5350        .then_some(s.config.graph.answer_timeout)
5351}
5352
5353/// The quota losses `after` holds that `before` did not: what one execution
5354/// suffered, as opposed to the run's history.
5355///
5356/// Compared by value rather than by length or position because
5357/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5358/// the vector can shrink and shift under a resume. A retried seat that hits
5359/// quota again is a `push` with a new `at`, so it shows up as new here.
5360/// Crash recovery uses the recorded pass start as its boundary when available;
5361/// legacy records without passes retain their original history-based policy.
5362fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5363    after
5364        .iter()
5365        .filter(|q| !before.contains(q))
5366        .cloned()
5367        .collect()
5368}
5369
5370/// When the loop-wide quota cooldown should end, given this attempt's losses;
5371/// `None` when there were none. Reset-hint parsing and the cap live here.
5372fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5373    let quota: Vec<_> = quota
5374        .iter()
5375        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5376        .collect();
5377    if quota.is_empty() {
5378        return None;
5379    }
5380    let with_hint = quota.iter().find(|q| q.reset.is_some());
5381    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5382    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5383    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5384    Some(
5385        now.checked_add(jiff::SignedDuration::from_secs(secs))
5386            .unwrap_or(Timestamp::MAX),
5387    )
5388}
5389
5390/// An explicit task count must agree with a run before any resume.
5391fn implementers_match(task: &Task, state: &RunState) -> bool {
5392    task.replacement.as_ref().map_or_else(
5393        || {
5394            task.implementers()
5395                .is_none_or(|n| n == state.config.graph.implementers)
5396        },
5397        |replacement| {
5398            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5399                && state.config.graph.implementers == 1
5400        },
5401    )
5402}
5403
5404/// Never resume or take over candidate work built for a different seat count.
5405fn starter_with_implementers(
5406    task: &Task,
5407    previous: Option<&RunState>,
5408    proposed: Starter,
5409) -> Starter {
5410    if previous.is_some_and(|s| !implementers_match(task, s)) {
5411        task.review_of
5412            .as_ref()
5413            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5414    } else {
5415        proposed
5416    }
5417}
5418
5419/// Apply this task's explicit count to the new attempt, without changing defaults.
5420fn apply_task_implementers(config: &mut Config, task: &Task) {
5421    if let Some(n) = task.implementers() {
5422        config.graph.implementers = n;
5423    }
5424}
5425
5426/// [`prepare`] for one task: its own `--config` and command-line overrides
5427/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5428/// over the loop's, so handing a hand-started task to a daemon changes nothing
5429/// about what it does.
5430#[cfg(test)]
5431fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5432    let explicit = match &task.overrides {
5433        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5434        _ => opts.config.as_deref(),
5435    };
5436    let (mut config, _) = Config::discover(repo, explicit)?;
5437    apply_options(&mut config, opts, task)?;
5438    Ok(config)
5439}
5440
5441fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5442    if task
5443        .overrides
5444        .as_ref()
5445        .is_none_or(|o| o.inherit_daemon_options)
5446        && let Some(mode) = opts.merge.as_deref()
5447    {
5448        config.merge.mode = merge_mode(mode)?;
5449    }
5450    if let Some(o) = &task.overrides {
5451        o.apply(config);
5452    }
5453    Ok(())
5454}
5455
5456/// Load the config for a task's repository, with the merge override applied.
5457fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5458    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5459    if let Some(mode) = &opts.merge {
5460        config.merge.mode = merge_mode(mode)?;
5461    }
5462    Ok(config)
5463}
5464
5465/// Prune the shared build cache at a between-runs boundary. The detached cache
5466/// service checks authoritative task jobs first; dispatch waits for that finite
5467/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5468/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5469async fn maybe_prune_cache_between_runs(
5470    repo: &Path,
5471    opts: &Opts,
5472    home: &Path,
5473    stop: &Stop,
5474    last_checked: &mut Option<Timestamp>,
5475    now: Timestamp,
5476) {
5477    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5478        return;
5479    }
5480    *last_checked = Some(now);
5481    let cfg = match prepare(repo, opts) {
5482        Ok(cfg) => cfg,
5483        Err(e) => {
5484            tracing::warn!("cache check: no config: {e:#}");
5485            return;
5486        }
5487    };
5488    match clean::prune_cache_if_over_limit(&cfg, home) {
5489        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5490            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5491            pruned.files,
5492            pruned.freed
5493        ),
5494        Ok(_) => {}
5495        Err(e) => {
5496            tracing::warn!("housekeep: prune cache: {e:#}");
5497            notices::raise_in(
5498                home,
5499                Notice::warn(
5500                    "housekeep:cache",
5501                    format!(
5502                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5503                        e.to_string()
5504                            .lines()
5505                            .next()
5506                            .unwrap_or("unknown cleanup error")
5507                    ),
5508                ),
5509            );
5510        }
5511    }
5512}
5513
5514/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5515/// now, given when it last did (if ever). Pure, so the cadence is asserted
5516/// directly rather than by waiting out real minutes in a test.
5517fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5518    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5519}
5520
5521/// The disk janitor, with its housekeeping logged rather than fatal.
5522///
5523/// Called only at the loop's idle points, for the reason the caller documents:
5524/// a prune racing a live compile would delete files mid-build. The config is
5525/// re-read on every call because the repository that just ran may not be the
5526/// daemon's own default, and the cache directory is a repository fact.
5527///
5528/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5529/// and [`crate::run::default_worktree_root`] read here, for the same reason
5530/// [`drive`] takes its queue and status file rather than resolving them: a
5531/// test driving the loop must not reach through to the operator's real home
5532/// or worktree bay just because the janitor runs on every idle tick.
5533/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5534/// to get wrong silently - a test's `home` was already isolated, but nothing
5535/// exercised the parameter next to it, so a real worktree bay stayed wired in
5536/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5537/// it for real, every test in this file that drives the loop at all started
5538/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5539async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5540    let cfg = match prepare(repo, opts) {
5541        Ok(cfg) => cfg,
5542        Err(e) => {
5543            tracing::warn!("housekeep: no config: {e:#}");
5544            return;
5545        }
5546    };
5547    // A run's own worktree lives under `config.graph.worktree_root` when the
5548    // repository sets one - the same precedence `RunState::worktree_root`
5549    // uses - and `worktrees_root` only stands in for the *default* an
5550    // unconfigured repository resolves to (see this function's own
5551    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5552    // that always swept the default regardless of this override would never
5553    // see, and so never reclaim, a single worktree for a repository that
5554    // relocated them elsewhere.
5555    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5556    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5557    // Reported whenever there is anything to say, not only when `folded > 0`:
5558    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5559    // folded, on every single pass, for months - a report gated on `folded`
5560    // would have stayed silent through every one of them.
5561    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5562        let mut extra = Vec::new();
5563        if out.unreadable > 0 {
5564            extra.push(format!("{} unreadable", out.unreadable));
5565        }
5566        if out.orphaned_worktrees > 0 {
5567            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5568        }
5569        let detail = if extra.is_empty() {
5570            String::new()
5571        } else {
5572            format!(" ({})", extra.join(", "))
5573        };
5574        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5575    }
5576    if out.external_merges_recorded > 0 {
5577        tracing::info!(
5578            "housekeep: recorded {} run(s) as merged externally",
5579            out.external_merges_recorded
5580        );
5581    }
5582    if out.stale_pr_states_repaired > 0 {
5583        tracing::info!(
5584            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5585            out.stale_pr_states_repaired
5586        );
5587    }
5588    if out.cache_files > 0 {
5589        tracing::info!(
5590            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5591            out.cache_files,
5592            out.cache_freed
5593        );
5594    }
5595    if out.questions_abandoned > 0 {
5596        tracing::info!(
5597            "housekeep: abandoned {} question(s) left open by a finished run",
5598            out.questions_abandoned
5599        );
5600    }
5601}
5602
5603/// Run [`triage::run_once`] and log whatever it did, the same "only when
5604/// there is something to say" rule [`janitor`] follows for its own report.
5605///
5606/// Called at the same idle points as [`janitor`] - once per full poll
5607/// interval, never mid-attempt - for the same reason: it is not liveness
5608/// critical, and a task's own `hold_reason` string is the one thing this
5609/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5610/// tick for no benefit.
5611async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5612    let questions = Questions::at(home.join("questions"));
5613    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5614    if report.is_empty() {
5615        return;
5616    }
5617    if !report.quarantined.is_empty() {
5618        tracing::info!(
5619            "triage: held {} blocked task(s) whose blocked-on task or \
5620             question no longer exists: {}",
5621            report.quarantined.len(),
5622            report.quarantined.join(", ")
5623        );
5624    }
5625    if !report.resumed.is_empty() {
5626        tracing::info!(
5627            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5628            report.resumed.len(),
5629            report.resumed.join(", ")
5630        );
5631    }
5632    if !report.asked.is_empty() {
5633        tracing::info!(
5634            "triage: asked about {} held task(s): {}",
5635            report.asked.len(),
5636            report.asked.join(", ")
5637        );
5638    }
5639    if !report.answered.is_empty() {
5640        tracing::info!(
5641            "triage: applied {} operator answer(s): {}",
5642            report.answered.len(),
5643            report.answered.join(", ")
5644        );
5645    }
5646}
5647
5648/// The free-space gate: what stands between this task and a new run, if
5649/// anything. `Some(reason)` holds the task; `None` lets it start.
5650///
5651/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5652/// the operator opted out. A measurement failure is a gate, not a pass: both
5653/// sides of "cannot tell" are served by not starting.
5654pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5655    disk_gate_with(repo, config, crate::disk::free_bytes)
5656}
5657
5658/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
5659/// test can assert the exact wiring `attempt` runs - config's threshold in,
5660/// task-holding reason out - without asking the real machine's disk anything.
5661fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5662    repo: &Path,
5663    config: &Config,
5664    free_bytes: F,
5665) -> Option<String> {
5666    let min = config.disk.min_free_bytes;
5667    if min == 0 {
5668        return None;
5669    }
5670    let mut paths = vec![repo.to_owned()];
5671    if let Some(cache) = config.cache_dir() {
5672        paths.push(cache);
5673    }
5674    if let Some(root) = &config.graph.worktree_root {
5675        paths.push(root.clone());
5676    }
5677    for path in paths {
5678        let probe = if path == repo {
5679            path.as_path()
5680        } else {
5681            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5682        };
5683        let reason = match free_bytes(probe) {
5684            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5685            Err(e) => Some(crate::disk::unmeasured_in(
5686                probe,
5687                &e,
5688                &config.graph.language,
5689            )),
5690        };
5691        if reason.is_some() {
5692            return reason;
5693        }
5694    }
5695    None
5696}
5697
5698/// How long to wait before offering another task when a run lost a seat to a
5699/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
5700/// could read, or carried nothing at all. Long enough that a quota outage
5701/// cannot burn through a whole backlog in the few seconds each doomed attempt
5702/// takes to fail; short enough that a quota which clears early is not left
5703/// idle for the fallback's sake.
5704const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5705
5706/// Longest a parsed reset hint may push the wait out to. The hint comes from
5707/// the CLI's own words, not a contract, so a parsing slip that lands a day
5708/// away must not leave the loop asleep for a day.
5709const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5710
5711/// How long [`poll`] should wait before offering the next task, after a run
5712/// lost at least one seat to a rate limit.
5713///
5714/// Pure and separate from the loop so the policy can be exercised without a
5715/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
5716/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
5717/// nothing to parse, or the parsed time has already passed; `cap` bounds how
5718/// far a parsed hint is trusted to push the wait out.
5719fn quota_wait(
5720    reset_at: Option<Timestamp>,
5721    now: Timestamp,
5722    fallback: Duration,
5723    cap: Duration,
5724) -> Duration {
5725    match reset_at {
5726        Some(at) if at > now => {
5727            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5728            Duration::from_secs(secs).min(cap)
5729        }
5730        _ => fallback,
5731    }
5732}
5733
5734/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
5735///
5736/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
5737/// explains why parsing it exactly "would be a bug factory" — so this only
5738/// recognises the shapes actually observed in the wild, and returns `None`
5739/// for anything else rather than guess at a format nobody has seen.
5740///
5741/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
5742/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
5743/// said it, not from whenever this loop happens to read it: anchoring on `now`
5744/// would push the reset later on every read and would read an already-elapsed
5745/// reset as still in the future. (A long hint is still clamped by
5746/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
5747fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5748    parse_reset_hint_zoned(text, now)
5749        .or_else(|| parse_reset_hint_dated(text))
5750        .or_else(|| parse_reset_hint_relative(text, recorded))
5751}
5752
5753/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
5754/// optional but at least one required, in that order. A bare number or any
5755/// unknown unit is refused.
5756fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5757    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5758    let mut rest = rest.trim();
5759    if rest.is_empty() {
5760        return None;
5761    }
5762    let mut total: i64 = 0;
5763    let mut matched = false;
5764    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5765        if let Some((digits, tail)) = rest.split_once(unit)
5766            && !digits.is_empty()
5767            && digits.bytes().all(|b| b.is_ascii_digit())
5768        {
5769            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5770            rest = tail;
5771            matched = true;
5772        }
5773    }
5774    if !rest.is_empty() || !matched {
5775        return None;
5776    }
5777    recorded
5778        .checked_add(jiff::SignedDuration::from_secs(total))
5779        .ok()
5780}
5781
5782/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
5783/// case-insensitive) into a 24-hour hour and minute. Shared by every
5784/// reset-hint shape below.
5785fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5786    let clock = clock.trim().to_lowercase();
5787    let (digits, pm) = clock
5788        .strip_suffix("am")
5789        .map(|d| (d, false))
5790        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5791    let (h, m) = digits.trim().split_once(':')?;
5792    let mut hour: i8 = h.trim().parse().ok()?;
5793    let minute: i8 = m.trim().parse().ok()?;
5794    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5795        return None;
5796    }
5797    if pm && hour != 12 {
5798        hour += 12;
5799    } else if !pm && hour == 12 {
5800        hour = 0;
5801    }
5802    Some((hour, minute))
5803}
5804
5805/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
5806/// and a zone, never a date. A clock reading already past today is read as
5807/// tomorrow's: a CLI naming a same-day reset that has already gone by means
5808/// the window rolled over while nothing was watching.
5809fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5810    let open = text.find('(')?;
5811    let close = text.rfind(')')?;
5812    if close <= open {
5813        return None;
5814    }
5815    let zone = text[open + 1..close].trim();
5816    let (hour, minute) = parse_12h_clock(&text[..open])?;
5817    let tz = jiff::tz::TimeZone::get(zone).ok()?;
5818    let candidate = now
5819        .to_zoned(tz)
5820        .with()
5821        .hour(hour)
5822        .minute(minute)
5823        .second(0)
5824        .millisecond(0)
5825        .microsecond(0)
5826        .nanosecond(0)
5827        .build()
5828        .ok()?;
5829    let mut at = candidate.timestamp();
5830    if at <= now {
5831        at += jiff::SignedDuration::from_hours(24);
5832    }
5833    Some(at)
5834}
5835
5836/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
5837/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
5838/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
5839/// "already past today" correction to make: the year already disambiguates
5840/// it. Scanned as a five-word window so it can be pulled out of the middle
5841/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
5842/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
5843/// any other timestamp with no zone attached.
5844fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5845    let words: Vec<&str> = text.split_whitespace().collect();
5846    if words.len() < 5 {
5847        return None;
5848    }
5849    (0..=words.len() - 5)
5850        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5851}
5852
5853/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
5854/// parenthesis right after the window is refused rather than ignored — it
5855/// reads as an explicit zone annotation on a shape that otherwise carries
5856/// none, and guessing UTC anyway would be exactly the silent misread this
5857/// module's parsing otherwise avoids.
5858fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5859    if trailing.is_some_and(|next| next.starts_with('(')) {
5860        return None;
5861    }
5862    let month = month_number(window[0])?;
5863    let day_token = window[1].strip_suffix(',')?.to_lowercase();
5864    let day_digits = ["st", "nd", "rd", "th"]
5865        .iter()
5866        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5867    let day: i8 = day_digits.parse().ok()?;
5868    let year_token = window[2];
5869    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5870        return None;
5871    }
5872    let year: i16 = year_token.parse().ok()?;
5873    // The am/pm word carries the sentence's own trailing punctuation, e.g.
5874    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
5875    // reusing the same 12-hour clock reader the bracketed shape uses.
5876    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5877    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5878    let date = jiff::civil::Date::new(year, month, day).ok()?;
5879    let candidate = date
5880        .at(hour, minute, 0, 0)
5881        .to_zoned(jiff::tz::TimeZone::UTC)
5882        .ok()?;
5883    Some(candidate.timestamp())
5884}
5885
5886/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
5887/// case-insensitively, into a 1-based month number.
5888fn month_number(name: &str) -> Option<i8> {
5889    const NAMES: [&str; 12] = [
5890        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5891    ];
5892    let lower = name.to_lowercase();
5893    NAMES
5894        .iter()
5895        .position(|n| *n == lower.as_str())
5896        .map(|i| i as i8 + 1)
5897}
5898
5899/// Test probe for the shared resume policy's review-budget exclusion.
5900#[cfg(test)]
5901fn exhausted_review_budget(state: &RunState) -> bool {
5902    // A run whose task-head publication failed has nothing left to review:
5903    // resuming it only retries the publication, so it is never "exhausted".
5904    !crate::handover::can_resume(state)
5905        && state.status == RunStatus::Blocked
5906        && !state.released()
5907        && state.retired_to.is_none()
5908}
5909
5910/// This task's *most recent* run, if resuming it would actually make
5911/// progress. `short` is only for the warning's own message.
5912///
5913/// Only ever `runs.last()` — never a search back through older history.
5914/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
5915/// mint, oldest first, and every entry before the last one was already
5916/// superseded at the moment it was minted: the daemon only ever starts a new
5917/// run when the previous one was not worth resuming (unresumable, exhausted,
5918/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
5919/// opens a fresh review-only run alongside an older, already-failed
5920/// competition. Searching further back would let an old run that merely
5921/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
5922/// behind, say — get resumed instead of the fresh competition
5923/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
5924/// nothing asked to revisit.
5925///
5926/// Two runs paid for the "prefer resuming over restarting" half of this
5927/// lesson, which is why this still checks `runs.last()` rather than always
5928/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
5929/// task a moment later, duplicating two and a half hours of agent work. Then
5930/// b25f stalled on a judge that timed out and one that answered with no JSON
5931/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
5932/// **one second** later, buying three fresh implementations to reach the
5933/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
5934/// the second case: a stall is terminal, and its cheap recovery re-asks only
5935/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
5936/// that is technically `resumable()` but provably cannot progress must not
5937/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
5938/// no-op instead of the fresh competition it promises.
5939///
5940/// A load failure is warned about rather than silently read as "not
5941/// resumable": the alternative is exactly what let a schema mismatch on run
5942/// `eba2` fall through to a full re-competition with nobody told why.
5943/// `crate::conduct` is what actually offers a better answer than
5944/// `Runner::start` here (see `Recovery::Review`), once this task's next
5945/// failure shows it up as `held`/`failed` with the run state unreadable.
5946fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5947    unfinished_run_with(runs, short, RunState::load)
5948}
5949
5950/// [`unfinished_run`] with an injected state reader. Tests provide their
5951/// fixtures directly rather than touching the process-global run home.
5952pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5953where
5954    F: FnMut(&str) -> Result<RunState>,
5955{
5956    let mut id = runs.last()?.clone();
5957    let mut visited = std::collections::BTreeSet::new();
5958    let mut repo = None;
5959    loop {
5960        if !runs.contains(&id) || !visited.insert(id.clone()) {
5961            tracing::warn!("invalid or cyclic recovery authority for task {short}");
5962            return None;
5963        }
5964        let state = match load(&id) {
5965            Ok(state) if state.id == id => state,
5966            Ok(_) => return None,
5967            Err(e) => {
5968                tracing::warn!("could not read run {id} for task {short}: {e:#}");
5969                return None;
5970            }
5971        };
5972        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5973            return None;
5974        }
5975        repo = Some(state.repo.clone());
5976        if let Some(authority) = state.retired_to {
5977            id = authority;
5978            continue;
5979        }
5980        return (crate::handover::can_resume(&state)
5981            && state.liveness(false) != crate::run::Liveness::Live)
5982            .then_some(id);
5983    }
5984}
5985
5986/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
5987/// that [`attempt`] will resume it on its own?
5988///
5989/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
5990/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
5991/// injected reader like its sibling. An unreadable run is not awaiting
5992/// anything: it keeps going to the conductor as before.
5993fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5994where
5995    F: FnOnce(&str) -> Result<RunState>,
5996{
5997    // `Failed` stays: a record an older build wrote for a parked run.
5998    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5999        || task.fresh_start
6000        || task.review_branch.is_some()
6001    {
6002        return false;
6003    }
6004    let Some(id) = task.execution_runs().last() else {
6005        return false;
6006    };
6007    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6008}
6009
6010/// Which of the three ways [`attempt`] can mint or continue a run this task
6011/// should use.
6012#[derive(Debug, Clone, PartialEq, Eq)]
6013enum Starter {
6014    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
6015    /// and that still exists.
6016    Review(String),
6017    /// `crate::graph::Runner::resume` on an unfinished run of this task.
6018    Resume(String),
6019    /// `crate::graph::Runner::start`: a fresh competition.
6020    Start,
6021}
6022
6023/// A second bound independent of inputs and the resettable failure counter.
6024/// Count execution and failed-startup recovery records once per run. Startup
6025/// failures can retain unrecorded preparation assets without an execution pass.
6026/// Unknown history is not evidence that a new set of worktrees is affordable.
6027fn retained_attempt_hold(
6028    task: &Task,
6029    starter: &Starter,
6030    limit: usize,
6031    mut load: impl FnMut(&str) -> Result<RunState>,
6032) -> Option<String> {
6033    if limit == 0 || matches!(starter, Starter::Resume(_)) {
6034        return None;
6035    }
6036    let mut retained = 0;
6037    for id in task
6038        .runs
6039        .iter()
6040        .chain(task.startup_failures.iter().map(|failure| &failure.run))
6041        .collect::<std::collections::BTreeSet<_>>()
6042    {
6043        let state = match load(id) {
6044            Ok(state) if state.id == *id => state,
6045            _ => {
6046                return Some(format!(
6047                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6048                ));
6049            }
6050        };
6051        if state.retired_to.is_some() || state.released() {
6052            continue;
6053        }
6054        // Neither a completed status nor an empty candidate array proves that
6055        // all recovery sources (including unrecorded preparation) were retired.
6056        retained += 1;
6057    }
6058    (retained >= limit).then(|| format!(
6059        "[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."
6060    ))
6061}
6062
6063/// A selected public implementation overrides every historical candidate and pin.
6064fn selected_starter(
6065    selected: &crate::pr_recovery::Selection,
6066    previous: Option<&RunState>,
6067    unfinished: Option<&str>,
6068) -> Starter {
6069    if let Some(id) = unfinished
6070        && previous.is_some_and(|r| {
6071            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6072        })
6073    {
6074        Starter::Resume(id.to_owned())
6075    } else {
6076        Starter::Review(selected.branch.clone())
6077    }
6078}
6079
6080/// The owner's answer to this branch's divergence question, consumed from the
6081/// task so a later, different divergence asks again. The runner applies it
6082/// (see `Runner::review_taking_over`), after the earlier worktree is released.
6083fn take_divergence_answer(
6084    branch: &str,
6085    remote: &str,
6086    task: &mut Task,
6087) -> Option<crate::reconcile::Choice> {
6088    let summary = crate::reconcile::summary_for(branch, remote);
6089    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6090        (a.question == summary)
6091            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6092            .flatten()
6093            .map(|c| (i, c))
6094    })?;
6095    task.answers.remove(idx);
6096    Some(choice)
6097}
6098
6099/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
6100/// this attempt should use. Pure, and separate from [`attempt`], so the
6101/// routing itself is assertable without spawning a real graph or a git
6102/// process: `attempt`'s own `crate::git::branch_exists` call has already
6103/// happened by the time this is called.
6104///
6105/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
6106/// whose branch is gone falls all the way through to [`Starter::Start`], not
6107/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
6108/// old (likely `Blocked`) run in the first place, and a branch that vanished
6109/// out from under that choice is not evidence resuming it would fare better.
6110fn choose_starter(
6111    review_branch: Option<&str>,
6112    branch_exists: bool,
6113    unfinished: Option<&str>,
6114) -> Starter {
6115    match review_branch {
6116        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6117        Some(_) => Starter::Start,
6118        None => match unfinished {
6119            Some(id) => Starter::Resume(id.to_owned()),
6120            None => Starter::Start,
6121        },
6122    }
6123}
6124
6125/// Reuse a compatible latest review owner instead of taking its checked-out
6126/// branch into a new run. Different branches and changed criteria still use
6127/// the ordinary review/takeover policy.
6128fn review_retry_starter(
6129    task: &Task,
6130    previous: Option<&RunState>,
6131    branch: Option<&str>,
6132    exists: bool,
6133    unfinished: Option<&str>,
6134) -> Starter {
6135    if let Some(run) = previous
6136        && unfinished == Some(run.id.as_str())
6137        && run.reviewed_commits.is_some()
6138        && branch.is_some_and(|branch| {
6139            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6140        })
6141        && may_resume_run(run, task)
6142    {
6143        return Starter::Resume(run.id.clone());
6144    }
6145    match (branch, unfinished, &task.review_of) {
6146        (None, None, Some(branch)) => Starter::Review(branch.clone()),
6147        _ => choose_starter(branch, exists, unfinished),
6148    }
6149}
6150
6151/// Consume a retained review only while its authored criteria still match.
6152fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
6153    let branch = task.review_branch.take();
6154    let instruction = task.review_instruction.take();
6155    branch.filter(|branch| match &instruction {
6156        Some(authored) => *authored == task.instruction,
6157        // Legacy retained branches must agree with their prior run; only an
6158        // explicitly pinned review can proceed without recoverable provenance.
6159        None => previous.map_or_else(
6160            || task.review_of.as_ref() == Some(branch),
6161            |run| compatible_run_instruction(run, task),
6162        ),
6163    })
6164}
6165
6166/// A current explicit pin can select an otherwise incompatible run. Edits
6167/// and subsequent approvals invalidate pins selected for earlier criteria.
6168fn may_resume_run(run: &RunState, task: &Task) -> bool {
6169    if !task.assignment_accepts(run) {
6170        return false;
6171    }
6172    task.resume_override
6173        .as_ref()
6174        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6175        || compatible_run_instruction(run, task)
6176}
6177
6178/// Review scaffolding is execution context, not evidence of an operator edit.
6179pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6180    if let Some(authored) = &run.task_instruction {
6181        return compatible_instruction(authored, task);
6182    }
6183    if compatible_instruction(&run.instruction, task) {
6184        return true;
6185    }
6186    // Recognize only the existing generated review shapes on legacy runs.
6187    // Ordinary authored text with a similar heading is left intact.
6188    if run.reviewed_commits.is_some() {
6189        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6190            return strip_answers_block(authored, task).trim() == task.instruction.trim();
6191        }
6192        if let Some(branch) = &task.review_of {
6193            let canonical = format!(
6194                "Review the branch `{branch}` (review-only: no implementation, no judging)."
6195            );
6196            let generated = format!(
6197                "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"
6198            );
6199            return task.instruction == canonical && run.instruction.starts_with(&generated);
6200        }
6201    }
6202    false
6203}
6204
6205/// Compare authored instructions, excluding answer blocks appended by the daemon.
6206pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6207    strip_answers_block(old, task) == task.instruction
6208}
6209
6210/// Which repository a task runs in. A task that names none — the normal case
6211/// for one filed from a phone — runs in the daemon's own default.
6212fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6213    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6214        return fallback.to_path_buf();
6215    }
6216    task.repo.clone()
6217}
6218
6219/// The header [`append_answers`] appends operator answers under. Shared with
6220/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
6221/// rather than grown a new block on every resume.
6222const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6223
6224/// Render the first `count` answers in the block appended to an instruction.
6225fn answers_block(task: &Task, count: usize) -> String {
6226    let mut s = ANSWERS_HEADER.to_owned();
6227    for a in &task.answers[..count] {
6228        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6229    }
6230    s
6231}
6232
6233/// Render the approval independently of transient task state, so historical
6234/// suffixes remain recognizable after another explicit release.
6235fn resumption_block(r: &crate::queue::Resumption) -> String {
6236    format!(
6237        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6238         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6239        r.generation, r.at, r.instruction, r.answers_through,
6240    )
6241}
6242
6243/// Append audit answers and the latest explicit approval to the instruction.
6244fn append_answers(base: &str, task: &Task) -> String {
6245    let mut s = base.to_owned();
6246    if !task.answers.is_empty() {
6247        s.push_str(&answers_block(task, task.answers.len()));
6248    }
6249    if let Some(r) = &task.resumption {
6250        s.push_str(&resumption_block(r));
6251    }
6252    s
6253}
6254
6255/// Drop the prior answer block only when it is exactly the suffix this task
6256/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6257/// the task author is ordinary instruction text, not a block to remove.
6258fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6259    let mut instruction = instruction;
6260    for approval in task
6261        .resumption
6262        .iter()
6263        .chain(task.resumption_history.iter().rev())
6264    {
6265        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6266            instruction = base;
6267            break;
6268        }
6269    }
6270    for count in (1..=task.answers.len()).rev() {
6271        let block = answers_block(task, count);
6272        if let Some(base) = instruction.strip_suffix(&block) {
6273            return base;
6274        }
6275    }
6276    instruction
6277}
6278
6279/// The instruction handed to `Runner::start`: the task's own text, plus any
6280/// operator answers `crate::conduct` collected for it (see
6281/// [`Task::answers`]), so a decision the operator actually made reaches the
6282/// implementers rather than only clearing the block that was waiting on it.
6283///
6284/// Appended rather than merged into [`Task::instruction`] itself, so the
6285/// task's own record stays exactly what its author wrote.
6286fn instruction_for(task: &Task) -> String {
6287    append_answers(&task.instruction, task)
6288}
6289
6290/// The instruction a resumed run should carry on with: whatever it already
6291/// had, refreshed with the task's *current* operator answers.
6292///
6293/// A resumable run's own `RunState::instruction` predates any answer
6294/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6295/// the behaviour before this function existed — silently drops the very
6296/// decision the operator made to unblock it. Re-stripping any block this
6297/// function appended on an earlier resume before re-appending the current
6298/// list (rather than blindly appending again) is what keeps a task resumed
6299/// three times over three answered questions from carrying the same answer
6300/// three times.
6301fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6302    append_answers(strip_answers_block(old_instruction, task), task)
6303}
6304
6305/// Preserve the producer's verified boundary and target, independent of prose.
6306fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6307    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6308    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6309    if let Some(cause) = task.hold_notice_cause.as_mut() {
6310        cause.target = failure.map(|f| f.target.clone());
6311    }
6312}
6313
6314#[derive(Debug, thiserror::Error)]
6315#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6316struct MissingAttachment {
6317    name: String,
6318    path: PathBuf,
6319}
6320
6321/// The task's attachments as absolute paths, each checked to still exist.
6322fn task_attachments(
6323    queue: &Queue,
6324    task: &Task,
6325) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6326    let paths = queue.attachment_paths(task);
6327    for (name, path) in task.attachments.iter().zip(&paths) {
6328        if !path.is_file() {
6329            return Err(MissingAttachment {
6330                name: name.clone(),
6331                path: path.clone(),
6332            });
6333        }
6334    }
6335    Ok(paths)
6336}
6337
6338/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6339/// answers before handing it to `Runner` — the actual boundary between
6340/// [`choose_starter`]'s routing and the graph, factored out so it is
6341/// assertable without a real repository, git branch, or agent CLI.
6342///
6343/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6344/// instruction from the reviewed branch's own commit log because there is no
6345/// task statement to speak of for hand-written work, and splicing operator
6346/// answers into that text would contradict the very message it sends
6347/// reviewers ("there is no task statement").
6348fn prepare_instruction(
6349    starter: &Starter,
6350    old_instruction: Option<&str>,
6351    task: &Task,
6352) -> Option<String> {
6353    match starter {
6354        Starter::Start => Some(instruction_for(task)),
6355        Starter::Resume(_) => Some(resumed_instruction(
6356            old_instruction.expect("a resumed run always has a prior instruction"),
6357            task,
6358        )),
6359        Starter::Review(_) => None,
6360    }
6361}
6362
6363/// Persist a transition. A queue write failure is logged rather than fatal: the
6364/// run already happened, and taking the daemon down would only add a lost
6365/// backlog to a full disk.
6366fn record(queue: &Queue, task: &mut Task) {
6367    if let Err(e) = queue.put(task) {
6368        tracing::error!("could not record task {}: {e:#}", task.short());
6369        let notice = Notice::error(
6370            "loop:record",
6371            format!(
6372                "Task {} state could not be saved: {}. Check the disk.",
6373                task.id,
6374                e.to_string().lines().next().unwrap_or("unknown save error")
6375            ),
6376        )
6377        .link(Link::Task {
6378            id: task.id.clone(),
6379        });
6380        // The queue lives at `<home>/queue`, so its parent is the home.
6381        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6382            Some(home) => notices::raise_in(home, notice),
6383            None => notices::raise(notice),
6384        }
6385    }
6386}
6387
6388/// Every runnable task, in the order the loop should try them.
6389///
6390/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6391/// tail exists so that a claim somebody else holds costs the loop the next
6392/// candidate rather than a whole poll interval of idleness.
6393fn runnable(queue: &Queue) -> Vec<Task> {
6394    let mut tasks: Vec<Task> = queue
6395        .list()
6396        .into_iter()
6397        .filter(|t| t.status.runnable())
6398        .collect();
6399    tasks.sort_unstable_by(crate::queue::dispatch_order);
6400    tasks
6401}
6402
6403/// Why a run ended where it did, in one line, for [`Task::last_error`].
6404///
6405/// A stalled run names the seats the quota took out: "out of quota" is not
6406/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6407/// agent to replace or which plan to top up.
6408///
6409/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6410/// purpose: unlike `label`'s other callers (an internal log line, an
6411/// already-a-bug fallback message), this string becomes `Task::last_error`
6412/// verbatim, which the phone renders in the same alarm-styled box an
6413/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6414/// `.err` styling. A bare `verified_noop` there would read exactly like the
6415/// failure this whole feature exists to tell apart from one.
6416fn describe(state: &RunState) -> String {
6417    let p = phrases(&state.config.graph.language);
6418    let mut detail = if state.status == RunStatus::Stalled {
6419        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6420        seats.sort_unstable();
6421        seats.dedup();
6422        if seats.is_empty() {
6423            p.quorum_lost.to_owned()
6424        } else {
6425            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6426        }
6427    } else {
6428        format!("{}{}", p.run_ended, state.status.display_label())
6429    };
6430    if let Some(cause) = state.verification_blocking_cause() {
6431        detail.push_str(&format!(" ({cause})"));
6432    } else if let Some(last) = state.events.last() {
6433        // The review loop's "never answered" stop is the one event worth
6434        // translating; it is recognised from structured state, not by
6435        // matching the English event text (which stays as recorded).
6436        let unanswered = state
6437            .reviews
6438            .last()
6439            .filter(|r| {
6440                state.status == RunStatus::Blocked
6441                    && last.node == "review"
6442                    && r.incomplete()
6443                    && r.blocking == 0
6444                    && r.round == state.config.graph.review_rounds
6445                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6446            })
6447            .map(|r| (r.expected - r.answered, r.round));
6448        match unanswered {
6449            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6450                detail.push_str(&format!(
6451                    " ({}: {})",
6452                    last.node,
6453                    (p.reviewers_never_answered)(missing, rounds)
6454                ));
6455            }
6456            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6457        }
6458    }
6459    detail.push_str(&format!(" [run {}]", state.id));
6460    detail
6461}
6462
6463/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6464///
6465/// The task file lives in the backlog indefinitely; a diagnostic is an
6466/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6467/// stay small regardless of how much a gate command or a candidate printed.
6468const DIAGNOSTIC_MAX: usize = 4_000;
6469
6470/// Tail kept from a single failing command's output inside a diagnostic.
6471/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6472/// pointer for a human deciding whether to go read the full artifact by hand,
6473/// not a replacement for reading it.
6474const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6475
6476/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6477/// `magi task show` says more than the one-line reason in [`describe`].
6478///
6479/// The one-liner answers "where did the run stop"; this answers "what would a
6480/// human have found opening `artifacts/` by hand" — the point of the whole
6481/// feature is the case that one-liner actively misleads on: a run held as "no
6482/// candidate produced a change" can mean the implementer actually finished
6483/// the task (opened a PR, merged it, tagged a release) and only left a clean
6484/// local worktree behind, which reads as "nothing happened" unless someone
6485/// goes and reads what the agent actually said. `None` when the run carries
6486/// none of the three shapes this recognises — an ordinary run held for
6487/// something not diagnosable from `RunState` alone still explains itself
6488/// through `Task::last_error`.
6489fn diagnostic(state: &RunState) -> Option<String> {
6490    let mut parts: Vec<String> = Vec::new();
6491
6492    // Gate failure: which check(s), and the tail of what each printed.
6493    for o in state.gate.iter().filter(|o| !o.ok()) {
6494        parts.push(format!(
6495            "gate `{}` failed ({}):\n{}",
6496            o.command,
6497            notices::exit_status(o.code),
6498            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6499        ));
6500    }
6501
6502    // The land loop gave up because the fixer declined while checks were
6503    // still red: the message already names them (see `land::run`).
6504    if let Some(last) = state
6505        .events
6506        .iter()
6507        .rev()
6508        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6509    {
6510        parts.push(last.message.clone());
6511    }
6512
6513    // No viable candidate: every implementer's own final word, sanitized the
6514    // same way a judge would have read it, so a run that actually finished
6515    // the job does not read as an unexplained failure. A verified no-op is
6516    // called out ahead of its own summary and apart from an ordinary
6517    // failure's `why` — this is the one candidate shape whose diagnostic a
6518    // human is expected to actually judge, not just skim.
6519    if state.viable().is_empty() {
6520        for c in &state.candidates {
6521            if let Some(evidence) = &c.verified_noop {
6522                parts.push(format!(
6523                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6524                    c.label
6525                ));
6526            } else if !c.summary.trim().is_empty() {
6527                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6528            } else if let Some(why) = &c.failed {
6529                parts.push(format!("candidate {}: {why}", c.label));
6530            }
6531        }
6532    }
6533
6534    if parts.is_empty() {
6535        return None;
6536    }
6537    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6538    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6539    // back slightly over. Leave it enough room to always land under the
6540    // limit.
6541    Some(crate::run::tail(
6542        &parts.join("\n\n"),
6543        DIAGNOSTIC_MAX.saturating_sub(100),
6544    ))
6545}
6546
6547/// Stable lower-case name for a run status, for an internal log line and the
6548/// "graph stopped without reaching a terminal status" bug message in
6549/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6550/// doc for why that one reads [`RunStatus::display_label`] instead. One
6551/// definition of a status's name, on the type that owns it: this table used
6552/// to live here as a second copy, and a status renamed in one place would
6553/// have gone on reading correctly in the other.
6554fn label(status: RunStatus) -> &'static str {
6555    status.as_str()
6556}
6557
6558/// Parse a merge mode override.
6559pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6560    match mode {
6561        "none" => Ok(MergeMode::None),
6562        "local" => Ok(MergeMode::Local),
6563        "pr" => Ok(MergeMode::Pr),
6564        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6565    }
6566}
6567
6568/// Take the status lock, recovering from a poisoned one.
6569///
6570/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6571/// data, and the worst a poisoned lock can hold is a stale timestamp.
6572fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6573    mutex
6574        .lock()
6575        .unwrap_or_else(std::sync::PoisonError::into_inner)
6576}
6577
6578#[cfg(test)]
6579mod tests {
6580    use super::*;
6581    use crate::queue::{Source, TaskStatus};
6582    use crate::run::{Candidate, CommandOutcome};
6583    use pretty_assertions::assert_eq;
6584
6585    fn task() -> Task {
6586        Task::new(
6587            "add retries".to_owned(),
6588            "add retries".to_owned(),
6589            PathBuf::from("/repo"),
6590            Source::Human,
6591        )
6592    }
6593
6594    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6595        let job = crate::worker::Job {
6596            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6597            sequence: 1,
6598            kind: "task".into(),
6599            key: format!("task:{}", request.task),
6600            payload: serde_json::to_value(request).unwrap(),
6601            generation: "a".repeat(64),
6602            version: None,
6603            status: crate::worker::Status::Starting,
6604            result: None,
6605            pid: None,
6606            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6607            finished_at: None,
6608        };
6609        let dir = home.join("workers/jobs").join(&job.id);
6610        std::fs::create_dir_all(&dir).unwrap();
6611        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6612        job
6613    }
6614
6615    #[test]
6616    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6617        let home = tempfile::tempdir().unwrap();
6618        let request = TaskWorker {
6619            opts: Opts::default(),
6620            queue: home.path().join("queue"),
6621            task: "startup".into(),
6622            lane: PermitKind::Ordinary,
6623            standalone: false,
6624        };
6625        let job = starting_task_reservation(home.path(), &request);
6626        let error = task_worker_spawn_error(
6627            home.path(),
6628            &request,
6629            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6630        )
6631        .expect_err("our own reservation must not turn a failed spawn into a resync");
6632        let active = crate::worker::active(home.path()).unwrap();
6633        assert_eq!(active.len(), 1);
6634        assert_eq!(active[0].id, job.id);
6635        assert_eq!(active[0].status, crate::worker::Status::Starting);
6636        assert!(
6637            crate::worker::control(home.path(), &job.key)
6638                .unwrap()
6639                .is_none()
6640        );
6641        let notices = notices::Notices::at(home.path().join("notifications")).list();
6642        assert_eq!(notices.len(), 1);
6643        assert_eq!(notices[0].key, "loop:worker-startup");
6644        assert!(!notices[0].message.contains("private-error-detail"));
6645        assert!(notices[0].message.contains(&request.task));
6646        assert!(
6647            notices[0]
6648                .message
6649                .contains("could not be started or acknowledged")
6650        );
6651        assert!(notices[0].message.contains("worker.log"));
6652        assert_eq!(
6653            notices[0].link,
6654            Some(Link::Task {
6655                id: request.task.clone()
6656            })
6657        );
6658        assert!(format!("{error:#}").contains("private-error-detail"));
6659    }
6660
6661    #[test]
6662    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6663        let home = tempfile::tempdir().unwrap();
6664        let mut request = TaskWorker {
6665            opts: Opts::default(),
6666            queue: home.path().join("queue"),
6667            task: "handoff".into(),
6668            lane: PermitKind::Ordinary,
6669            standalone: true,
6670        };
6671        let job = starting_task_reservation(home.path(), &request);
6672        request.standalone = false;
6673        task_worker_spawn_error(
6674            home.path(),
6675            &request,
6676            anyhow::anyhow!("operation key is already reserved for a different request"),
6677        )
6678        .expect("a different standalone request is the handoff race, not our startup failure");
6679        let active = crate::worker::active(home.path()).unwrap();
6680        assert_eq!(active.len(), 1);
6681        assert_eq!(active[0].id, job.id);
6682        assert_eq!(active[0].payload, job.payload);
6683        assert!(
6684            notices::Notices::at(home.path().join("notifications"))
6685                .list()
6686                .is_empty()
6687        );
6688    }
6689
6690    #[test]
6691    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6692        let home = tempfile::tempdir().unwrap();
6693        let queue = Queue::at(home.path().join("queue"));
6694        let mut task = task();
6695        task.runs = vec!["previous".into()];
6696        queue.put(&mut task).unwrap();
6697        let request = TaskWorker {
6698            opts: Opts::default(),
6699            queue: home.path().join("queue"),
6700            task: task.id.clone(),
6701            lane: PermitKind::Ordinary,
6702            standalone: false,
6703        };
6704        let job = starting_task_reservation(home.path(), &request);
6705        let claims = current_work(home.path(), Timestamp::now());
6706        assert_eq!(claims.len(), 1);
6707        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6708        assert_eq!(claims[0].run, "previous");
6709        assert!(other_claims_run(&claims, "previous", None));
6710        // Only after confirming the executing caller may admission ignore
6711        // this exact projection. Cleanup continues to observe it as live.
6712        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6713        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6714    }
6715
6716    #[test]
6717    fn admission_excludes_only_the_callers_exact_reservation() {
6718        let own = Current {
6719            worker: Some("own".into()),
6720            task: "same-task".into(),
6721            run: "previous".into(),
6722        };
6723        assert!(!other_claims_run(
6724            std::slice::from_ref(&own),
6725            "previous",
6726            Some("own")
6727        ));
6728        assert!(other_claims_run(
6729            std::slice::from_ref(&own),
6730            "previous",
6731            None
6732        ));
6733        for worker in [None, Some("other".into())] {
6734            let other = Current {
6735                worker,
6736                ..own.clone()
6737            };
6738            assert!(other_claims_run(
6739                &[own.clone(), other],
6740                "previous",
6741                Some("own")
6742            ));
6743        }
6744        let legacy: Current =
6745            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6746        assert!(other_claims_run(&[legacy], "previous", Some("own")));
6747    }
6748
6749    #[test]
6750    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6751        let mut task = task();
6752        let mut run = run_state(RunStatus::Reviewing);
6753        run.task_instruction = Some(task.instruction.clone());
6754        run.reviewed_commits = Some(vec!["committed-fix".into()]);
6755        let branch = "magi/test/B";
6756        run.candidates.push(crate::run::Candidate {
6757            branch: branch.into(),
6758            ..candidate('B', "preserved work", false, None)
6759        });
6760        task.runs = vec![run.id.clone()];
6761        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6762        assert_eq!(
6763            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6764            Starter::Resume(run.id.clone())
6765        );
6766        assert!(matches!(
6767            review_retry_starter(
6768                &task,
6769                Some(&run),
6770                Some("different"),
6771                true,
6772                unfinished.as_deref()
6773            ),
6774            Starter::Review(_)
6775        ));
6776        assert_eq!(
6777            review_retry_starter(
6778                &task,
6779                Some(&run),
6780                Some(branch),
6781                false,
6782                unfinished.as_deref()
6783            ),
6784            Starter::Start
6785        );
6786        task.instruction.push_str(" changed criteria");
6787        assert!(matches!(
6788            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6789            Starter::Review(_)
6790        ));
6791        assert!(matches!(
6792            review_retry_starter(&task, Some(&run), Some(branch), true, None),
6793            Starter::Review(_)
6794        ));
6795    }
6796
6797    #[test]
6798    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6799        let dir = tempfile::tempdir().unwrap();
6800        let queue = Queue::at(dir.path().join("queue"));
6801        let mut task = task();
6802        task.status = TaskStatus::Running;
6803        task.attempts = 1;
6804        queue.put(&mut task).unwrap();
6805        let live = std::collections::BTreeSet::from([task.id.clone()]);
6806        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6807        drop(queue.claim(&task.id).unwrap());
6808        let saved = queue.get(&task.id).unwrap();
6809        assert_eq!(saved.status, TaskStatus::Running);
6810        assert_eq!(saved.attempts, 1);
6811        assert!(saved.last_error.is_none());
6812    }
6813
6814    #[test]
6815    fn standalone_workers_do_not_consume_scheduler_lanes() {
6816        let request = |task: &str, lane, standalone| TaskWorker {
6817            opts: Opts::default(),
6818            queue: PathBuf::from("/queue"),
6819            task: task.to_owned(),
6820            lane,
6821            standalone,
6822        };
6823        let mut jobs = vec![
6824            request("ordinary", PermitKind::Ordinary, false),
6825            request("standalone-urgent", PermitKind::Urgent, true),
6826            request("standalone-ordinary", PermitKind::Ordinary, true),
6827            request("decision", PermitKind::None, false),
6828        ];
6829        assert_eq!(available_slots(&jobs, 2), (1, 1));
6830        jobs.push(request("urgent", PermitKind::Urgent, false));
6831        assert_eq!(available_slots(&jobs, 2), (1, 0));
6832        assert_eq!(available_slots(&jobs, 0), (0, 0));
6833    }
6834
6835    #[test]
6836    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6837        let now = Timestamp::now();
6838        let mut reading = Reading {
6839            pid: Some(std::process::id()),
6840            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6841            ..Reading::default()
6842        };
6843        assert!(!reading.running(now));
6844        assert!(legacy_scheduler_running(&reading, now, 0));
6845        reading.worker_protocol = Some(1);
6846        assert!(!legacy_scheduler_running(&reading, now, 0));
6847    }
6848
6849    #[test]
6850    fn selected_public_head_overrides_historical_resume_and_pin() {
6851        let mut t = task();
6852        let mut old = run_state(RunStatus::Blocked);
6853        let selection = crate::pr_recovery::Selection {
6854            url: "url".into(),
6855            branch: format!("magi/task-{}", t.id),
6856            head: "a".repeat(40),
6857            source_head: None,
6858            source_run: None,
6859            source_proof: None,
6860            disposition: Some(crate::pr_recovery::Disposition::Review),
6861            instruction: t.instruction.clone(),
6862            approved_at: Timestamp::now(),
6863        };
6864        t.resume_override = Some(crate::queue::OperatorResume {
6865            pinned_run: Some(old.id.clone()),
6866            question_id: "choice".into(),
6867            at: Timestamp::now(),
6868            conductor_rehold: None,
6869            forced: false,
6870        });
6871        assert_eq!(
6872            selected_starter(&selection, Some(&old), Some(&old.id)),
6873            Starter::Review(selection.branch.clone())
6874        );
6875        old.pr_recovery = Some(selection.clone());
6876        assert_eq!(
6877            selected_starter(&selection, Some(&old), Some(&old.id)),
6878            Starter::Review(selection.branch.clone())
6879        );
6880        old.reviewed_commits = Some(vec!["implementation".into()]);
6881        assert_eq!(
6882            selected_starter(&selection, Some(&old), Some(&old.id)),
6883            Starter::Resume(old.id.clone())
6884        );
6885        let mut changed = selection.clone();
6886        changed.head = "b".repeat(40);
6887        assert_eq!(
6888            selected_starter(&changed, Some(&old), Some(&old.id)),
6889            Starter::Review(changed.branch)
6890        );
6891    }
6892
6893    #[test]
6894    fn candidate_transplant_failure_is_one_actionable_hold() {
6895        let dir = tempfile::tempdir().unwrap();
6896        let q = Queue::at(dir.path().join("queue"));
6897        let mut t = task();
6898        let mut state = run_state(RunStatus::Blocked);
6899        state.event("prep", "cannot apply referenced commit: conflict");
6900        state.prep_failure = Some("conflict".into());
6901        t.start(state.id.clone());
6902        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6903        assert_eq!(t.attempts, 1);
6904        assert_eq!(t.status, TaskStatus::Held);
6905        assert!(t.operator_held());
6906        assert!(!t.status.runnable());
6907        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6908        let first = t.chat_notice_key().unwrap();
6909        t.chat_notices.push(first.clone());
6910        t.release_operator("test", None);
6911        state.id = "another-unprepared-run".into();
6912        t.start(state.id.clone());
6913        finish_attempt(
6914            3,
6915            &q,
6916            &mut t,
6917            &state,
6918            &[],
6919            Err(anyhow::anyhow!("still conflicts")),
6920        );
6921        assert_eq!(
6922            t.chat_notice_key().as_ref(),
6923            Some(&first),
6924            "no work happened"
6925        );
6926        t.release_operator("test", None);
6927        state.prep_failure = None;
6928        state.status = RunStatus::Failed;
6929        state.begin_pass();
6930        t.start(state.id.clone());
6931        finish_attempt(
6932            1,
6933            &q,
6934            &mut t,
6935            &state,
6936            &[],
6937            Err(anyhow::anyhow!("new gate failure")),
6938        );
6939        let failure = t.chat_notice_key().unwrap();
6940        assert_ne!(failure, first, "approved recovery reached a real failure");
6941        t.release_operator("test", None);
6942        state.begin_pass();
6943        t.start(state.id.clone());
6944        finish_attempt(
6945            1,
6946            &q,
6947            &mut t,
6948            &state,
6949            &[],
6950            Err(anyhow::anyhow!("new failure on resume")),
6951        );
6952        assert_ne!(
6953            t.chat_notice_key().as_ref(),
6954            Some(&failure),
6955            "a new settled pass"
6956        );
6957    }
6958
6959    #[test]
6960    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6961        for source in ["cli", "web"] {
6962            let mut t = task();
6963            let mut run = run_state(RunStatus::Blocked);
6964            run.instruction = "Run A original criteria".into();
6965            run.task_instruction = Some(run.instruction.clone());
6966            t.start(run.id.clone());
6967            t.release_operator("choice", Some("resume-question"));
6968            t.resume_override = Some(crate::queue::OperatorResume {
6969                question_id: "resume-question".into(),
6970                at: Timestamp::now(),
6971                conductor_rehold: None,
6972                forced: true,
6973                pinned_run: Some(run.id.clone()),
6974            });
6975            t.hold_machine(Some("not enough free space to start a run".into()));
6976            let mut unchanged = t.clone();
6977            unchanged
6978                .edit("title changed".into(), unchanged.instruction.clone())
6979                .unwrap();
6980            unchanged.release_operator(source, None);
6981            assert_eq!(
6982                unchanged
6983                    .resume_override
6984                    .as_ref()
6985                    .unwrap()
6986                    .pinned_run
6987                    .as_deref(),
6988                Some(run.id.as_str())
6989            );
6990            assert!(!compatible_run_instruction(&run, &unchanged));
6991            assert!(may_resume_run(&run, &unchanged));
6992
6993            t.edit(
6994                "approved recovery".into(),
6995                "Reuse measured PR head B; fix Clippy; review".into(),
6996            )
6997            .unwrap();
6998            assert!(t.resume_override.is_none());
6999            t.release_operator(source, None);
7000            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7001            assert!(reloaded.resume_override.is_none());
7002            assert!(!may_resume_run(&run, &reloaded));
7003            let unfinished =
7004                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7005                    .filter(|_| may_resume_run(&run, &reloaded));
7006            assert_eq!(
7007                choose_starter(None, false, unfinished.as_deref()),
7008                Starter::Start
7009            );
7010            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7011            assert_eq!(
7012                reloaded.resumption_history[0].question_id.as_deref(),
7013                Some("resume-question")
7014            );
7015
7016            // A revision already persisted with the old approval/pin is also
7017            // invalidated when the new operator release is recorded.
7018            unchanged.instruction = "Reuse measured PR head B".into();
7019            unchanged.hold_machine(Some("disk hold".into()));
7020            unchanged.release_operator(source, None);
7021            assert!(unchanged.resume_override.is_none());
7022            assert!(!may_resume_run(&run, &unchanged));
7023        }
7024    }
7025
7026    #[test]
7027    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7028        let mut t = task();
7029        let mut run = run_state(RunStatus::Blocked);
7030        t.review_of = Some("approved-head".into());
7031        t.instruction =
7032            "Review the branch `approved-head` (review-only: no implementation, no judging)."
7033                .into();
7034        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();
7035        run.reviewed_commits = Some(vec!["Commit log".into()]);
7036        t.start(run.id.clone());
7037        t.hold_machine(Some("interrupted review".into()));
7038        t.release_operator("cli", None);
7039        assert!(
7040            compatible_run_instruction(&run, &t),
7041            "legacy explicit review remains resumable"
7042        );
7043        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7044            .filter(|_| compatible_run_instruction(&run, &t));
7045        assert_eq!(
7046            choose_starter(None, false, unfinished.as_deref()),
7047            Starter::Resume(run.id.clone())
7048        );
7049        run.task_instruction = Some(t.instruction.clone());
7050        assert!(compatible_run_instruction(&run, &t));
7051        let reloaded: RunState =
7052            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7053        assert!(compatible_run_instruction(&reloaded, &t));
7054        t.edit(
7055            "new approved head".into(),
7056            "Reuse measured PR head B".into(),
7057        )
7058        .unwrap();
7059        assert!(!compatible_run_instruction(&run, &t));
7060
7061        // Legacy recovery reviews retain the task criteria ahead of the log.
7062        t.review_of = None;
7063        t.instruction = "Fix Clippy on approved head".into();
7064        run.task_instruction = None;
7065        run.instruction = format!(
7066            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7067            t.instruction
7068        );
7069        assert!(compatible_run_instruction(&run, &t));
7070        t.instruction.push('\n');
7071        assert!(
7072            compatible_run_instruction(&run, &t),
7073            "legacy generated review trimmed the original criteria"
7074        );
7075        t.hold_for_handover(Some("approved-head".into()), "refused".into());
7076        let mut unchanged = t.clone();
7077        assert_eq!(
7078            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
7079            Some("approved-head")
7080        );
7081        t.edit("new plan".into(), "Reuse measured PR head B".into())
7082            .unwrap();
7083        assert!(take_review_branch(&mut t, Some(&run)).is_none());
7084        assert!(!compatible_run_instruction(&run, &t));
7085        t.review_branch = Some("approved-head".into());
7086        t.review_instruction = None;
7087        assert!(
7088            take_review_branch(&mut t, Some(&run)).is_none(),
7089            "legacy retained candidate cannot replace a revised approved head"
7090        );
7091    }
7092
7093    #[test]
7094    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7095        let home = crate::run::test_home();
7096        crate::run::pin_test_home();
7097        let dir = tempfile::tempdir().unwrap();
7098        let queue = Queue::at(dir.path().join("queue"));
7099        for resume in [true, false] {
7100            let state = run_state(RunStatus::Blocked);
7101            let mut t = task();
7102            t.start(state.id.clone());
7103            let action = if resume {
7104                ask::ChoiceAction::Resume {
7105                    run: state.id.clone(),
7106                }
7107            } else {
7108                ask::ChoiceAction::Requeue
7109            };
7110            let mut q = action_question(&state.id, action);
7111            q.status = ask::QuestionStatus::Open;
7112            q.answer = None;
7113            q.answered_at = None;
7114            t.fail("run stopped with a question", 3);
7115            hold_if_runnable(&queue, &mut t);
7116            assert!(t.operator_decided_at.is_none());
7117            assert!(t.operator_held());
7118            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7119            let expected = if resume {
7120                ActionDecision::Resume(state.id.clone())
7121            } else {
7122                ActionDecision::Requeue
7123            };
7124            assert_eq!(
7125                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7126                expected
7127            );
7128            t.hold_manual(Some("later explicit hold".into()));
7129            assert_eq!(
7130                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7131                ActionDecision::Stale
7132            );
7133        }
7134    }
7135
7136    #[test]
7137    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7138        let mut t = task();
7139        t.answers.push(crate::queue::AnsweredQuestion {
7140            question: "Inspect the remote?".into(),
7141            answer: "Inspect then wait".into(),
7142        });
7143        let old = instruction_for(&t);
7144        assert!(compatible_instruction(&old, &t));
7145        t.instruction = "Reuse approved PR head and review".into();
7146        t.release_operator("cli", None);
7147        assert!(!compatible_instruction(&old, &t));
7148        let approved = instruction_for(&t);
7149        assert!(approved.contains("waiting premises are superseded"));
7150        assert!(compatible_instruction(&approved, &t));
7151        assert_eq!(resumed_instruction(&approved, &t), approved);
7152        t.release_operator("web", None);
7153        assert!(compatible_instruction(&approved, &t));
7154        assert_eq!(t.resumption_history.len(), 1);
7155        t.start("run".into());
7156        assert!(instruction_for(&t).contains("Explicit operator resumption"));
7157    }
7158
7159    /// A run that stopped on an infrastructure wait asked no agent anything:
7160    /// the task is held by the machine under a `[resource]` reason (resumable,
7161    /// re-checked by triage), and the attempt it started is given back.
7162    #[test]
7163    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7164        let mut state = RunState::new(
7165            PathBuf::from("/repo"),
7166            "main".into(),
7167            "base".into(),
7168            "task".into(),
7169            Config::default(),
7170        );
7171        state.status = RunStatus::Landing;
7172        state.parked = true;
7173        state.pr_pushed_head = Some("head".into());
7174        state.land_unrelated = Some(
7175            serde_json::from_value(serde_json::json!({
7176                "head": "head", "question": "ci-question",
7177                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7178            }))
7179            .unwrap(),
7180        );
7181        let mut t = task();
7182        t.start(state.id.clone());
7183        let verdict = Verdict {
7184            status: RunStatus::Landing,
7185            left_pr: true,
7186            quota_hit: false,
7187            parked: true,
7188            no_viable_candidates: false,
7189        };
7190        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7191        assert_eq!(t.attempts, 0);
7192        assert_eq!(t.status, TaskStatus::Held);
7193        assert!(!t.operator_held());
7194        assert!(
7195            t.hold_reason
7196                .as_deref()
7197                .unwrap()
7198                .starts_with("[ci-unrelated]")
7199        );
7200        // A second settlement must not refund an earlier task attempt.
7201        t.attempts = 1;
7202        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7203        assert_eq!(t.attempts, 1);
7204        assert_eq!(t.passes.len(), 1);
7205        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7206        state.pr_pushed_head = Some("new-head".into());
7207        state.parked = false;
7208        state.status = RunStatus::Blocked;
7209        let stale = Verdict {
7210            status: RunStatus::Blocked,
7211            parked: false,
7212            ..verdict
7213        };
7214        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7215        assert_eq!(t.attempts, 1);
7216        // A new execution pass can refund its own newly charged attempt.
7217        state.begin_pass();
7218        state.begin_pass();
7219        state.status = RunStatus::Landing;
7220        state.parked = true;
7221        state.pr_pushed_head = Some("head".into());
7222        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7223        assert_eq!(t.attempts, 0);
7224        assert_eq!(t.passes.len(), 2);
7225    }
7226
7227    #[test]
7228    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7229        let mut state = run_state(RunStatus::Failed);
7230        state
7231            .quota
7232            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7233        state.begin_pass();
7234        let mut t = task();
7235        t.start(state.id.clone());
7236        reclaim(&mut t, Some(state), 2, "en");
7237        assert_eq!(t.attempts, 1);
7238    }
7239
7240    #[test]
7241    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7242        let mut state = run_state(RunStatus::Blocked);
7243        let losses: Vec<_> = ["alpha", "beta"]
7244            .into_iter()
7245            .enumerate()
7246            .map(|(i, agent)| {
7247                QuotaLoss::from_report(
7248                    format!("advisor-{i}"),
7249                    "advise",
7250                    Some(&crate::agent::Quota {
7251                        cause: crate::agent::QuotaCause::Authentication,
7252                        agent: agent.to_owned(),
7253                        reset: None,
7254                    }),
7255                )
7256            })
7257            .collect();
7258        crate::graph::block_machine_outage(&mut state, "advise", &losses);
7259        state.quota = losses;
7260        let mut t = task();
7261        t.start(state.id.clone());
7262        let verdict = Verdict {
7263            status: state.status,
7264            left_pr: false,
7265            quota_hit: true,
7266            parked: false,
7267            no_viable_candidates: true,
7268        };
7269        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7270        assert_eq!(t.attempts, 0);
7271        assert_eq!(t.status, TaskStatus::Held);
7272        assert!(!t.operator_held());
7273        let reason = t.hold_reason.as_deref().unwrap();
7274        assert!(reason.starts_with("[authentication]"));
7275        assert!(
7276            reason.contains("alpha")
7277                && reason.contains("beta")
7278                && reason.contains("re-authenticate")
7279        );
7280        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7281        // Orphan recovery uses the same settlement and cannot spend an attempt.
7282        let mut orphan = task();
7283        orphan.start(state.id.clone());
7284        reclaim(&mut orphan, Some(state), 2, "en");
7285        assert_eq!(orphan.attempts, 0);
7286        assert_eq!(orphan.status, TaskStatus::Held);
7287    }
7288
7289    #[test]
7290    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7291        let mut state = RunState::new(
7292            PathBuf::from("/repo"),
7293            "main".to_owned(),
7294            "abc1234".to_owned(),
7295            "task".to_owned(),
7296            Config::default(),
7297        );
7298        state.status = RunStatus::Blocked;
7299        state.resource_block = Some(crate::run::ResourceBlock {
7300            cause: crate::run::ResourceBlockCause::Other,
7301            node: "graft".to_owned(),
7302            kind: "shared build cache".to_owned(),
7303            detail: "timed out".to_owned(),
7304            at: jiff::Timestamp::now(),
7305        });
7306        let mut t = task();
7307        t.start("20260902-000000-aaaa".to_owned());
7308        assert_eq!(t.attempts, 1);
7309        let verdict = Verdict {
7310            status: RunStatus::Blocked,
7311            left_pr: false,
7312            quota_hit: false,
7313            parked: false,
7314            no_viable_candidates: false,
7315        };
7316        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7317        assert_eq!(t.status, TaskStatus::Held);
7318        assert_eq!(t.attempts, 0, "the attempt is refunded");
7319        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7320        assert!(
7321            !t.operator_held(),
7322            "a machine hold, released without a human"
7323        );
7324
7325        let mut selected = task();
7326        selected.start("20260902-000000-cccc".into());
7327        selected.replacement = Some(crate::merge_decision::Replacement {
7328            question: "fixture".into(),
7329            run: "earlier".into(),
7330            pr: "https://example.invalid/pr/1".into(),
7331            agent: "selected".into(),
7332            context: "fixture".into(),
7333        });
7334        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7335        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7336        assert_eq!(selected.attempts, 0);
7337        assert!(
7338            !selected.operator_held(),
7339            "a selected agent also retains a machine resource hold"
7340        );
7341        assert!(
7342            selected
7343                .hold_reason
7344                .as_deref()
7345                .unwrap()
7346                .starts_with("[resource] ")
7347        );
7348
7349        // A park request outranks it: still the operator's doing.
7350        let mut p = task();
7351        p.start("20260902-000000-bbbb".to_owned());
7352        settle_and_diagnose(
7353            &mut p,
7354            Verdict {
7355                parked: true,
7356                ..verdict
7357            },
7358            "parked",
7359            2,
7360            &state,
7361        );
7362        assert_eq!(p.status, TaskStatus::Parked);
7363        assert_eq!(
7364            p.attempts, 0,
7365            "parking refunds once rather than also settling the resource hold"
7366        );
7367    }
7368
7369    #[test]
7370    fn record_failure_notice_links_the_task() {
7371        let dir = tempfile::tempdir().unwrap();
7372        // A regular file where the queue directory should be makes every
7373        // `put` fail, on every platform and whoever runs the test.
7374        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7375        let queue = Queue::at(dir.path().join("queue"));
7376        let mut t = interrupt_task("rec-fail-1");
7377        record(&queue, &mut t);
7378
7379        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7380        assert_eq!(found.len(), 1);
7381        assert_eq!(found[0].key, "loop:record");
7382        assert_eq!(
7383            found[0].link,
7384            Some(Link::Task {
7385                id: "rec-fail-1".to_owned()
7386            })
7387        );
7388    }
7389
7390    /// A runnable task marked to interrupt, with an id fixed for assertions
7391    /// rather than the random one [`Task::new`] mints.
7392    fn interrupt_task(id: &str) -> Task {
7393        let mut t = task();
7394        t.id = id.to_owned();
7395        t.interrupt = true;
7396        t
7397    }
7398
7399    /// An ordinary runnable task with an id fixed for assertions.
7400    fn task_with_id(id: &str) -> Task {
7401        let mut t = task();
7402        t.id = id.to_owned();
7403        t
7404    }
7405
7406    /// A runnable task marked `--urgent`, with an id fixed for assertions.
7407    fn urgent_task(id: &str) -> Task {
7408        let mut t = task();
7409        t.id = id.to_owned();
7410        t.urgent = true;
7411        t
7412    }
7413
7414    #[test]
7415    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7416        let dir = tempfile::tempdir().unwrap();
7417        let queue = Queue::at(dir.path().join("queue"));
7418        let mut parked = task_with_id("parked");
7419        parked.start("run".into());
7420        parked.park("upgrade");
7421        parked.record_pass_at(
7422            "run",
7423            0,
7424            Some(Timestamp::now()),
7425            1,
7426            Some(crate::run::ParkCause::Upgrade {
7427                from: "old".into(),
7428                to: None,
7429            }),
7430        );
7431        let mut fresh = task_with_id("fresh");
7432        fresh.priority = 100;
7433        let mut urgent_task = urgent_task("urgent");
7434        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7435            queue.put(t).unwrap();
7436        }
7437        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7438        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7439        let candidates = runnable(&queue);
7440        assert_eq!(candidates[0].id, parked.id);
7441        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7442        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7443        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7444        drop(first);
7445        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7446        let next = runnable(&queue)
7447            .into_iter()
7448            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7449            .unwrap();
7450        assert_eq!(next.task.id, fresh.id);
7451        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7452        drop(claimed_elsewhere);
7453        drop(next);
7454        assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7455    }
7456
7457    #[test]
7458    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7459        let dir = tempfile::tempdir().unwrap();
7460        let queue = Queue::at(dir.path().join("queue"));
7461        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7462        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7463        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7464        let mut first = task();
7465        queue.put(&mut first).unwrap();
7466        let stale_plain = queue.get(&first.id).unwrap();
7467        first.set_urgent(true).unwrap();
7468        queue.put(&mut first).unwrap();
7469        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7470        let mut second = urgent_task("second");
7471        queue.put(&mut second).unwrap();
7472        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7473        drop(queue.claim(&second.id).unwrap());
7474        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7475        drop(dispatched);
7476        let stale_urgent = queue.get(&first.id).unwrap();
7477        first.set_urgent(false).unwrap();
7478        queue.put(&mut first).unwrap();
7479        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7480        assert_eq!(urgent.available_permits(), 1);
7481        drop(queue.claim(&first.id).unwrap());
7482        drop(occupied);
7483    }
7484
7485    #[test]
7486    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7487        let dir = tempfile::tempdir().unwrap();
7488        let queue = Queue::at(dir.path().join("queue"));
7489        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7490        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7491        let mut t = task();
7492        queue.put(&mut t).unwrap();
7493        for enabled in [true, false] {
7494            let stale = queue.get(&t.id).unwrap();
7495            t.set_urgent(enabled).unwrap();
7496            queue.put(&mut t).unwrap();
7497            assert_ne!(stale.urgent, enabled);
7498            let DispatchClaim {
7499                task: fresh,
7500                claim,
7501                permit,
7502            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7503            assert_eq!(fresh.urgent, enabled);
7504            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7505            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7506            assert!(queue.claim(&t.id).is_err());
7507            assert_eq!(fresh.attempts, stale.attempts);
7508            drop((claim, permit));
7509            assert_eq!(ordinary.available_permits(), 1);
7510            assert_eq!(urgent.available_permits(), 1);
7511        }
7512        t.set_urgent(true).unwrap();
7513        queue.put(&mut t).unwrap();
7514        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7515        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7516        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7517        drop(queue.claim(&t.id).unwrap());
7518        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7519        drop(occupied);
7520        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7521        drop(queue.claim(&t.id).unwrap());
7522        let held = queue.claim(&t.id).unwrap();
7523        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7524        drop(held);
7525        t.status = TaskStatus::Held;
7526        queue.put(&mut t).unwrap();
7527        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7528        drop(queue.claim(&t.id).unwrap());
7529        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7530        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7531        drop(queue.claim(&t.id).unwrap());
7532        assert_eq!(urgent.available_permits(), 1);
7533    }
7534
7535    /// The land-resume exemption wins outright, whether or not the candidate
7536    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7537    /// queue behind anything" guarantee cannot be weaker just because the
7538    /// same task was also filed with `--urgent`.
7539    #[test]
7540    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7541        assert_eq!(permit_kind(true, false), PermitKind::None);
7542        assert_eq!(permit_kind(true, true), PermitKind::None);
7543    }
7544
7545    /// The one property this whole feature exists for: `--urgent` draws from
7546    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7547    /// ordinary candidate draws from the ordinary pool exactly as before,
7548    /// untouched by the urgent slot's existence.
7549    #[test]
7550    fn permit_kind_separates_urgent_from_ordinary() {
7551        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7552        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7553    }
7554
7555    /// The exact wiring `attempt` runs before minting anything: a config's
7556    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7557    /// Free space is injected rather than asked of the real disk - the point
7558    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7559    /// is deterministic on every machine this test runs on, never dependent
7560    /// on how full the CI runner's own disk happens to be.
7561    #[test]
7562    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7563        let cfg = Config::default();
7564        let repo = Path::new("/any/repo/path");
7565
7566        let reason =
7567            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7568        assert!(reason.contains("1024"), "{reason}");
7569        assert!(
7570            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7571            "{reason}"
7572        );
7573
7574        assert_eq!(
7575            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7576            None,
7577            "exactly at the floor is open"
7578        );
7579        assert_eq!(
7580            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7581            None,
7582            "comfortably above the floor is open"
7583        );
7584    }
7585
7586    #[test]
7587    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7588        let mut cfg = Config::default();
7589        cfg.disk.min_free_bytes = 0;
7590        let repo = Path::new("/any/repo/path");
7591        assert_eq!(
7592            disk_gate_with(repo, &cfg, |_| Ok(0)),
7593            None,
7594            "a zero floor never measures at all"
7595        );
7596    }
7597
7598    #[test]
7599    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7600        let cfg = Config::default();
7601        let repo = Path::new("/any/repo/path");
7602        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7603            .expect("a measurement failure must close the gate, not open it");
7604        assert!(reason.contains("could not measure"), "{reason}");
7605    }
7606
7607    #[test]
7608    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7609        let ordinary = task();
7610        let next = advance_interrupt(
7611            Interrupt::Idle,
7612            std::slice::from_ref(&ordinary.id),
7613            std::slice::from_ref(&ordinary),
7614        );
7615        assert_eq!(next, Interrupt::Idle);
7616    }
7617
7618    #[test]
7619    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7620        // Nothing to interrupt - this is just an ordinary candidate, and the
7621        // loop's normal dispatch will pick it up like any other.
7622        let marked = interrupt_task("marked");
7623        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7624        assert_eq!(next, Interrupt::Idle);
7625    }
7626
7627    #[test]
7628    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7629        let marked = interrupt_task("marked");
7630        let next = advance_interrupt(
7631            Interrupt::Idle,
7632            &["running".to_owned()],
7633            std::slice::from_ref(&marked),
7634        );
7635        assert_eq!(
7636            next,
7637            Interrupt::Parking {
7638                parked: vec!["running".to_owned()],
7639                interrupt_task: "marked".to_owned(),
7640            }
7641        );
7642    }
7643
7644    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
7645    /// one run can be in flight when a task becomes runnable and marked.
7646    /// Parking all of them would mean `Resuming` later has more than one id
7647    /// to release back to ordinary dispatch, which cannot be made safe
7648    /// against that same setting's own extra concurrency slots letting two
7649    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
7650    /// The simplification the task's own constraints ask for: do not begin
7651    /// a sequence at all until the herd settles back to exactly one.
7652    #[test]
7653    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7654        let marked = interrupt_task("marked");
7655
7656        let two = advance_interrupt(
7657            Interrupt::Idle,
7658            &["a".to_owned(), "b".to_owned()],
7659            std::slice::from_ref(&marked),
7660        );
7661        assert_eq!(two, Interrupt::Idle);
7662
7663        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7664        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7665    }
7666
7667    #[test]
7668    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7669        let state = Interrupt::Parking {
7670            parked: vec!["running".to_owned()],
7671            interrupt_task: "marked".to_owned(),
7672        };
7673        // Still in flight: no change.
7674        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7675        assert_eq!(still_going, state);
7676
7677        // Left flight, but the interrupt task has not been dispatched yet on
7678        // this tick - stays `Parking` so `interrupt_gate` can let it through,
7679        // as long as it is still runnable.
7680        let stopped_but_not_yet_dispatched =
7681            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7682        assert_eq!(stopped_but_not_yet_dispatched, state);
7683
7684        // Left flight, and the interrupt task is now in flight itself.
7685        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7686        assert_eq!(
7687            dispatched,
7688            Interrupt::Running {
7689                parked: vec!["running".to_owned()],
7690                interrupt_task: "marked".to_owned(),
7691            }
7692        );
7693    }
7694
7695    #[test]
7696    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7697        let state = Interrupt::Running {
7698            parked: vec!["running".to_owned()],
7699            interrupt_task: "marked".to_owned(),
7700        };
7701        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7702        assert_eq!(still_running, state);
7703
7704        // Whatever it ended as - merged, failed, held - is not this
7705        // function's concern: leaving flight is the only trigger, driven
7706        // straight off the same in-flight list `poll` already reaps. It does
7707        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
7708        // why that would let an unrelated task start ahead of, or alongside,
7709        // the guaranteed resume.
7710        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7711        assert_eq!(
7712            ended,
7713            Interrupt::Resuming {
7714                parked: vec!["running".to_owned()]
7715            }
7716        );
7717    }
7718
7719    #[test]
7720    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7721        let state = Interrupt::Resuming {
7722            parked: vec!["running".to_owned()],
7723        };
7724        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7725        assert_eq!(still_waiting, state);
7726
7727        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7728        assert_eq!(dispatched, Interrupt::Idle);
7729    }
7730
7731    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
7732    /// or otherwise moved on by an operator with no claim standing in the
7733    /// way - must not wedge the sequence (and so the whole loop's dispatch,
7734    /// via `interrupt_gate`) waiting forever for a dispatch that can never
7735    /// come. The parked run still gets its resume.
7736    #[test]
7737    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7738    {
7739        let state = Interrupt::Parking {
7740            parked: vec!["running".to_owned()],
7741            interrupt_task: "marked".to_owned(),
7742        };
7743        // `marked` has been held/blocked/deleted since the sequence began:
7744        // it no longer appears in `runnable` at all.
7745        let next = advance_interrupt(state, &[], &[]);
7746        assert_eq!(
7747            next,
7748            Interrupt::Resuming {
7749                parked: vec!["running".to_owned()]
7750            },
7751            "abandoning the interrupt must not abandon the resume it owes"
7752        );
7753    }
7754
7755    /// The same abandonment, one step later: `Resuming` itself must not wait
7756    /// forever for a parked task that has since become unrunnable.
7757    #[test]
7758    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7759        let state = Interrupt::Resuming {
7760            parked: vec!["running".to_owned()],
7761        };
7762        let next = advance_interrupt(state, &[], &[]);
7763        assert_eq!(
7764            next,
7765            Interrupt::Idle,
7766            "nothing is left to wait for; the loop must not stay wedged"
7767        );
7768    }
7769
7770    #[test]
7771    fn disabled_by_config_the_sequence_can_never_leave_idle() {
7772        let marked = interrupt_task("marked");
7773        let next = advance_interrupt_tick(
7774            false,
7775            Interrupt::Idle,
7776            &["running".to_owned()],
7777            std::slice::from_ref(&marked),
7778        );
7779        assert_eq!(
7780            next,
7781            Interrupt::Idle,
7782            "an unmarked, unconfigured daemon must behave exactly as before"
7783        );
7784    }
7785
7786    #[test]
7787    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7788        let state = Interrupt::Parking {
7789            parked: vec!["running".to_owned()],
7790            interrupt_task: "marked".to_owned(),
7791        };
7792        let candidates = vec![interrupt_task("marked"), task()];
7793        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7794        assert!(
7795            allowed.is_empty(),
7796            "nothing may dispatch - not even the interrupt task itself - \
7797             until the parked run has actually stopped"
7798        );
7799    }
7800
7801    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
7802    /// grow a special case for it: an urgent candidate that is not the
7803    /// interrupt task withholds exactly like an ordinary one for as long as
7804    /// the parked run it is racing has not actually left flight. A version
7805    /// of this feature once bypassed the gate for urgent candidates, on the
7806    /// theory that a genuinely separate concurrency lane could not collide
7807    /// with 75dd's own; it could, and did - the bypassed task dispatched
7808    /// alongside a run 75dd's own state machine had only *asked* to park,
7809    /// not yet confirmed gone, which is exactly the second run
7810    /// `Interrupt::Parking`'s own doc says must never happen. There is no
7811    /// tick during Parking/Running/Resuming where letting an extra
7812    /// candidate through is safe, urgent or not - the parked run may still
7813    /// be genuinely mid-call.
7814    #[test]
7815    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7816        for state in [
7817            Interrupt::Parking {
7818                parked: vec!["running".to_owned()],
7819                interrupt_task: "marked".to_owned(),
7820            },
7821            Interrupt::Running {
7822                parked: vec!["running".to_owned()],
7823                interrupt_task: "marked".to_owned(),
7824            },
7825            Interrupt::Resuming {
7826                parked: vec!["running".to_owned()],
7827            },
7828        ] {
7829            let candidates = vec![
7830                interrupt_task("marked"),
7831                urgent_task("hot"),
7832                task_with_id("ordinary"),
7833            ];
7834            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7835            assert!(
7836                !allowed.iter().any(|t| t.id == "hot"),
7837                "an urgent candidate must wait out the same gate as anything \
7838                 else while the run it would run alongside has not actually \
7839                 left flight, for state {state:?}: {allowed:?}"
7840            );
7841        }
7842    }
7843
7844    /// The one case where marking a task `--urgent` and `interrupt` at once
7845    /// is not redundant: once the interrupt sequence's own guaranteed
7846    /// resume/dispatch actually admits the task, it is unaffected by also
7847    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
7848    /// never on the urgent flag.
7849    #[test]
7850    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7851        let state = Interrupt::Resuming {
7852            parked: vec!["hot".to_owned()],
7853        };
7854        let candidates = vec![urgent_task("hot"), task()];
7855        let allowed = interrupt_gate(&state, &[], candidates);
7856        assert_eq!(
7857            allowed.iter().filter(|t| t.id == "hot").count(),
7858            1,
7859            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7860        );
7861    }
7862
7863    #[test]
7864    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7865        let state = Interrupt::Parking {
7866            parked: vec!["running".to_owned()],
7867            interrupt_task: "marked".to_owned(),
7868        };
7869        let other = task();
7870        let candidates = vec![interrupt_task("marked"), other.clone()];
7871        let allowed = interrupt_gate(&state, &[], candidates);
7872        assert_eq!(allowed.len(), 1);
7873        assert_eq!(allowed[0].id, "marked");
7874    }
7875
7876    #[test]
7877    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7878        let state = Interrupt::Running {
7879            parked: vec!["running".to_owned()],
7880            interrupt_task: "marked".to_owned(),
7881        };
7882        let candidates = vec![task(), task()];
7883        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7884        assert!(allowed.is_empty());
7885    }
7886
7887    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
7888    /// sequence began (only reachable above the default
7889    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
7890    /// never both in the same tick, which is what "exactly one resume, no
7891    /// simultaneous run" actually requires structurally rather than by
7892    /// coincidence of how many ordinary slots happen to be free.
7893    #[test]
7894    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7895        let state = Interrupt::Resuming {
7896            parked: vec!["a".to_owned(), "c".to_owned()],
7897        };
7898        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7899        let allowed = interrupt_gate(&state, &[], candidates);
7900        assert_eq!(
7901            allowed.len(),
7902            1,
7903            "at most one candidate may be offered while resuming: {allowed:?}"
7904        );
7905        assert_eq!(allowed[0].id, "a");
7906    }
7907
7908    #[test]
7909    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7910        let state = Interrupt::Resuming {
7911            parked: vec!["a".to_owned()],
7912        };
7913        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7914        assert!(allowed.is_empty());
7915    }
7916
7917    /// The invariant the completion criteria ask for by name: across a whole
7918    /// simulated sequence, there is never a tick where the gate would let
7919    /// through both the parked run's resume and the interrupt task, and
7920    /// exactly one candidate resumes the instant the interrupt task's run
7921    /// ends - never zero, never more than one.
7922    #[test]
7923    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7924        let running = task(); // id: whatever `Task::new` minted
7925        let marked = interrupt_task("marked");
7926
7927        let mut state = Interrupt::Idle;
7928        // Tick 1: `running` is in flight, `marked` becomes runnable.
7929        let in_flight = vec![running.id.clone()];
7930        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7931        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7932        assert!(gated.is_empty(), "still waiting on `running` to park");
7933
7934        // Tick 2: `running` parked and left flight; nothing dispatched yet.
7935        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7936        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7937        assert_eq!(
7938            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7939            vec!["marked"],
7940            "only the interrupt task may be offered to the dispatcher now"
7941        );
7942
7943        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
7944        state = advance_interrupt_tick(
7945            true,
7946            state,
7947            &["marked".to_owned()],
7948            std::slice::from_ref(&running),
7949        );
7950        let gated = interrupt_gate(
7951            &state,
7952            &["marked".to_owned()],
7953            vec![marked.clone(), running.clone()],
7954        );
7955        assert!(
7956            gated.is_empty(),
7957            "the parked run must not be offered back while the interrupt \
7958             task is still running"
7959        );
7960
7961        // Tick 4: `marked`'s run reached a terminal status and left flight.
7962        // A higher-priority ordinary task `other` is also runnable now - it
7963        // must not be let through instead of, or alongside, `running`.
7964        let other = task_with_id("other");
7965        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7966        assert_eq!(
7967            state,
7968            Interrupt::Resuming {
7969                parked: vec![running.id.clone()]
7970            }
7971        );
7972        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7973        assert_eq!(
7974            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7975            vec![running.id.as_str()],
7976            "exactly the parked run resumes - not the unrelated task, even \
7977             though it was offered first"
7978        );
7979
7980        // Tick 5: `running` is now in flight (dispatched from tick 4's
7981        // gate). Only now does the sequence end and ordinary dispatch fully
7982        // resume.
7983        state = advance_interrupt_tick(
7984            true,
7985            state,
7986            std::slice::from_ref(&running.id),
7987            std::slice::from_ref(&other),
7988        );
7989        assert_eq!(state, Interrupt::Idle);
7990        let gated = interrupt_gate(
7991            &state,
7992            std::slice::from_ref(&running.id),
7993            vec![other.clone()],
7994        );
7995        assert_eq!(
7996            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7997            vec![other.id.as_str()],
7998            "ordinary dispatch is unrestricted again"
7999        );
8000    }
8001
8002    #[test]
8003    fn every_run_status_settles_the_task_it_came_from() {
8004        // run status, resulting task status, attempts still standing after one
8005        let table = [
8006            (RunStatus::Merged, TaskStatus::Done, 1),
8007            (RunStatus::Ready, TaskStatus::Done, 1),
8008            (RunStatus::Stalled, TaskStatus::Failed, 0),
8009            (RunStatus::Blocked, TaskStatus::Failed, 1),
8010            (RunStatus::Failed, TaskStatus::Failed, 1),
8011            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8012            (RunStatus::Prep, TaskStatus::Failed, 1),
8013            (RunStatus::Implementing, TaskStatus::Failed, 1),
8014            (RunStatus::Judging, TaskStatus::Failed, 1),
8015            (RunStatus::Deliberating, TaskStatus::Failed, 1),
8016            (RunStatus::Voting, TaskStatus::Failed, 1),
8017            (RunStatus::Reviewing, TaskStatus::Failed, 1),
8018            (RunStatus::Gating, TaskStatus::Failed, 1),
8019        ];
8020        for (run, want, attempts) in table {
8021            let mut t = task();
8022            t.start("20260902-000000-aaaa".to_owned());
8023            settle(
8024                &mut t,
8025                Verdict {
8026                    status: run,
8027                    left_pr: false,
8028                    parked: false,
8029                    quota_hit: matches!(run, RunStatus::Stalled),
8030                    no_viable_candidates: false,
8031                },
8032                "why",
8033                2,
8034            );
8035            assert_eq!(t.status, want, "task status after {}", label(run));
8036            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8037        }
8038    }
8039
8040    #[test]
8041    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8042        let mut stalled = task();
8043        stalled.start("20260902-000000-aaaa".to_owned());
8044        settle(
8045            &mut stalled,
8046            Verdict {
8047                status: RunStatus::Stalled,
8048                left_pr: false,
8049                parked: false,
8050                quota_hit: true,
8051                no_viable_candidates: false,
8052            },
8053            "quota",
8054            1,
8055        );
8056        assert_eq!(stalled.attempts, 0);
8057        assert!(
8058            stalled.status.runnable(),
8059            "a machine problem must leave the task in line"
8060        );
8061
8062        let mut blocked = task();
8063        blocked.start("20260902-000000-aaaa".to_owned());
8064        settle(
8065            &mut blocked,
8066            Verdict {
8067                status: RunStatus::Blocked,
8068                left_pr: false,
8069                parked: false,
8070                quota_hit: false,
8071                no_viable_candidates: false,
8072            },
8073            "findings open",
8074            1,
8075        );
8076        assert_eq!(blocked.attempts, 1);
8077        assert_eq!(
8078            blocked.status,
8079            TaskStatus::Held,
8080            "the last attempt hands the task to a human"
8081        );
8082    }
8083
8084    #[test]
8085    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8086        // Attempts to spare: without the pull request this task would go
8087        // straight back in line and run the whole competition again.
8088        let mut delivered = task();
8089        delivered.start("20260903-080619-01c2".to_owned());
8090        settle(
8091            &mut delivered,
8092            Verdict {
8093                status: RunStatus::Blocked,
8094                left_pr: true,
8095                parked: false,
8096                quota_hit: false,
8097                no_viable_candidates: false,
8098            },
8099            "no check status",
8100            4,
8101        );
8102        assert_eq!(
8103            delivered.status,
8104            TaskStatus::Held,
8105            "a pull request waiting on CI or a person is not a retryable failure"
8106        );
8107        assert!(
8108            !delivered.status.runnable(),
8109            "the loop must not pick this task up again"
8110        );
8111        assert_eq!(
8112            delivered.last_error.as_deref(),
8113            Some("no check status"),
8114            "the operator needs to be told what the gate was waiting for"
8115        );
8116
8117        // The same status without a pull request is a plain failure, and with
8118        // attempts left it is retried.
8119        let mut empty_handed = task();
8120        empty_handed.start("20260903-080619-01c2".to_owned());
8121        settle(
8122            &mut empty_handed,
8123            Verdict {
8124                status: RunStatus::Blocked,
8125                left_pr: false,
8126                parked: false,
8127                quota_hit: false,
8128                no_viable_candidates: false,
8129            },
8130            "findings open",
8131            4,
8132        );
8133        assert_eq!(empty_handed.status, TaskStatus::Failed);
8134        assert!(empty_handed.status.runnable());
8135    }
8136
8137    #[test]
8138    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8139        // Every candidate agreed, with evidence, that nothing belonged in the
8140        // worktree. That is not a confirmed success to close automatically -
8141        // a human still has to check the claim - and it is not an ordinary
8142        // failure either, so this settles exactly like a pull request nobody
8143        // merged yet: `Held`, same as `Blocked` with a PR.
8144        let mut noop = task();
8145        noop.start("20260912-131304-391f".to_owned());
8146        settle(
8147            &mut noop,
8148            Verdict {
8149                status: RunStatus::VerifiedNoop,
8150                left_pr: false,
8151                parked: false,
8152                quota_hit: false,
8153                no_viable_candidates: true,
8154            },
8155            "candidate A: already fixed by b32cfc4, on main",
8156            4,
8157        );
8158        assert_eq!(
8159            noop.status,
8160            TaskStatus::Held,
8161            "an unverified claim is a request for a human, not a failure"
8162        );
8163        assert!(
8164            !noop.status.runnable(),
8165            "the loop must not requeue this on the same unverified claim"
8166        );
8167        // `Task::release` resets attempts to zero the moment a human looks at
8168        // the evidence and lets it run again, so it does not matter here
8169        // whether the one attempt already spent stays spent - what matters is
8170        // that nothing retries this task unattended in the meantime.
8171        assert_eq!(noop.attempts, 1);
8172    }
8173
8174    #[test]
8175    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8176        // Parking is the operator asking for the process back - to replace the
8177        // binary, most of all. The run's work is intact on disk, so this is
8178        // not a failed attempt, and charging for it would mean a few upgrades
8179        // could exhaust a budget meant for agents that misbehaved.
8180        let mut parked = task();
8181        parked.start("20260903-183634-2d98".to_owned());
8182        settle(
8183            &mut parked,
8184            Verdict {
8185                status: RunStatus::Implementing,
8186                left_pr: false,
8187                quota_hit: false,
8188                parked: true,
8189                no_viable_candidates: false,
8190            },
8191            "parked after `implementing`",
8192            2,
8193        );
8194        assert_eq!(parked.attempts, 0, "a park is refunded");
8195        assert!(
8196            parked.status.runnable(),
8197            "and the task stays in line so the next loop resumes its run"
8198        );
8199        assert_eq!(parked.status, TaskStatus::Parked);
8200        assert_eq!(
8201            parked.park_reason.as_deref(),
8202            Some("parked after `implementing`"),
8203            "the card says where it stopped"
8204        );
8205        assert_eq!(parked.last_error, None, "nothing failed");
8206
8207        // Without the park flag the same non-terminal status is what it always
8208        // was: `execute` returning mid-flight, which is a bug and spends an
8209        // attempt so a task cannot loop on it forever.
8210        let mut broken = task();
8211        broken.start("20260903-183634-2d98".to_owned());
8212        settle(
8213            &mut broken,
8214            Verdict {
8215                status: RunStatus::Implementing,
8216                left_pr: false,
8217                quota_hit: false,
8218                parked: false,
8219                no_viable_candidates: false,
8220            },
8221            "returned mid-flight",
8222            2,
8223        );
8224        assert_eq!(broken.attempts, 1);
8225    }
8226
8227    #[test]
8228    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
8229        // Run e633: quorum lost because two judges answered with the wrong
8230        // JSON shape, `quota: []`. Refunding that takes the bound off the
8231        // retry loop, and each retry pays for a fresh hour-long implement
8232        // wave before it can fail the same way.
8233        let mut flaky = task();
8234        flaky.start("20260903-123023-e633".to_owned());
8235        settle(
8236            &mut flaky,
8237            Verdict {
8238                status: RunStatus::Stalled,
8239                left_pr: false,
8240                parked: false,
8241                quota_hit: false,
8242                no_viable_candidates: false,
8243            },
8244            "verdict rests on 1 of 3 judges",
8245            2,
8246        );
8247        assert_eq!(
8248            flaky.attempts, 1,
8249            "flakiness spends an attempt, so `max_attempts` still bounds it"
8250        );
8251        assert!(flaky.status.runnable(), "and it is still worth retrying");
8252
8253        // The same status, lost to a rate limit, is the machine's fault.
8254        let mut limited = task();
8255        limited.start("20260903-123023-e633".to_owned());
8256        settle(
8257            &mut limited,
8258            Verdict {
8259                status: RunStatus::Stalled,
8260                left_pr: false,
8261                parked: false,
8262                quota_hit: true,
8263                no_viable_candidates: false,
8264            },
8265            "judge-2, judge-3 out of quota",
8266            2,
8267        );
8268        assert_eq!(limited.attempts, 0, "a quota window is refunded");
8269        assert!(limited.status.runnable());
8270
8271        // And the bound really binds: a task that keeps stalling on flakiness
8272        // reaches a human instead of running the roster forever.
8273        let mut worn = task();
8274        for _ in 0..2 {
8275            worn.release();
8276        }
8277        worn.start("20260903-123023-e633".to_owned());
8278        worn.attempts = 2;
8279        settle(
8280            &mut worn,
8281            Verdict {
8282                status: RunStatus::Stalled,
8283                left_pr: false,
8284                parked: false,
8285                quota_hit: false,
8286                no_viable_candidates: false,
8287            },
8288            "no quorum again",
8289            2,
8290        );
8291        assert_eq!(worn.status, TaskStatus::Held);
8292        assert!(!worn.status.runnable());
8293    }
8294
8295    #[test]
8296    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8297        // The implement wave loses every seat to the same rate limit and
8298        // `after_implement` bails with nothing viable, which surfaces as
8299        // `Failed` rather than `Stalled`. That is the same machine fact the
8300        // `Stalled`-quota row already refunds, and must be refunded the same
8301        // way, or a quota outage quietly holds every task it touches instead
8302        // of leaving them in line for the reset.
8303        let mut wiped_out = task();
8304        wiped_out.start("20260907-025000-a1b2".to_owned());
8305        settle(
8306            &mut wiped_out,
8307            Verdict {
8308                status: RunStatus::Failed,
8309                left_pr: false,
8310                parked: false,
8311                quota_hit: true,
8312                no_viable_candidates: true,
8313            },
8314            "no candidate produced a change; nothing to judge",
8315            2,
8316        );
8317        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8318        assert!(
8319            wiped_out.status.runnable(),
8320            "a machine problem must leave the task in line"
8321        );
8322
8323        // This is the exemption that must stay narrow: a candidate that did
8324        // produce a change, and then failed for some other reason, still
8325        // spends the attempt even though a seat elsewhere hit its quota.
8326        // Otherwise every ordinary failure that happens to share a run with
8327        // an unrelated rate limit would be refunded for free.
8328        let mut partial_progress = task();
8329        partial_progress.start("20260907-025500-c3d4".to_owned());
8330        settle(
8331            &mut partial_progress,
8332            Verdict {
8333                status: RunStatus::Failed,
8334                left_pr: false,
8335                parked: false,
8336                quota_hit: true,
8337                no_viable_candidates: false,
8338            },
8339            "gate failed on the winning candidate",
8340            2,
8341        );
8342        assert_eq!(
8343            partial_progress.attempts, 1,
8344            "a candidate that actually produced a change spends the attempt \
8345             even though some other seat hit its quota"
8346        );
8347        assert!(partial_progress.status.runnable());
8348    }
8349
8350    #[test]
8351    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8352        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
8353        // disk, and that construction must reach the same conclusion as the
8354        // one `attempt` builds from a live run, or a crash at exactly the
8355        // wrong moment gives a recovered task a different policy than one a
8356        // daemon finished settling itself.
8357        let mut t = task();
8358        t.start("20260907-025000-a1b2".to_owned());
8359        let mut state = run_state(RunStatus::Failed);
8360        state.quota.push(QuotaLoss {
8361            cause: crate::agent::QuotaCause::UsageLimit,
8362            agent: String::new(),
8363            seat: "cand-a".to_owned(),
8364            node: "implement".to_owned(),
8365            at: Timestamp::now(),
8366            reset: None,
8367        });
8368        assert!(
8369            state.viable().is_empty(),
8370            "no candidate was added, so nothing is viable"
8371        );
8372        reclaim(&mut t, Some(state), 2, "en");
8373        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8374        assert!(t.status.runnable());
8375    }
8376
8377    #[test]
8378    fn a_held_task_is_never_offered_to_the_loop() {
8379        let dir = tempfile::tempdir().unwrap();
8380        let queue = Queue::at(dir.path().to_path_buf());
8381        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8382            let mut t = task();
8383            t.id = format!("2026090{n}-000000-000{n}");
8384            t.priority = priority;
8385            queue.put(&mut t).unwrap();
8386        }
8387        let mut held = task();
8388        held.id = "20260909-000000-9999".to_owned();
8389        held.priority = 99;
8390        held.hold_machine(None);
8391        queue.put(&mut held).unwrap();
8392
8393        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8394        assert_eq!(order.len(), 3);
8395        assert!(!order.contains(&held.id));
8396        assert_eq!(
8397            order.first().cloned(),
8398            queue.next_runnable().map(|t| t.id),
8399            "the loop's first candidate is exactly what the queue offers"
8400        );
8401        assert_eq!(
8402            order,
8403            vec![
8404                "20260902-000000-0002".to_owned(),
8405                "20260903-000000-0003".to_owned(),
8406                "20260901-000000-0001".to_owned(),
8407            ],
8408            "priority first, then oldest, so nothing starves"
8409        );
8410    }
8411
8412    #[test]
8413    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8414        let dir = tempfile::tempdir().unwrap();
8415        let queue = Queue::at(dir.path().to_path_buf());
8416        let mut old = task();
8417        old.id = "20260101-000000-old0".to_owned();
8418        queue.put(&mut old).unwrap();
8419        let mut fresh = task();
8420        fresh.id = "20260101-000000-new0".to_owned();
8421        queue.put(&mut fresh).unwrap();
8422
8423        // No parseable pid at all, so age is the only signal there is to
8424        // check - unlike a real `Queue::claim`, which always names a real,
8425        // and therefore alive, pid this test cannot fake as dead.
8426        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8427        std::thread::sleep(Duration::from_millis(60));
8428        let live = queue.claim(&fresh.id).unwrap();
8429
8430        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8431        assert_eq!(swept, vec![old.id.clone()]);
8432        assert!(
8433            queue.claim(&old.id).is_ok(),
8434            "an unparseable lock older than the threshold is swept"
8435        );
8436        assert!(
8437            queue.claim(&fresh.id).is_err(),
8438            "a live pid protects its lock regardless of age"
8439        );
8440        drop(live);
8441    }
8442
8443    #[test]
8444    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8445        // A live worker's claim remains authoritative even beyond the sweep's
8446        // age limit. Sweeping it would permit a second competing attempt.
8447        let dir = tempfile::tempdir().unwrap();
8448        let queue = Queue::at(dir.path().to_path_buf());
8449        let mut t = task();
8450        t.id = "20260101-000000-live".to_owned();
8451        queue.put(&mut t).unwrap();
8452
8453        let claim = queue.claim(&t.id).unwrap();
8454        std::thread::sleep(Duration::from_millis(60));
8455
8456        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8457        assert!(
8458            swept.is_empty(),
8459            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8460        );
8461        assert!(
8462            queue.claim(&t.id).is_err(),
8463            "the lock still protects its task"
8464        );
8465        drop(claim);
8466    }
8467
8468    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8469    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8470    fn injected_dead_pid() -> u32 {
8471        std::process::id().checked_add(1).unwrap_or(1)
8472    }
8473
8474    #[test]
8475    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8476        let dir = tempfile::tempdir().unwrap();
8477        let queue = Queue::at(dir.path().to_path_buf());
8478        let mut t = task();
8479        t.id = "20260101-000000-dead".to_owned();
8480        queue.put(&mut t).unwrap();
8481        let dead_pid = injected_dead_pid();
8482
8483        // Written directly rather than through `Queue::claim`, which would
8484        // stamp this test process's own very much alive pid and defeat the
8485        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8486        // like moments after it died, not six hours later.
8487        std::fs::write(
8488            dir.path().join(format!("{}.lock", t.id)),
8489            dead_pid.to_string(),
8490        )
8491        .unwrap();
8492
8493        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8494            pid != dead_pid
8495        });
8496        assert_eq!(
8497            swept,
8498            vec![t.id.clone()],
8499            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8500        );
8501        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8502    }
8503
8504    #[test]
8505    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8506        let dir = tempfile::tempdir().unwrap();
8507        let queue = Queue::at(dir.path().to_path_buf());
8508        let mut t = task();
8509        t.id = "20260101-000000-late".to_owned();
8510        queue.put(&mut t).unwrap();
8511        let dead_pid = injected_dead_pid();
8512
8513        // Tick one, standing in for the sweep `poll` already runs at
8514        // startup: nothing to find yet.
8515        assert!(
8516            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8517            "nothing has claimed the task yet"
8518        );
8519
8520        // A second daemon claims the task and dies before it ever writes
8521        // `running`, well after this loop's own startup sweep already ran.
8522        std::fs::write(
8523            dir.path().join(format!("{}.lock", t.id)),
8524            dead_pid.to_string(),
8525        )
8526        .unwrap();
8527
8528        // Tick two, standing in for a poll long into this daemon's uptime:
8529        // the same function, called again, notices what only just appeared -
8530        // proving the sweep is not a one-shot startup check.
8531        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8532            pid != dead_pid
8533        });
8534        assert_eq!(swept, vec![t.id.clone()]);
8535    }
8536
8537    #[test]
8538    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8539        // `reclaim_orphaned_running` looks up the task's last run, which
8540        // touches `run::home()`; the first call anywhere in this binary wins,
8541        // so this is a no-op if another test already pinned one, and either
8542        // way the run id below is never written under it.
8543        crate::run::pin_test_home();
8544        let dir = tempfile::tempdir().unwrap();
8545        let queue = Queue::at(dir.path().to_path_buf());
8546        let mut t = task();
8547        t.id = "20260101-000000-crsh".to_owned();
8548        t.status = TaskStatus::Running;
8549        t.attempts = 1;
8550        // No `run.json` behind this id: standing in for a run this test does
8551        // not need to make readable, since the point is the lock, not the
8552        // recovery table `reclaim` already has its own tests for.
8553        t.runs.push("20260904-000000-4043".to_owned());
8554        queue.put(&mut t).unwrap();
8555        let dead_pid = injected_dead_pid();
8556
8557        // The crashed daemon's own claim, naming a pid nothing on the
8558        // machine holds anymore.
8559        std::fs::write(
8560            dir.path().join(format!("{}.lock", t.id)),
8561            dead_pid.to_string(),
8562        )
8563        .unwrap();
8564
8565        // Before the lock is swept the task looks claimed, and
8566        // `reclaim_orphaned_running` must leave it alone - this is exactly
8567        // the bug: a `running` task stranded behind a dead daemon's lock,
8568        // invisible to the claim-as-proof check because the lock outlived
8569        // the process that wrote it.
8570        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8571        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8572
8573        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8574            pid != dead_pid
8575        });
8576        assert_eq!(swept, vec![t.id.clone()]);
8577
8578        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8579        assert_eq!(reclaimed, vec![t.id.clone()]);
8580        let after = queue.get(&t.id).unwrap();
8581        assert_eq!(
8582            after.status,
8583            TaskStatus::Held,
8584            "no run.json to recover from, so a human is asked"
8585        );
8586        assert_eq!(
8587            after.runs,
8588            vec!["20260904-000000-4043".to_owned()],
8589            "the crashed run's id is kept as evidence, not discarded"
8590        );
8591    }
8592
8593    #[test]
8594    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8595        let dir = tempfile::tempdir().unwrap();
8596        let queue = Queue::at(dir.path().to_path_buf());
8597        let mut t = task();
8598        t.id = "20260101-000000-unknown".to_owned();
8599        queue.put(&mut t).unwrap();
8600        let dead_pid = injected_dead_pid();
8601        std::fs::write(
8602            dir.path().join(format!("{}.lock", t.id)),
8603            dead_pid.to_string(),
8604        )
8605        .unwrap();
8606
8607        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8608        assert!(swept.is_empty(), "an unknown pid must keep its lock");
8609        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8610    }
8611
8612    fn run_state_in(status: RunStatus, language: &str) -> RunState {
8613        let mut s = run_state(status);
8614        s.config.graph.language = language.to_owned();
8615        s
8616    }
8617
8618    fn unstarted_verdict(status: RunStatus) -> Verdict {
8619        Verdict {
8620            status,
8621            left_pr: false,
8622            quota_hit: false,
8623            parked: false,
8624            no_viable_candidates: false,
8625        }
8626    }
8627
8628    #[test]
8629    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8630        let mut t = task();
8631        t.attempts = 1;
8632        settle_in(
8633            &mut t,
8634            unstarted_verdict(RunStatus::AlreadyInBase),
8635            "already in main",
8636            1,
8637            phrases("en"),
8638        );
8639        assert_eq!(t.status, TaskStatus::Done);
8640        assert_eq!(t.attempts, 0);
8641    }
8642
8643    #[test]
8644    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8645        let reason = |language: &str| {
8646            let mut t = task();
8647            settle_in(
8648                &mut t,
8649                unstarted_verdict(RunStatus::Judging),
8650                "boom",
8651                1,
8652                phrases(language),
8653            );
8654            t.last_error.or(t.hold_reason).unwrap_or_default()
8655        };
8656        assert!(
8657            reason("en").starts_with("the graph stopped at `"),
8658            "{}",
8659            reason("en")
8660        );
8661        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8662        assert!(reason("日本語").contains("boom"));
8663        assert_eq!(reason("fr"), reason("en"));
8664    }
8665
8666    #[test]
8667    fn describe_follows_the_run_language_and_keeps_the_run_id() {
8668        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8669        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8670        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8671        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8672        assert!(ja.contains("[run "), "{ja}");
8673        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8674        assert!(ended.starts_with("run 終了: "), "{ended}");
8675        let mut de = run_state_in(RunStatus::Failed, "de");
8676        let mut en = run_state_in(RunStatus::Failed, "en");
8677        de.id = "same".to_owned();
8678        en.id = "same".to_owned();
8679        assert_eq!(describe(&de), describe(&en));
8680    }
8681
8682    #[test]
8683    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8684        use crate::handover::Refused;
8685        let cases = [
8686            Refused::Foreign {
8687                branch: "b".into(),
8688                path: "/w/x".into(),
8689                why: "made by hand".into(),
8690            },
8691            Refused::Unsafe {
8692                branch: "b".into(),
8693                path: "/w/x".into(),
8694                why: "its worktree has uncommitted changes (a.rs)".into(),
8695            },
8696            Refused::ReleaseFailed {
8697                branch: "b".into(),
8698                path: "/w/x".into(),
8699                run: "ab12".into(),
8700            },
8701        ];
8702        for r in &cases {
8703            let en = (phrases("en").handover_refused)(r);
8704            assert_eq!(en, r.to_string());
8705            let ja = (phrases("ja").handover_refused)(r);
8706            assert!(
8707                !ja.contains("is checked out") && !ja.contains("try again"),
8708                "{ja}"
8709            );
8710            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8711            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8712                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8713            }
8714        }
8715        assert!(phrases("en").handover_hint.contains("release the task"));
8716        assert!(phrases("ja").handover_hint.contains("解放"));
8717    }
8718
8719    #[test]
8720    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8721        let build = |lang: &str| {
8722            let mut s = run_state_in(RunStatus::Blocked, lang);
8723            s.id = "same".to_owned();
8724            s.config.graph.review_rounds = 3;
8725            let mut r = review_round(3);
8726            r.expected = 3;
8727            r.answered = 1;
8728            s.reviews.push(r);
8729            s.event(
8730                "review",
8731                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8732            );
8733            s
8734        };
8735        let en = describe(&build("en"));
8736        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8737        let ja = describe(&build("ja"));
8738        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8739        assert!(!ja.contains("never answered"), "{ja}");
8740        assert!(ja.contains("[run "), "{ja}");
8741
8742        // An incomplete panel whose verification failed is a different stop:
8743        // the real event must survive in ja too.
8744        let mut failed = build("ja");
8745        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8746            command: "cargo test".to_owned(),
8747            code: Some(1),
8748            output_tail: String::new(),
8749            duration_ms: 0,
8750            resource_blocked: false,
8751        });
8752        failed.event("review", "stopped; e2e failed: cargo test");
8753        let ja = describe(&failed);
8754        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8755        assert!(!ja.contains("席のレビュアー"), "{ja}");
8756    }
8757
8758    #[test]
8759    fn refusals_and_recovery_prose_follow_the_language() {
8760        let home = crate::run::test_home();
8761        let t = held_task_with("r1");
8762        let q = action_question(
8763            "r1",
8764            ask::ChoiceAction::Resume {
8765                run: "r1".to_owned(),
8766            },
8767        );
8768        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
8769            ActionDecision::Refuse(s) => s,
8770            other => panic!("{other:?}"),
8771        };
8772        assert!(refuse(phrases("en")).contains("could not be read: gone"));
8773        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8774        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8775
8776        let mut held = task();
8777        reclaim(&mut held, None, 2, "ja");
8778        assert!(held.hold_reason.unwrap().contains("保留にしました"));
8779        let mut held = task();
8780        reclaim(&mut held, None, 2, "xx");
8781        assert!(held.hold_reason.unwrap().contains("held for a human"));
8782    }
8783
8784    fn run_state(status: RunStatus) -> RunState {
8785        let mut state = RunState::new(
8786            PathBuf::from("/repo"),
8787            "main".to_owned(),
8788            "abc1234def".to_owned(),
8789            "add retries".to_owned(),
8790            Config::default(),
8791        );
8792        state.status = status;
8793        state
8794    }
8795
8796    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8797        Candidate {
8798            index: 0,
8799            label,
8800            agent: "claude".to_owned(),
8801            branch: format!("magi/x/{label}"),
8802            worktree: PathBuf::from("/repo"),
8803            summary: summary.to_owned(),
8804            stat: String::new(),
8805            files: 0,
8806            commits: usize::from(!empty),
8807            empty,
8808            failed: failed.map(str::to_owned),
8809            verified_noop: None,
8810            duration_ms: 0,
8811            folded: false,
8812        }
8813    }
8814
8815    #[test]
8816    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8817        let mut state = run_state(RunStatus::Blocked);
8818        state.gate = vec![
8819            CommandOutcome {
8820                command: "cargo make check".to_owned(),
8821                code: Some(0),
8822                output_tail: "ok".to_owned(),
8823                duration_ms: 0,
8824                resource_blocked: false,
8825            },
8826            CommandOutcome {
8827                command: "cargo test".to_owned(),
8828                code: Some(101),
8829                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8830                duration_ms: 0,
8831                resource_blocked: false,
8832            },
8833        ];
8834        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8835        assert!(d.contains("cargo test"), "{d}");
8836        assert!(
8837            !d.contains("cargo make check"),
8838            "a passing check is not a diagnostic: {d}"
8839        );
8840        assert!(d.contains("assertion failed"), "{d}");
8841    }
8842
8843    #[test]
8844    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8845        let mut state = run_state(RunStatus::Blocked);
8846        state.event(
8847            "land",
8848            "stopped: the fixer produced no commit while 2 check(s) were failing \
8849             (build, lint); stopping instead of looping on an unchanged tree",
8850        );
8851        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8852        assert!(d.contains("build"), "{d}");
8853        assert!(d.contains("lint"), "{d}");
8854        assert!(d.contains("fixer produced no commit"), "{d}");
8855    }
8856
8857    #[test]
8858    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8859        // `describe`'s output becomes `Task::last_error` verbatim, and the
8860        // phone renders that in the same alarm-styled box an ordinary
8861        // failure gets. A bare `verified_noop` there would read exactly like
8862        // the failure this status exists to be told apart from.
8863        let state = run_state(RunStatus::VerifiedNoop);
8864        let d = describe(&state);
8865        assert!(
8866            d.contains("agent-verified no-op"),
8867            "expected the display label, not the wire spelling: {d}"
8868        );
8869        assert!(!d.contains("verified_noop"), "{d}");
8870    }
8871
8872    #[test]
8873    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
8874        let mut state = run_state(RunStatus::Failed);
8875        state.gate.push(crate::run::CommandOutcome {
8876            command: "cargo test".into(),
8877            code: Some(101),
8878            output_tail: format!(
8879                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8880                "  41: 0x1234 - backtrace frame\n".repeat(10000)
8881            ),
8882            duration_ms: 1,
8883            resource_blocked: false,
8884        });
8885        let d = diagnostic(&state).unwrap();
8886        assert!(d.contains("panicked at widget.rs:12"), "{d}");
8887        assert!(d.contains("assertion failed: widget missing"));
8888        assert!(d.contains("widget log"));
8889    }
8890
8891    #[test]
8892    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8893        // The whole point of the feature: a run held as "no candidate produced
8894        // a change" can mean the implementer actually finished the task and
8895        // only left a clean local tree behind - see AGENTS.md on this exact
8896        // failure mode. The diagnostic has to carry what the agent actually
8897        // said, not just the fact that nothing was there to judge.
8898        let mut state = run_state(RunStatus::Failed);
8899        state.candidates = vec![candidate(
8900            'A',
8901            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8902            true,
8903            None,
8904        )];
8905        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8906        assert!(d.contains("candidate A"), "{d}");
8907        assert!(d.contains("tagged v1.2.3"), "{d}");
8908    }
8909
8910    #[test]
8911    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8912        let mut state = run_state(RunStatus::Failed);
8913        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8914        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8915        assert!(d.contains("candidate A"), "{d}");
8916        assert!(d.contains("agent timed out"), "{d}");
8917    }
8918
8919    #[test]
8920    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8921        // A viable candidate existed, the gate never ran, and nothing land
8922        // said matches - `Task::last_error` is left to explain this one alone.
8923        let mut state = run_state(RunStatus::Failed);
8924        state.candidates = vec![candidate('A', "did the work", false, None)];
8925        assert!(diagnostic(&state).is_none());
8926    }
8927
8928    #[test]
8929    fn diagnostic_is_bounded_however_much_a_run_printed() {
8930        let mut state = run_state(RunStatus::Blocked);
8931        state.gate = vec![
8932            CommandOutcome {
8933                command: "cargo test".to_owned(),
8934                code: Some(101),
8935                output_tail: "x".repeat(50_000),
8936                duration_ms: 0,
8937                resource_blocked: false,
8938            },
8939            CommandOutcome {
8940                command: "cargo clippy".to_owned(),
8941                code: Some(1),
8942                output_tail: "y".repeat(50_000),
8943                duration_ms: 0,
8944                resource_blocked: false,
8945            },
8946        ];
8947        state.candidates = vec![
8948            candidate('A', &"z".repeat(50_000), true, None),
8949            candidate('B', &"w".repeat(50_000), true, None),
8950        ];
8951        let d = diagnostic(&state).expect("plenty here to diagnose");
8952        assert!(
8953            d.len() <= DIAGNOSTIC_MAX,
8954            "diagnostic grew to {} bytes, unbounded",
8955            d.len()
8956        );
8957    }
8958
8959    #[test]
8960    fn selected_delivery_guards_survive_recovery_failure_accounting() {
8961        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8962            let mut t = task();
8963            let mut state = run_state(status);
8964            t.pr_recovery = Some(crate::pr_recovery::Selection {
8965                url: "url".into(),
8966                branch: format!("magi/task-{}", t.id),
8967                head: "a".repeat(40),
8968                source_head: None,
8969                source_run: None,
8970                source_proof: None,
8971                disposition: Some(crate::pr_recovery::Disposition::Land),
8972                instruction: t.instruction.clone(),
8973                approved_at: Timestamp::now(),
8974            });
8975            state.pr_recovery = t.pr_recovery.clone();
8976            t.start(state.id.clone());
8977            settle_and_diagnose(
8978                &mut t,
8979                Verdict {
8980                    status,
8981                    left_pr: false,
8982                    quota_hit: false,
8983                    parked: false,
8984                    no_viable_candidates: false,
8985                },
8986                "delivery stopped",
8987                5,
8988                &state,
8989            );
8990            assert_eq!(t.status, TaskStatus::Held);
8991            let reason = t.hold_reason.as_deref().unwrap();
8992            if status == RunStatus::Ready {
8993                assert!(reason.contains("Selected PR delivery is incomplete"));
8994                assert!(t.recovery_budget.is_none());
8995            } else {
8996                assert!(reason.contains("Selected recovery stopped"));
8997                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8998            }
8999            assert!(t.pr_recovery.is_some());
9000        }
9001    }
9002
9003    #[test]
9004    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9005        let mut state = run_state(RunStatus::Voting);
9006        state.base_sync = Some(crate::run::BaseSync {
9007            tip: "base-tip".into(),
9008            behind: 3,
9009            attempts: 4,
9010            conflict: Some("base stopped".into()),
9011            already_in: None,
9012        });
9013        state.record_base_sync_stop("candidate-head");
9014        let mut t = task();
9015        t.start(state.id.clone());
9016        let verdict = Verdict {
9017            status: RunStatus::Blocked,
9018            left_pr: false,
9019            quota_hit: false,
9020            parked: false,
9021            no_viable_candidates: false,
9022        };
9023        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9024        assert_eq!(
9025            t.status,
9026            TaskStatus::Held,
9027            "unspent task attempts cannot start another competition"
9028        );
9029        let at = t.held_at;
9030        let cause = t.hold_notice_cause.clone();
9031        state.begin_pass();
9032        t.release_operator("test-resume", None);
9033        t.start(state.id.clone());
9034        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9035        assert_eq!(t.status, TaskStatus::Held);
9036        assert_eq!(t.held_at, at);
9037        assert_eq!(t.hold_notice_cause, cause);
9038    }
9039
9040    #[test]
9041    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9042        let mut state = run_state(RunStatus::Blocked);
9043        state.gate = vec![CommandOutcome {
9044            command: "cargo test".to_owned(),
9045            code: Some(101),
9046            output_tail: "assertion failed".to_owned(),
9047            duration_ms: 0,
9048            resource_blocked: false,
9049        }];
9050        let verdict = Verdict {
9051            status: RunStatus::Blocked,
9052            left_pr: false,
9053            quota_hit: false,
9054            parked: false,
9055            no_viable_candidates: false,
9056        };
9057
9058        // Attempt one of two still has a retry coming: no diagnostic yet, the
9059        // task is going to run again and this run's evidence would go stale.
9060        let mut t = task();
9061        t.start("run-1".to_owned());
9062        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9063        assert_eq!(t.status, TaskStatus::Failed);
9064        assert!(t.diagnostic.is_none());
9065
9066        // Attempt two exhausts the budget: now it is held, and the
9067        // diagnostic is what `magi task show` has to say more than one line.
9068        t.start("run-2".to_owned());
9069        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9070        assert_eq!(t.status, TaskStatus::Held);
9071        let d = t.diagnostic.expect("a held task must carry its diagnostic");
9072        assert!(d.contains("cargo test"), "{d}");
9073    }
9074
9075    #[test]
9076    fn a_held_task_names_the_open_question_it_is_waiting_on() {
9077        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
9078        // `magi ask` question settled Held with `hold_reason: null`, so the
9079        // notification said nothing actionable. `note_open_question` should
9080        // append the question id to whatever `handed_off` already wrote.
9081        crate::run::pin_test_home();
9082        let home = crate::run::home();
9083        let state = run_state(RunStatus::VerifiedNoop);
9084        let mut q = ask::Question::new(
9085            state.id.clone(),
9086            "implement".to_owned(),
9087            "impl-A".to_owned(),
9088            "is this really a no-op?".to_owned(),
9089            String::new(),
9090            Vec::new(),
9091        );
9092        Questions::at(home.join("questions")).put(&mut q).unwrap();
9093
9094        let verdict = Verdict {
9095            status: RunStatus::VerifiedNoop,
9096            left_pr: false,
9097            quota_hit: false,
9098            parked: false,
9099            no_viable_candidates: false,
9100        };
9101        let mut t = task();
9102        t.start(state.id.clone());
9103        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9104
9105        assert_eq!(t.status, TaskStatus::Held);
9106        let reason = t.hold_reason.expect("a held task must record why");
9107        assert!(
9108            reason.starts_with("run ended agent-verified no-op"),
9109            "the original settle reason must survive unchanged: {reason}"
9110        );
9111        assert!(
9112            reason.contains(q.short()),
9113            "the open question's id must be named so the notice is actionable: {reason}"
9114        );
9115    }
9116
9117    #[test]
9118    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9119        crate::run::pin_test_home();
9120        let state = run_state(RunStatus::VerifiedNoop);
9121
9122        let verdict = Verdict {
9123            status: RunStatus::VerifiedNoop,
9124            left_pr: false,
9125            quota_hit: false,
9126            parked: false,
9127            no_viable_candidates: false,
9128        };
9129        let mut t = task();
9130        t.start(state.id.clone());
9131        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9132
9133        assert_eq!(t.status, TaskStatus::Held);
9134        assert_eq!(
9135            t.hold_reason.as_deref(),
9136            Some("run ended agent-verified no-op"),
9137            "nothing to append when the question was already answered or never asked"
9138        );
9139    }
9140
9141    #[test]
9142    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
9143        crate::run::pin_test_home();
9144        let mut first = run_state(RunStatus::Blocked);
9145        first.id = "20260101-000000-sup1".to_owned();
9146        first.save().unwrap();
9147        let mut second = run_state(RunStatus::Merged);
9148        second.id = "20260101-000000-sup2".to_owned();
9149        second.save().unwrap();
9150
9151        let mut t = task();
9152        t.runs = vec![first.id.clone(), second.id.clone()];
9153        t.status = TaskStatus::Done;
9154
9155        supersede_prior_runs(&t, &crate::run::home());
9156
9157        assert_eq!(
9158            RunState::load(&first.id).unwrap().status,
9159            RunStatus::Superseded,
9160            "the first attempt's Blocked no longer needs anyone's attention"
9161        );
9162        assert_eq!(
9163            RunState::load(&second.id).unwrap().status,
9164            RunStatus::Merged,
9165            "the run that actually succeeded is left exactly as it was"
9166        );
9167    }
9168
9169    #[test]
9170    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
9171        // `is_working_on` alone only proves a *daemon* claim; a `magi run
9172        // --resume` invoked by hand outside the daemon never touches
9173        // `daemon.json` at all, so it would look identical to a genuinely
9174        // idle run without also consulting `RunState::liveness`, which reads
9175        // this run's own recorded `driver_pid` instead.
9176        crate::run::pin_test_home();
9177        let mut first = run_state(RunStatus::Blocked);
9178        first.id = "20260101-000000-sup9".to_owned();
9179        // This test process's own pid: guaranteed alive without needing a
9180        // real second process or daemon.
9181        first.driver_pid = Some(std::process::id());
9182        first.driver_started_at = Some(
9183            crate::proc::process_started_at(std::process::id())
9184                .expect("this test process's own start time must be queryable"),
9185        );
9186        first.save().unwrap();
9187        let mut second = run_state(RunStatus::Merged);
9188        second.id = "20260101-000000-supa".to_owned();
9189        second.save().unwrap();
9190
9191        let mut t = task();
9192        t.runs = vec![first.id.clone(), second.id.clone()];
9193        t.status = TaskStatus::Done;
9194
9195        supersede_prior_runs(&t, &crate::run::home());
9196
9197        assert_eq!(
9198            RunState::load(&first.id).unwrap().status,
9199            RunStatus::Blocked,
9200            "a live driver_pid means something is still actually working this run, \
9201             even though no daemon claims it - rewriting under it would just be \
9202             undone the next time that process saves"
9203        );
9204    }
9205
9206    #[test]
9207    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
9208        // The first resweep must skip a still-live attempt exactly like
9209        // `supersede_prior_runs` itself does; a later resweep, once that
9210        // process is no longer actually driving it, is what closes the gap
9211        // `supersede_prior_runs` alone leaves - a task only ever reaches
9212        // `Done` once, so nothing else would ever look at this run again.
9213        let dir = tempfile::tempdir().unwrap();
9214        let home = dir.path().to_path_buf();
9215        let queue = Queue::at(dir.path().join("queue"));
9216
9217        let mut first = run_state(RunStatus::Blocked);
9218        first.id = "20260101-000000-supd".to_owned();
9219        first.driver_pid = Some(std::process::id());
9220        first.driver_started_at = Some(
9221            crate::proc::process_started_at(std::process::id())
9222                .expect("this test process's own start time must be queryable"),
9223        );
9224        first.save_under(&home).unwrap();
9225        let mut second = run_state(RunStatus::Merged);
9226        second.id = "20260101-000000-supe".to_owned();
9227        second.save_under(&home).unwrap();
9228
9229        let mut t = task();
9230        t.runs = vec![first.id.clone(), second.id.clone()];
9231        t.status = TaskStatus::Done;
9232        queue.put(&mut t).unwrap();
9233
9234        resweep_superseded_attempts(&queue, &home);
9235        assert_eq!(
9236            RunState::load_under(&first.id, &home).unwrap().status,
9237            RunStatus::Blocked,
9238            "still live on the first pass, so still untouched"
9239        );
9240
9241        // Stand in for the manual process no longer being the one driving
9242        // this run: same pid (this test process really is still alive), but
9243        // an identity marker that no longer matches it - see
9244        // `RunState::liveness`'s own doc for why a mismatched
9245        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
9246        let mut stale = RunState::load_under(&first.id, &home).unwrap();
9247        stale.driver_started_at = Some("1".to_owned());
9248        stale.save_under(&home).unwrap();
9249
9250        resweep_superseded_attempts(&queue, &home);
9251        assert_eq!(
9252            RunState::load_under(&first.id, &home).unwrap().status,
9253            RunStatus::Superseded,
9254            "the second pass catches up what the first one correctly skipped"
9255        );
9256    }
9257
9258    #[test]
9259    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
9260        crate::run::pin_test_home();
9261        let mut first = run_state(RunStatus::Blocked);
9262        first.id = "20260101-000000-sup3".to_owned();
9263        first.save().unwrap();
9264        let mut second = run_state(RunStatus::Blocked);
9265        second.id = "20260101-000000-sup4".to_owned();
9266        second.save().unwrap();
9267
9268        let mut t = task();
9269        t.runs = vec![first.id.clone(), second.id.clone()];
9270        // Still retrying: nothing about this task's story is settled yet, so
9271        // neither Blocked run may be relabelled, even though a later attempt
9272        // already exists.
9273        t.status = TaskStatus::Failed;
9274
9275        supersede_prior_runs(&t, &crate::run::home());
9276
9277        assert_eq!(
9278            RunState::load(&first.id).unwrap().status,
9279            RunStatus::Blocked
9280        );
9281        assert_eq!(
9282            RunState::load(&second.id).unwrap().status,
9283            RunStatus::Blocked
9284        );
9285    }
9286
9287    #[test]
9288    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9289        // `magi task done` (or the API's equivalent) can close a task with no
9290        // run of its own ever having succeeded - there is nothing here that
9291        // counts as "the attempt that finished it", so nothing is rewritten.
9292        crate::run::pin_test_home();
9293        let mut first = run_state(RunStatus::Blocked);
9294        first.id = "20260101-000000-sup5".to_owned();
9295        first.save().unwrap();
9296
9297        let mut t = task();
9298        t.runs = vec![first.id.clone()];
9299        t.status = TaskStatus::Done;
9300
9301        supersede_prior_runs(&t, &crate::run::home());
9302
9303        assert_eq!(
9304            RunState::load(&first.id).unwrap().status,
9305            RunStatus::Blocked,
9306            "a single-attempt task has no earlier run to supersede"
9307        );
9308    }
9309
9310    #[test]
9311    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9312        // `magi task done` (or the web/conductor equivalents) can close a
9313        // task in any status, including one whose *last* recorded attempt is
9314        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
9315        // never watched, say. `runs.last()` being `Done`-adjacent is not
9316        // proof it actually succeeded, so nothing earlier may be relabelled
9317        // on its say-so alone.
9318        crate::run::pin_test_home();
9319        let mut first = run_state(RunStatus::Blocked);
9320        first.id = "20260101-000000-supb".to_owned();
9321        first.save().unwrap();
9322        let mut second = run_state(RunStatus::Failed);
9323        second.id = "20260101-000000-supc".to_owned();
9324        second.save().unwrap();
9325
9326        let mut t = task();
9327        t.runs = vec![first.id.clone(), second.id.clone()];
9328        t.status = TaskStatus::Done;
9329
9330        supersede_prior_runs(&t, &crate::run::home());
9331
9332        assert_eq!(
9333            RunState::load(&first.id).unwrap().status,
9334            RunStatus::Blocked,
9335            "the task's last attempt never landed, so there is nothing here \
9336             actually superseding it"
9337        );
9338    }
9339
9340    #[test]
9341    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9342        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
9343        // to look" - `Failed` and `VerifiedNoop` are already their own
9344        // terminal answers and must not be relabelled into a third one.
9345        crate::run::pin_test_home();
9346        let mut failed = run_state(RunStatus::Failed);
9347        failed.id = "20260101-000000-sup6".to_owned();
9348        failed.save().unwrap();
9349        let mut noop = run_state(RunStatus::VerifiedNoop);
9350        noop.id = "20260101-000000-sup7".to_owned();
9351        noop.save().unwrap();
9352        let mut winner = run_state(RunStatus::Ready);
9353        winner.id = "20260101-000000-sup8".to_owned();
9354        winner.save().unwrap();
9355
9356        let mut t = task();
9357        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9358        t.status = TaskStatus::Done;
9359
9360        supersede_prior_runs(&t, &crate::run::home());
9361
9362        assert_eq!(
9363            RunState::load(&failed.id).unwrap().status,
9364            RunStatus::Failed
9365        );
9366        assert_eq!(
9367            RunState::load(&noop.id).unwrap().status,
9368            RunStatus::VerifiedNoop
9369        );
9370    }
9371
9372    fn approval_question(run: &str) -> ask::Question {
9373        ask::Question::new(
9374            run.to_owned(),
9375            land::APPROVAL_NODE.to_owned(),
9376            "land".to_owned(),
9377            "merge?".to_owned(),
9378            String::new(),
9379            vec!["merge".to_owned(), "hold".to_owned()],
9380        )
9381    }
9382
9383    #[test]
9384    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9385        crate::run::pin_test_home();
9386        let mut state = run_state(RunStatus::Landing);
9387        state.id = "20260101-000000-fre1".to_owned();
9388        state.parked = true;
9389        state.save().unwrap();
9390        ask::Questions::open()
9391            .put(&mut approval_question(&state.id))
9392            .unwrap();
9393
9394        let mut t = task();
9395        t.runs.push(state.id.clone());
9396        assert_eq!(
9397            land_resume_state(&t),
9398            LandResume::StillWaiting,
9399            "nobody has answered and the timeout has not passed"
9400        );
9401    }
9402
9403    #[test]
9404    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9405        crate::run::pin_test_home();
9406        let mut state = run_state(RunStatus::Gating);
9407        state.id = "20260101-000000-gt01".to_owned();
9408        state.parked = true;
9409        state.config.graph.answer_timeout = 60;
9410        state.github_text = Some(crate::run::GithubTextAsk {
9411            rewrite: None,
9412            fingerprint: "f".into(),
9413            title: true,
9414            body: false,
9415            categories: vec!["title-language".into()],
9416            question: None,
9417            asks: 1,
9418            resolved: false,
9419            chosen_title: None,
9420            choice: None,
9421            publication: None,
9422        });
9423        state.save().unwrap();
9424        let store = ask::Questions::open();
9425        let mut q = ask::Question::new(
9426            state.id.clone(),
9427            crate::github_text::ASK_NODE.to_owned(),
9428            crate::github_text::ASK_SEAT.to_owned(),
9429            "s".into(),
9430            String::new(),
9431            vec!["use fallback".into()],
9432        );
9433        store.put(&mut q).unwrap();
9434        let mut t = task();
9435        t.runs.push(state.id.clone());
9436        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9437        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9438        store.put(&mut q).unwrap();
9439        assert_eq!(land_resume_state(&t), LandResume::Ready);
9440        assert!(!store.get(&q.id).unwrap().status.open());
9441        // Once decided, a parked run is an ordinary candidate again.
9442        state.github_text.as_mut().unwrap().resolved = true;
9443        state.save().unwrap();
9444        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9445    }
9446
9447    #[test]
9448    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9449        // `ask::ask_and_wait`'s own deadline used to retire a question
9450        // nobody answered; land's approval bypasses that wait (see
9451        // `land::approval_gate`), so this is now the only place
9452        // `graph.answer_timeout` is enforced for a land approval at all.
9453        crate::run::pin_test_home();
9454        let mut state = run_state(RunStatus::Landing);
9455        state.id = "20260101-000000-exp1".to_owned();
9456        state.parked = true;
9457        state.config.graph.answer_timeout = 60;
9458        state.save().unwrap();
9459
9460        let store = ask::Questions::open();
9461        let mut q = approval_question(&state.id);
9462        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9463        store.put(&mut q).unwrap();
9464
9465        let mut t = task();
9466        t.runs.push(state.id.clone());
9467        assert_eq!(
9468            land_resume_state(&t),
9469            LandResume::Ready,
9470            "an expired question must not be waited on forever"
9471        );
9472
9473        let after = store.get(&q.id).unwrap();
9474        assert!(
9475            !after.status.open(),
9476            "the question is abandoned, not silently ignored"
9477        );
9478        assert!(
9479            after.resolution().is_none(),
9480            "an abandoned question is not read as a decision"
9481        );
9482    }
9483
9484    #[test]
9485    fn reclaim_settles_a_running_task_against_its_last_run() {
9486        let mut t = task();
9487        t.start("20260904-000000-4043".to_owned());
9488        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9489        assert_eq!(
9490            t.status,
9491            TaskStatus::Done,
9492            "a run that actually finished must not stay `running` forever"
9493        );
9494    }
9495
9496    #[test]
9497    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
9498        let dir = tempfile::tempdir().unwrap();
9499        let queue = Queue::at(dir.path().join("queue"));
9500        let mut task = task();
9501        let mut run = run_state(RunStatus::Blocked);
9502        run.reserve_under(dir.path()).unwrap();
9503        run.driver_exited = true;
9504        run.save_under(dir.path()).unwrap();
9505        queue.put(&mut task).unwrap();
9506        let stale = task.clone();
9507        task.resume_override = Some(crate::queue::OperatorResume {
9508            question_id: "pending-resume".into(),
9509            at: Timestamp::now(),
9510            conductor_rehold: None,
9511            forced: true,
9512            pinned_run: Some(run.id.clone()),
9513        });
9514        task.start(run.id.clone());
9515        queue.put(&mut task).unwrap();
9516        // Discard every in-memory handoff, as a worker death before execute does.
9517        let mut recovered = queue.get(&task.id).unwrap();
9518        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
9519        reclaim(&mut recovered, Some(disk), 2, "en");
9520        queue.put(&mut recovered).unwrap();
9521        assert!(recovered.resume_override.is_none());
9522        assert_eq!(
9523            recovered.dispatched_resumes.get("pending-resume"),
9524            Some(&run.id)
9525        );
9526        let mut stale = stale;
9527        queue.put(&mut stale).unwrap();
9528        assert_eq!(
9529            stale.dispatched_resumes, recovered.dispatched_resumes,
9530            "a stale task writer cannot erase dispatch ownership"
9531        );
9532        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
9533        assert!(resumed.decision_starts.is_empty());
9534        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
9535        assert!(
9536            resumed.decision_starts.is_empty(),
9537            "handoff is not execution proof"
9538        );
9539        resumed.begin_pass();
9540        resumed.save_under(dir.path()).unwrap();
9541        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
9542        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
9543        disk.carry_dispatched_resumes(&recovered);
9544        disk.begin_pass();
9545        assert_eq!(
9546            disk.decision_starts.get("pending-resume"),
9547            Some(&0),
9548            "later execution must preserve the original pass receipt"
9549        );
9550    }
9551
9552    #[test]
9553    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9554        let mut t = task();
9555        t.start("20260904-000000-4043".to_owned());
9556        t.last_error = Some("earlier trouble".to_owned());
9557        let mut state = run_state(RunStatus::Judging);
9558        state.parked = true;
9559        reclaim(&mut t, Some(state), 1, "en");
9560        assert_eq!(t.status, TaskStatus::Parked);
9561        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9562        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9563        assert!(t.park_reason.is_some());
9564        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9565        assert!(!t.fresh_start);
9566        assert!(t.status.runnable());
9567    }
9568
9569    #[test]
9570    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9571        let mut t = task();
9572        t.start("20260904-000000-4043".to_owned());
9573        t.last_error = Some("earlier trouble".to_owned());
9574        settle(
9575            &mut t,
9576            Verdict {
9577                status: RunStatus::Judging,
9578                left_pr: false,
9579                quota_hit: false,
9580                parked: true,
9581                no_viable_candidates: false,
9582            },
9583            "parked after `judging`",
9584            1,
9585        );
9586        assert_eq!(t.status, TaskStatus::Parked);
9587        assert_eq!(t.attempts, 0);
9588        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9589        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9590        assert_eq!(t.schema, crate::queue::SCHEMA);
9591        assert!(
9592            crate::notices::task_held(&t).is_none(),
9593            "a park is not news"
9594        );
9595        t.start("20260904-000000-4043".to_owned());
9596        assert_eq!(t.park_reason, None);
9597    }
9598
9599    #[test]
9600    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9601        // A blocked run with attempts left goes back to `Failed`, exactly as
9602        // it would from `attempt` itself - `reclaim` must not invent a second
9603        // policy for a task a daemon merely stopped without reporting.
9604        let mut t = task();
9605        t.start("20260904-000000-4043".to_owned());
9606        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9607        assert_eq!(t.status, TaskStatus::Failed);
9608        assert!(t.status.runnable());
9609    }
9610
9611    #[test]
9612    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9613        let mut t = task();
9614        t.start("20260904-000000-4043".to_owned());
9615        assert_eq!(t.attempts, 1);
9616        let mut run = run_state(RunStatus::Implementing);
9617        run.id = "20260904-000000-4043".to_owned();
9618        run.begin_pass();
9619        let cause = crate::run::ParkCause::Upgrade {
9620            from: "0.121.0".to_owned(),
9621            to: Some("0.121.1".to_owned()),
9622        };
9623        run.end_pass_parked(cause.clone());
9624        run.parked = true;
9625        let verdict = Verdict {
9626            status: run.status,
9627            left_pr: false,
9628            quota_hit: false,
9629            parked: true,
9630            no_viable_candidates: false,
9631        };
9632        // A crash after the checkpoint but before queue settlement must
9633        // recover exactly the same scheduling evidence and refund.
9634        let mut orphan = t.clone();
9635        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9636        assert_eq!(orphan.status, TaskStatus::Parked);
9637        assert_eq!(orphan.attempts, 0);
9638        assert_eq!(
9639            orphan.upgrade_resume_key(),
9640            Some((run.passes[0].started_at, orphan.id.as_str()))
9641        );
9642        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9643        assert_eq!(t.attempts, 0);
9644        assert_eq!(t.passes.len(), 1);
9645        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9646        assert_eq!(t.passes[0].parked, Some(cause));
9647        assert_eq!(t.passes[0].pass_index, 0);
9648        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9649        assert!(t.upgrade_resume_key().is_some());
9650
9651        // A resumed pass that then fails spends its attempt, and the earlier
9652        // pass's entry is untouched.
9653        t.start("20260904-000000-4043".to_owned());
9654        run.begin_pass();
9655        run.status = RunStatus::Failed;
9656        let verdict = Verdict {
9657            status: RunStatus::Failed,
9658            left_pr: false,
9659            quota_hit: false,
9660            parked: false,
9661            no_viable_candidates: false,
9662        };
9663        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9664        assert_eq!(t.passes.len(), 2);
9665        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9666        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9667        assert_eq!(t.passes[1].pass_index, 1);
9668        assert_eq!(t.attempts, 1);
9669    }
9670
9671    #[test]
9672    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9673        let mut t = task();
9674        t.start("20260904-000000-4043".to_owned());
9675        reclaim(&mut t, None, 2, "en");
9676        assert_eq!(t.status, TaskStatus::Held);
9677        assert!(
9678            t.last_error
9679                .as_deref()
9680                .is_some_and(|e| e.contains("running")),
9681            "the operator needs to know why this task was held"
9682        );
9683    }
9684
9685    #[test]
9686    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9687        let dir = tempfile::tempdir().unwrap();
9688        let queue = Queue::at(dir.path().to_path_buf());
9689
9690        // No run recorded, so this never has to touch `RunState::load`.
9691        let mut orphaned = task();
9692        orphaned.id = "20260904-000000-orph".to_owned();
9693        orphaned.status = TaskStatus::Running;
9694        orphaned.attempts = 1;
9695        queue.put(&mut orphaned).unwrap();
9696
9697        let mut alive = task();
9698        alive.id = "20260904-000000-live".to_owned();
9699        alive.status = TaskStatus::Running;
9700        alive.attempts = 1;
9701        queue.put(&mut alive).unwrap();
9702        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9703
9704        let mut queued = task();
9705        queued.id = "20260904-000000-wait".to_owned();
9706        queue.put(&mut queued).unwrap();
9707
9708        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9709        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9710
9711        assert_eq!(
9712            queue.get(&orphaned.id).unwrap().status,
9713            TaskStatus::Held,
9714            "nothing was driving it and there was no run to recover"
9715        );
9716        assert_eq!(
9717            queue.get(&alive.id).unwrap().status,
9718            TaskStatus::Running,
9719            "a live claim must protect the task it belongs to"
9720        );
9721        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9722    }
9723
9724    /// Read a run.json back from an explicit `home`, the same way
9725    /// `reclaim_abandoned_runs` itself does - never through the
9726    /// process-global `RunState::load`, which this test's own `home` (an
9727    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
9728    /// use at all.
9729    fn read_run_under(home: &Path, id: &str) -> RunState {
9730        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9731        serde_json::from_str(&body).unwrap()
9732    }
9733
9734    #[test]
9735    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9736        let dir = tempfile::tempdir().unwrap();
9737        let home = dir.path().to_path_buf();
9738        let now = Timestamp::now();
9739        let overrun_seat = || crate::run::ActiveSeat {
9740            node: "implement".to_owned(),
9741            started_at: now - jiff::SignedDuration::new(21_000, 0),
9742            timeout_secs: 3_600,
9743            attempt: 0,
9744            task: None,
9745            command: None,
9746            index: None,
9747            total: None,
9748        };
9749
9750        let mut dead = run_state(RunStatus::Implementing);
9751        dead.id = "20260101-000000-dead".to_owned();
9752        dead.active.insert("impl-A".to_owned(), overrun_seat());
9753        // A `driver_pid` the injected query below confirms gone outright —
9754        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
9755        dead.driver_pid = Some(4242);
9756        dead.save_under(&home).unwrap();
9757
9758        // Same shape, but a live daemon's heartbeat names it: must be left
9759        // exactly alone, however far past its own timeout the seat sits.
9760        let mut alive = run_state(RunStatus::Implementing);
9761        alive.id = "20260101-000000-aliv".to_owned();
9762        alive.active.insert("impl-A".to_owned(), overrun_seat());
9763        alive.save_under(&home).unwrap();
9764        let mut status = Status::new();
9765        status.current = vec![Current {
9766            worker: None,
9767            task: "20260101-000000-task".to_owned(),
9768            run: alive.id.clone(),
9769        }];
9770        write_status_to(&home.join("daemon.json"), &status).unwrap();
9771
9772        // The abandoned seat left an open question behind: nobody is left to
9773        // read an answer once the run is failed, and this must not wait for
9774        // some later daemon startup's own sweep to notice that.
9775        let questions = Questions::at(home.join("questions"));
9776        let mut q = ask::Question::new(
9777            dead.id.clone(),
9778            "implement".to_owned(),
9779            "impl-A".to_owned(),
9780            "Which storage backend?".to_owned(),
9781            String::new(),
9782            vec!["SQLite".to_owned(), "Redis".to_owned()],
9783        );
9784        questions.put(&mut q).unwrap();
9785
9786        let abandoned = reclaim_abandoned_runs_with(
9787            &home,
9788            now,
9789            |pid| if pid == 4242 { Some(false) } else { None },
9790            |_| panic!("a query answering Dead outright needs no identity corroboration"),
9791        );
9792        assert_eq!(abandoned, vec![dead.id.clone()]);
9793
9794        let reloaded = read_run_under(&home, &dead.id);
9795        assert_eq!(reloaded.status, RunStatus::Failed);
9796        assert!(reloaded.active.is_empty());
9797        assert!(
9798            !questions.get(&q.id).unwrap().status.open(),
9799            "the failed run's own open question must be settled in the same pass"
9800        );
9801
9802        let still_alive = read_run_under(&home, &alive.id);
9803        assert_eq!(
9804            still_alive.status,
9805            RunStatus::Implementing,
9806            "a live daemon's claim protects it"
9807        );
9808        assert!(!still_alive.active.is_empty());
9809    }
9810
9811    /// The exact shape a review round flagged as broken: `magi serve` running
9812    /// in this same `home` scans *every* run on disk, including a manual
9813    /// `magi review` / `magi run` this daemon never started and that
9814    /// therefore claims no heartbeat of its own. Before this scan asked
9815    /// `liveness` rather than just `is_working_on`, a manual run whose active
9816    /// seat merely ran a little past its own timeout — the CLI finishing up,
9817    /// its result still being collected — got wiped and failed by a daemon
9818    /// that had nothing to do with it, out from under a process that was
9819    /// still very much running.
9820    #[test]
9821    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9822        let dir = tempfile::tempdir().unwrap();
9823        let home = dir.path().to_path_buf();
9824        let now = Timestamp::now();
9825
9826        let mut manual = run_state(RunStatus::Reviewing);
9827        manual.id = "20260101-000000-manl".to_owned();
9828        manual.active.insert(
9829            "review-1".to_owned(),
9830            crate::run::ActiveSeat {
9831                node: "review".to_owned(),
9832                started_at: now - jiff::SignedDuration::new(21_000, 0),
9833                timeout_secs: 3_600,
9834                attempt: 0,
9835                task: None,
9836                command: None,
9837                index: None,
9838                total: None,
9839            },
9840        );
9841        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
9842        // but a real, still-running process: `liveness` must corroborate this
9843        // as `Live`, not read the missing daemon claim as death.
9844        manual.driver_pid = Some(4242);
9845        manual.driver_started_at = Some("1790000000".to_owned());
9846        manual.save_under(&home).unwrap();
9847
9848        let abandoned = reclaim_abandoned_runs_with(
9849            &home,
9850            now,
9851            |pid| if pid == 4242 { Some(true) } else { None },
9852            |pid| {
9853                if pid == 4242 {
9854                    Some("1790000000".to_owned())
9855                } else {
9856                    None
9857                }
9858            },
9859        );
9860        assert!(
9861            abandoned.is_empty(),
9862            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9863        );
9864
9865        let reloaded = read_run_under(&home, &manual.id);
9866        assert_eq!(reloaded.status, RunStatus::Reviewing);
9867        assert!(!reloaded.active.is_empty());
9868    }
9869
9870    #[test]
9871    fn an_already_claimed_task_is_skipped_rather_than_failed() {
9872        let dir = tempfile::tempdir().unwrap();
9873        let queue = Queue::at(dir.path().to_path_buf());
9874        let mut only = task();
9875        queue.put(&mut only).unwrap();
9876
9877        let _elsewhere = queue.claim(&only.id).unwrap();
9878        let candidates = runnable(&queue);
9879        assert_eq!(candidates.len(), 1, "the task is still runnable");
9880        assert!(
9881            queue.claim(&candidates[0].id).is_err(),
9882            "the loop cannot take a claim somebody else holds"
9883        );
9884
9885        let after = queue.get(&only.id).unwrap();
9886        assert_eq!(after.status, TaskStatus::Queued);
9887        assert_eq!(
9888            after.attempts, 0,
9889            "losing the race is not an attempt at the task"
9890        );
9891        assert_eq!(after.last_error, None);
9892    }
9893
9894    #[test]
9895    fn the_status_file_round_trips_and_its_heartbeat_advances() {
9896        let dir = tempfile::tempdir().unwrap();
9897        let path = dir.path().join("daemon.json");
9898
9899        let mut status = Status::new();
9900        status.idle = false;
9901        status.completed = 7;
9902        status.current = vec![Current {
9903            worker: None,
9904            task: "20260902-000000-t111".to_owned(),
9905            run: "20260902-000001-r111".to_owned(),
9906        }];
9907        write_status_to(&path, &status).unwrap();
9908        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9909        assert_eq!(first.schema, SCHEMA);
9910        assert_eq!(first.pid, std::process::id());
9911        assert!(!first.idle);
9912        assert_eq!(first.completed, 7);
9913        assert_eq!(first.current, status.current);
9914        assert!(
9915            !path.with_extension("json.tmp").exists(),
9916            "the temp file is renamed, not left behind"
9917        );
9918
9919        std::thread::sleep(Duration::from_millis(5));
9920        status.updated_at = Timestamp::now();
9921        status.polls = 3;
9922        write_status_to(&path, &status).unwrap();
9923        let second: Status =
9924            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9925        assert!(
9926            second.updated_at > first.updated_at,
9927            "a reader can only detect staleness if the heartbeat moves"
9928        );
9929        assert_eq!(
9930            second.started_at, first.started_at,
9931            "the start time is not a heartbeat"
9932        );
9933        assert_eq!(second.polls, 3);
9934    }
9935
9936    #[test]
9937    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9938        let dir = tempfile::tempdir().unwrap();
9939
9940        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9941
9942        let mut status = Status::new();
9943        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9944        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9945        let stale = read_status(dir.path()).unwrap();
9946        assert!(
9947            !stale.running(Timestamp::now()),
9948            "a minute without a heartbeat is a dead daemon, not a busy one"
9949        );
9950        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9951
9952        status.updated_at = Timestamp::now();
9953        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9954        let fresh = read_status(dir.path()).unwrap();
9955        assert!(fresh.running(Timestamp::now()));
9956    }
9957
9958    #[test]
9959    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9960        let dir = tempfile::tempdir().unwrap();
9961        let now = Timestamp::now();
9962        let mine = "20260903-080619-01c2";
9963
9964        assert!(
9965            !is_working_on(dir.path(), mine, now),
9966            "no status file means nobody is working on anything"
9967        );
9968
9969        let mut status = Status::new();
9970        status.current = vec![Current {
9971            worker: None,
9972            task: "20260903-080340-0167".to_owned(),
9973            run: mine.to_owned(),
9974        }];
9975        status.updated_at = now;
9976        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9977        assert!(is_working_on(dir.path(), mine, now));
9978        assert!(
9979            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9980            "a daemon busy with one run is not working on another"
9981        );
9982
9983        // A killed daemon stops writing heartbeats but leaves the file behind
9984        // naming the run it died in. That run must not be undeletable forever.
9985        status.updated_at = now - jiff::SignedDuration::from_secs(600);
9986        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9987        assert!(
9988            !is_working_on(dir.path(), mine, now),
9989            "a stale heartbeat is a dead daemon, so its run is a leftover"
9990        );
9991    }
9992
9993    #[test]
9994    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9995        let dir = tempfile::tempdir().unwrap();
9996        let now = Timestamp::now();
9997
9998        assert!(
9999            !is_working_on_short(dir.path(), "01c2", now),
10000            "no status file means nobody is working on anything"
10001        );
10002
10003        let mut status = Status::new();
10004        status.current = vec![Current {
10005            worker: None,
10006            task: "20260903-080340-0167".to_owned(),
10007            run: "20260903-080619-01c2".to_owned(),
10008        }];
10009        status.updated_at = now;
10010        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10011        assert!(
10012            is_working_on_short(dir.path(), "01c2", now),
10013            "the run's short id is the last block of its full id"
10014        );
10015        assert!(
10016            !is_working_on_short(dir.path(), "3cbf", now),
10017            "a daemon busy with one worktree bay is not working on another"
10018        );
10019    }
10020
10021    #[test]
10022    fn a_newer_status_file_still_yields_a_reading() {
10023        let dir = tempfile::tempdir().unwrap();
10024        // A field this build has never heard of must not turn the reading into
10025        // nothing at all; that is the whole reason the reader is permissive.
10026        std::fs::write(
10027            dir.path().join("daemon.json"),
10028            serde_json::json!({
10029                "schema": 2,
10030                "updated_at": Timestamp::now().to_string(),
10031                "idle": true,
10032                "surprise": { "nested": [1, 2, 3] },
10033            })
10034            .to_string(),
10035        )
10036        .unwrap();
10037
10038        let reading = read_status(dir.path()).expect("a forward-compatible read");
10039        assert!(reading.running(Timestamp::now()));
10040        assert!(reading.idle);
10041        assert!(reading.current.is_empty());
10042    }
10043
10044    #[test]
10045    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
10046        // A daemon started before `current` became a list keeps writing this
10047        // shape on every heartbeat until it is restarted. A rolling upgrade
10048        // - a newer `magi web` or `magi doctor` reading an older `magi
10049        // serve`'s heartbeat - must still see the run it is on, not "no
10050        // daemon" from a type mismatch failing the whole struct.
10051        let dir = tempfile::tempdir().unwrap();
10052        std::fs::write(
10053            dir.path().join("daemon.json"),
10054            serde_json::json!({
10055                "schema": 1,
10056                "pid": 4242,
10057                "updated_at": Timestamp::now().to_string(),
10058                "idle": false,
10059                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
10060                "completed": 3,
10061                "polls": 9,
10062            })
10063            .to_string(),
10064        )
10065        .unwrap();
10066
10067        let reading = read_status(dir.path()).expect("an older shape must still parse");
10068        assert!(reading.running(Timestamp::now()));
10069        assert_eq!(
10070            reading.current,
10071            vec![Current {
10072                worker: None,
10073                task: "20260902-140501-aaaa".to_owned(),
10074                run: "20260902-140502-bbbb".to_owned(),
10075            }]
10076        );
10077    }
10078
10079    #[test]
10080    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
10081        let dir = tempfile::tempdir().unwrap();
10082        std::fs::write(
10083            dir.path().join("daemon.json"),
10084            serde_json::json!({
10085                "schema": 1,
10086                "updated_at": Timestamp::now().to_string(),
10087                "idle": true,
10088                "current": null,
10089            })
10090            .to_string(),
10091        )
10092        .unwrap();
10093        let with_null = read_status(dir.path()).expect("null must still parse");
10094        assert!(with_null.current.is_empty());
10095
10096        std::fs::write(
10097            dir.path().join("daemon.json"),
10098            serde_json::json!({
10099                "schema": 1,
10100                "updated_at": Timestamp::now().to_string(),
10101                "idle": true,
10102            })
10103            .to_string(),
10104        )
10105        .unwrap();
10106        let absent = read_status(dir.path()).expect("a missing field must still parse");
10107        assert!(absent.current.is_empty());
10108    }
10109
10110    #[test]
10111    fn a_task_without_a_repository_runs_in_the_daemons_default() {
10112        let fallback = Path::new("/default");
10113        let mut blank = task();
10114        blank.repo = PathBuf::new();
10115        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
10116        let mut dot = task();
10117        dot.repo = PathBuf::from(".");
10118        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
10119        assert_eq!(
10120            repo_for(&task(), fallback),
10121            PathBuf::from("/repo"),
10122            "a task that names a repository keeps it"
10123        );
10124    }
10125
10126    #[test]
10127    fn task_implementers_edit_inherits_daemon_config_and_merge() {
10128        let dir = tempfile::tempdir().unwrap();
10129        let path = dir.path().join("explicit.toml");
10130        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
10131        let opts = Opts {
10132            config: Some(path),
10133            merge: Some("none".into()),
10134            ..Default::default()
10135        };
10136        let mut t = task();
10137        t.set_implementers(
10138            2,
10139            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10140                .unwrap(),
10141        )
10142        .unwrap();
10143        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10144        assert_eq!(cfg.graph.implementers, 2);
10145        assert_eq!(cfg.graph.judges, 1);
10146        assert_eq!(cfg.merge.mode, MergeMode::None);
10147        t.set_implementers(1, &cfg).unwrap();
10148        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10149        apply_task_implementers(&mut cfg, &t);
10150        assert_eq!(cfg.graph.implementers, 1);
10151        assert_eq!(cfg.graph.judges, 1);
10152        assert_eq!(cfg.merge.mode, MergeMode::None);
10153    }
10154
10155    #[test]
10156    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
10157        let dir = tempfile::tempdir().unwrap();
10158        let repo = dir.path().join("repo");
10159        std::fs::create_dir(&repo).unwrap();
10160        std::fs::write(
10161            repo.join("magi.toml"),
10162            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
10163        )
10164        .unwrap();
10165        let daemon_config = dir.path().join("daemon.toml");
10166        std::fs::write(
10167            &daemon_config,
10168            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
10169        )
10170        .unwrap();
10171        let opts = Opts {
10172            config: Some(daemon_config),
10173            merge: Some("pr".into()),
10174            ..Default::default()
10175        };
10176        let q = Queue::at(dir.path().join("queue"));
10177        let validation: Config =
10178            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10179                .unwrap();
10180        // No provenance field on legacy direct tasks: both shapes stay isolated.
10181        for record in ["{}", r#"{"candidates":2}"#] {
10182            let overrides = serde_json::from_str(record).unwrap();
10183            let filing = crate::direct::Filing {
10184                instruction: "work".into(),
10185                title: "direct".into(),
10186                repo: repo.clone(),
10187                source: crate::queue::Source::Human,
10188                solo: false,
10189                overrides,
10190                review_of: None,
10191                sources: Default::default(),
10192            };
10193            let filed =
10194                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
10195            let crate::direct::Filed::Standalone {
10196                mut task,
10197                claim: _claim,
10198            } = filed
10199            else {
10200                panic!("local filing")
10201            };
10202            let before = prepare_for(&repo, &opts, &task).unwrap();
10203            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
10204            assert_eq!(
10205                before.merge.mode,
10206                MergeMode::None,
10207                "daemon --merge must not leak"
10208            );
10209            for n in [2, 1, 2] {
10210                task.set_implementers(n, &validation).unwrap();
10211                q.put(&mut task).unwrap();
10212                task = q.get(&task.id).unwrap();
10213                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
10214                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
10215                apply_task_implementers(&mut cfg, &task);
10216                assert_eq!(cfg.graph.implementers, usize::from(n));
10217                assert_eq!(cfg.graph.judges, 2);
10218                assert_eq!(cfg.merge.mode, MergeMode::None);
10219            }
10220        }
10221    }
10222
10223    #[test]
10224    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
10225        let cfg: Config =
10226            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10227                .unwrap();
10228        let mut t = task();
10229        t.review_of = Some("review-target".into());
10230        t.hold_manual(Some("retry".into()));
10231        let mut previous = RunState::new(
10232            PathBuf::from("/repo"),
10233            "main".into(),
10234            "abc1234".into(),
10235            "review".into(),
10236            cfg.clone(),
10237        );
10238        previous.config.graph.implementers = 2;
10239        for count in [1, 3] {
10240            t.set_implementers(count, &cfg).unwrap();
10241            t.release();
10242            assert_eq!(t.review_of.as_deref(), Some("review-target"));
10243            for proposed in [
10244                Starter::Resume(previous.id.clone()),
10245                Starter::Review("recovery-target".into()),
10246            ] {
10247                assert_eq!(
10248                    starter_with_implementers(&t, Some(&previous), proposed),
10249                    Starter::Review("review-target".into())
10250                );
10251            }
10252            let mut configured = cfg.clone();
10253            apply_task_implementers(&mut configured, &t);
10254            assert_eq!(configured.graph.implementers, usize::from(count));
10255            assert_eq!(previous.config.graph.implementers, 2);
10256        }
10257    }
10258
10259    #[test]
10260    fn task_implementers_dispatch_and_resume_agree() {
10261        let mut t = task();
10262        let cfg: crate::config::Config =
10263            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10264                .unwrap();
10265        let mut run = RunState::new(
10266            PathBuf::from("/repo"),
10267            "main".into(),
10268            "abc1234".into(),
10269            "work".into(),
10270            cfg.clone(),
10271        );
10272        run.config.graph.implementers = 2;
10273        for n in [2, 1, 3, 2] {
10274            t.set_implementers(n, &cfg).unwrap();
10275            let mut dispatched = cfg.clone();
10276            apply_task_implementers(&mut dispatched, &t);
10277            assert_eq!(dispatched.graph.implementers, usize::from(n));
10278            assert_eq!(implementers_match(&t, &run), n == 2);
10279            for proposed in [
10280                Starter::Resume(run.id.clone()),
10281                Starter::Review("old-branch".into()),
10282            ] {
10283                let expected = if n == 2 {
10284                    proposed.clone()
10285                } else {
10286                    Starter::Start
10287                };
10288                assert_eq!(
10289                    starter_with_implementers(&t, Some(&run), proposed),
10290                    expected
10291                );
10292            }
10293            assert_eq!(
10294                run.config.graph.implementers, 2,
10295                "history must not be rewritten"
10296            );
10297        }
10298        t.solo = false;
10299        t.overrides = None;
10300        assert!(implementers_match(&t, &run));
10301    }
10302
10303    #[test]
10304    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
10305        // Three seats said out loud. What `solo` promises is one candidate
10306        // *whatever the config asks for*, so the contrast has to be a number
10307        // this test owns - it used to be `Config::default()`'s, which became
10308        // 1 when one implementation became the default and left the two
10309        // halves of this test asserting the same thing.
10310        let mut solo_cfg = Config::default();
10311        solo_cfg.graph.implementers = 3;
10312        let mut solo_task = task();
10313        solo_task.solo = true;
10314        apply_task_implementers(&mut solo_cfg, &solo_task);
10315        assert_eq!(solo_cfg.graph.implementers, 1);
10316
10317        let mut plain_cfg = Config::default();
10318        plain_cfg.graph.implementers = 3;
10319        let plain_task = task();
10320        assert!(!plain_task.solo);
10321        apply_task_implementers(&mut plain_cfg, &plain_task);
10322        assert_eq!(
10323            plain_cfg.graph.implementers, 3,
10324            "a task that did not ask to run alone keeps the config's candidates"
10325        );
10326    }
10327
10328    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
10329        QuotaLoss {
10330            cause: crate::agent::QuotaCause::UsageLimit,
10331            agent: String::new(),
10332            seat: seat.into(),
10333            node: "judge".into(),
10334            at: at.parse().unwrap(),
10335            reset: reset.map(str::to_string),
10336        }
10337    }
10338
10339    #[test]
10340    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
10341        let now = Timestamp::now();
10342        for reset in [None, Some("in 1h")] {
10343            let auth = crate::agent::Quota {
10344                cause: crate::agent::QuotaCause::Authentication,
10345                agent: "alpha".into(),
10346                reset: reset.map(str::to_owned),
10347            };
10348            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
10349            assert_eq!(cooldown_until(&[loss], now), None);
10350        }
10351    }
10352
10353    #[test]
10354    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
10355        let old: Vec<QuotaLoss> = (1..=4)
10356            .map(|i| {
10357                loss(
10358                    &format!("judge-{i}"),
10359                    "2026-09-23T05:23:00Z",
10360                    Some("2:40pm (Asia/Tokyo)"),
10361                )
10362            })
10363            .collect();
10364        let fresh = losses_this_attempt(&old, &old);
10365        assert!(fresh.is_empty());
10366        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
10367        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
10368    }
10369
10370    #[test]
10371    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
10372        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
10373        let now = Timestamp::now();
10374        let mut after = old.clone();
10375        after.push(loss("judge-2", &now.to_string(), None));
10376        let fresh = losses_this_attempt(&old, &after);
10377        assert_eq!(fresh, vec![after[1].clone()]);
10378        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
10379        assert_eq!(
10380            until,
10381            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
10382        );
10383    }
10384
10385    #[test]
10386    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
10387        // `recover_stall` removes judge-1's loss and the retry then hits quota
10388        // again: the vector is the same length, so an index diff sees nothing.
10389        let before = vec![
10390            loss("judge-1", "2026-09-23T05:23:00Z", None),
10391            loss("judge-2", "2026-09-23T05:24:00Z", None),
10392        ];
10393        let after = vec![
10394            loss("judge-2", "2026-09-23T05:24:00Z", None),
10395            loss("judge-1", "2026-09-24T01:00:00Z", None),
10396        ];
10397        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
10398    }
10399
10400    #[test]
10401    fn merge_overrides_are_parsed_or_refused() {
10402        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
10403        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
10404        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
10405        assert!(merge_mode("squash").is_err());
10406    }
10407
10408    #[test]
10409    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
10410        let now = Timestamp::now();
10411        let fallback = Duration::from_secs(300);
10412        let cap = Duration::from_secs(1800);
10413
10414        // No reset hint at all: the fallback.
10415        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
10416
10417        // A reset ten minutes out, well inside the cap: waited for exactly.
10418        let soon = now + jiff::SignedDuration::from_secs(600);
10419        assert_eq!(
10420            quota_wait(Some(soon), now, fallback, cap),
10421            Duration::from_secs(600)
10422        );
10423
10424        // A reset already in the past is not trusted: the fallback, not a
10425        // zero or negative wait that would spin the loop right back around.
10426        let past = now - jiff::SignedDuration::from_secs(60);
10427        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
10428
10429        // A reset further out than the cap is trusted for direction but not
10430        // for magnitude: a parsing slip must not sleep the loop for a day.
10431        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
10432        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
10433    }
10434
10435    #[test]
10436    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
10437        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10438
10439        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
10440        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
10441
10442        // Same clock reading, but it has already gone by today: read as
10443        // tomorrow's, since the CLI would not still be reporting a limit past
10444        // its own stated reset.
10445        let already_past =
10446            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
10447        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
10448
10449        assert!(
10450            parse_reset_hint("session limit reached", now, now).is_none(),
10451            "free text with no recognised shape is not guessed at"
10452        );
10453        assert!(
10454            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
10455            "an unresolvable zone name is not guessed at either"
10456        );
10457    }
10458
10459    #[test]
10460    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
10461        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10462
10463        let at = parse_reset_hint(
10464            "You've hit your usage limit. Visit \
10465             https://chatgpt.com/codex/settings/usage to purchase more \
10466             credits or try again at Sep 19th, 2026 5:10 PM.",
10467            now,
10468            now,
10469        )
10470        .expect("the codex reset wording is a recognised shape");
10471        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
10472
10473        // The month is explicit, so a date already earlier in the same
10474        // sentence-implied year than `now` is trusted as written rather than
10475        // rolled forward a year the way the bracketed shape rolls a
10476        // same-day clock reading to tomorrow.
10477        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
10478            .expect("an explicit year needs no rollover");
10479        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
10480
10481        assert!(
10482            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
10483            "a two-digit year is not the documented shape and is not guessed at"
10484        );
10485        assert!(
10486            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
10487            "a four-letter month name is not the documented three-letter abbreviation"
10488        );
10489        assert!(
10490            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10491            "an explicit zone on the dated shape is a format nobody has \
10492             documented, and is refused rather than guessed at as UTC"
10493        );
10494    }
10495
10496    #[test]
10497    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10498        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10499        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10500
10501        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10502        assert_eq!(at.as_second() - recorded.as_second(), 3769);
10503
10504        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10505        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10506
10507        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10508            assert!(
10509                parse_reset_hint(bad, now, recorded).is_none(),
10510                "{bad:?} must not be guessed at"
10511            );
10512        }
10513    }
10514
10515    /// A loop whose queue lives in a temp tree and whose poll interval is far
10516    /// longer than the test's patience, so anything that waits out a poll
10517    /// instead of noticing the stop fails rather than merely being slow.
10518    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10519        let config = dir.join("magi.toml");
10520        std::fs::write(
10521            &config,
10522            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10523        )
10524        .unwrap();
10525        let opts = Opts {
10526            poll: Duration::from_secs(30),
10527            config: Some(config),
10528            // The explicit fixture config keeps startup cleanup from reading
10529            // machine configuration. This fictional repository likewise
10530            // keeps any best-effort git cleanup away from this checkout.
10531            repo: dir.join("repo"),
10532            ..Opts::default()
10533        };
10534        // The status file goes in a directory that does not exist yet, so its
10535        // creation is itself evidence the loop published one. `worktrees`
10536        // must be just as fictional: the janitor reclaims worktrees under it
10537        // for real, and a test that let it fall through to
10538        // `crate::run::default_worktree_root()` would have it reclaim
10539        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
10540        // which is exactly what happened before this function took the
10541        // parameter at all.
10542        let home = dir.join("home");
10543        // These control-only fixtures do not launch native workers. Give the
10544        // independently tested maintenance services a fresh cadence receipt.
10545        let stamps = home.join("service-ticks");
10546        std::fs::create_dir_all(&stamps).unwrap();
10547        for service in ["waiter", "deputies", "release-watch"] {
10548            std::fs::write(
10549                stamps.join(service),
10550                Timestamp::now().as_second().to_string(),
10551            )
10552            .unwrap();
10553        }
10554        for operation in [
10555            "conductor",
10556            "maintenance",
10557            "housekeeping",
10558            "disk-pressure",
10559            "cache",
10560            "fetch",
10561        ] {
10562            std::fs::write(
10563                stamps.join(format!("daemon-{operation}")),
10564                serde_json::to_vec(&Timestamp::now()).unwrap(),
10565            )
10566            .unwrap();
10567        }
10568        let worktrees = dir.join("wt");
10569        (
10570            opts,
10571            Queue::at(dir.join("queue")),
10572            home.join("daemon.json"),
10573            home,
10574            worktrees,
10575        )
10576    }
10577
10578    #[tokio::test]
10579    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
10580        let dir = tempfile::tempdir().unwrap();
10581        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10582        let cfg = Config::default();
10583        start_service(
10584            &home,
10585            &opts,
10586            &queue,
10587            &worktrees,
10588            "housekeeping",
10589            Some(&cfg),
10590            true,
10591        )
10592        .await
10593        .unwrap();
10594        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
10595        let read = |path: &Path| -> serde_json::Value {
10596            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
10597        };
10598        assert_eq!(read(&receipt)["detail"], "cadence not due");
10599        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
10600        start_service(
10601            &home,
10602            &opts,
10603            &queue,
10604            &worktrees,
10605            "housekeeping",
10606            Some(&cfg),
10607            true,
10608        )
10609        .await
10610        .unwrap();
10611        assert_eq!(
10612            read(&receipt)["detail"],
10613            "active work or runnable task queue"
10614        );
10615        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
10616        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
10617        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
10618        start_service(
10619            &home,
10620            &opts,
10621            &queue,
10622            &worktrees,
10623            "disk-pressure",
10624            Some(&cfg),
10625            false,
10626        )
10627        .await
10628        .unwrap();
10629        assert_eq!(
10630            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
10631            "no active work; idle housekeeping owns scan"
10632        );
10633        assert!(crate::worker::active(&home).unwrap().is_empty());
10634    }
10635
10636    #[test]
10637    fn a_stop_is_idempotent_and_once_set_stays_set() {
10638        let stop = Stop::new();
10639        assert!(!stop.stopped());
10640
10641        stop.stop();
10642        assert!(stop.stopped());
10643        stop.stop();
10644        assert!(stop.stopped(), "a second stop is not a toggle");
10645
10646        let shared = stop.clone();
10647        assert!(
10648            shared.stopped(),
10649            "a clone is the same stop; that is how the loop and its caller share one"
10650        );
10651    }
10652
10653    #[tokio::test]
10654    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10655        for operation in ["conductor", "maintenance", "housekeeping"] {
10656            let dir = tempfile::tempdir().unwrap();
10657            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10658            opts.once = true;
10659            opts.poll = Duration::from_millis(1);
10660            let mut task = task();
10661            task.runs.push("fixture-run".into());
10662            queue.put(&mut task).unwrap();
10663            let claim = queue.claim(&task.id).unwrap();
10664
10665            // Model a live service holding the task's claim across the
10666            // scheduler's dispatch scan. No real subprocess or timed race.
10667            let directory = home.join("workers/jobs/abcdef");
10668            std::fs::create_dir_all(&directory).unwrap();
10669            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10670            crate::pr_head::try_lock_file(&lease).unwrap();
10671            let mut job = crate::worker::Job {
10672                id: "abcdef".into(),
10673                sequence: 1,
10674                kind: "daemon-service".into(),
10675                key: format!("service:daemon-{operation}"),
10676                payload: serde_json::Value::Null,
10677                generation: "fixture".into(),
10678                version: None,
10679                status: crate::worker::Status::Running,
10680                result: None,
10681                pid: Some(std::process::id()),
10682                created_at: Timestamp::now().as_second() as u64,
10683                finished_at: None,
10684            };
10685            let record = directory.join("job.json");
10686            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10687
10688            let status = Arc::new(Mutex::new(Status::new()));
10689            let stop = Stop::new();
10690            let mut drain = Box::pin(poll(
10691                &opts,
10692                &queue,
10693                &status,
10694                &home,
10695                &worktrees,
10696                &stop,
10697                DispatchLimits {
10698                    max_concurrent: 1,
10699                    pause_for_interrupts: false,
10700                    recovery_cfg: None,
10701                },
10702            ));
10703            std::future::poll_fn(|cx| {
10704                use std::future::Future;
10705                assert!(
10706                    drain.as_mut().poll(cx).is_pending(),
10707                    "--once must wait for {operation} to release its queue claim"
10708                );
10709                std::task::Poll::Ready(())
10710            })
10711            .await;
10712            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10713
10714            // An answer arrives while the service still owns the claim. A
10715            // fresh scheduling pass must apply it before declaring idle.
10716            let questions = Questions::at(home.join("questions"));
10717            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10718            questions.put(&mut q).unwrap();
10719            drop(claim);
10720            // Model services that took longer than their cadence, without a
10721            // wall-clock sleep. The final scans must not respawn them even
10722            // though their receipts now permit another periodic invocation.
10723            let expired =
10724                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10725            for service in [operation, "housekeeping"] {
10726                std::fs::write(
10727                    home.join("service-ticks").join(format!("daemon-{service}")),
10728                    &expired,
10729                )
10730                .unwrap();
10731            }
10732            job.status = crate::worker::Status::Finished;
10733            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10734            drop(lease);
10735            tokio::time::timeout(Duration::from_secs(2), drain)
10736                .await
10737                .expect("the settled service must allow the drain to finish")
10738                .unwrap();
10739            let after = queue.get(&task.id).unwrap();
10740            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10741            assert!(after.action_applied(&q.id));
10742            for service in [operation, "housekeeping"] {
10743                assert_eq!(
10744                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10745                        .unwrap(),
10746                    expired,
10747                    "the final once rescan must not restart {service}"
10748                );
10749            }
10750        }
10751    }
10752
10753    #[test]
10754    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10755        let stop = Stop::new();
10756        stop.busy.store(1, Ordering::SeqCst);
10757        assert!(
10758            !stop.finishing(),
10759            "a busy loop nobody has asked to stop is just running"
10760        );
10761
10762        stop.stop();
10763        assert!(
10764            stop.finishing(),
10765            "a stop asked for mid-run has not landed until the run is settled"
10766        );
10767
10768        stop.busy.store(0, Ordering::SeqCst);
10769        assert!(
10770            !stop.finishing(),
10771            "once the run is settled the stop has landed and there is nothing to finish"
10772        );
10773    }
10774
10775    #[test]
10776    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10777        let stop = Stop::new();
10778        stop.busy.store(2, Ordering::SeqCst);
10779        stop.stop();
10780        assert!(stop.finishing(), "two runs still in flight");
10781
10782        stop.busy.store(1, Ordering::SeqCst);
10783        assert!(
10784            stop.finishing(),
10785            "one run finished, but a sibling is still working"
10786        );
10787
10788        stop.busy.store(0, Ordering::SeqCst);
10789        assert!(
10790            !stop.finishing(),
10791            "the last run out is what actually lands the stop"
10792        );
10793    }
10794
10795    #[tokio::test]
10796    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10797        let dir = tempfile::tempdir().unwrap();
10798        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10799        let stop = Stop::new();
10800        stop.stop();
10801
10802        let began = std::time::Instant::now();
10803        tokio::time::timeout(
10804            Duration::from_secs(2),
10805            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10806        )
10807        .await
10808        .expect("a stopped loop must return, not sit out its poll interval")
10809        .expect("the loop's own setup and teardown must not fail");
10810        assert!(
10811            began.elapsed() < opts.poll,
10812            "returned only after {:?}, which is a poll interval, not a stop",
10813            began.elapsed()
10814        );
10815    }
10816
10817    #[tokio::test]
10818    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10819        let dir = tempfile::tempdir().unwrap();
10820        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10821        let stop = Stop::new();
10822
10823        // Asked for after the loop is already parked on its empty queue, which
10824        // is the case an operator tapping stop on a phone actually hits.
10825        let asker = {
10826            let stop = stop.clone();
10827            tokio::spawn(async move {
10828                tokio::time::sleep(Duration::from_millis(20)).await;
10829                stop.stop();
10830            })
10831        };
10832
10833        let began = std::time::Instant::now();
10834        tokio::time::timeout(
10835            Duration::from_secs(2),
10836            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10837        )
10838        .await
10839        .expect("a stop asked for while idle must wake the wait")
10840        .expect("the loop's own setup and teardown must not fail");
10841        asker.await.unwrap();
10842        assert!(
10843            began.elapsed() < opts.poll,
10844            "returned only after {:?}, so the stop waited on the sleep",
10845            began.elapsed()
10846        );
10847    }
10848
10849    #[tokio::test]
10850    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10851        let dir = tempfile::tempdir().unwrap();
10852        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10853        let stop = Stop::new();
10854        stop.stop();
10855
10856        tokio::time::timeout(
10857            Duration::from_secs(2),
10858            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10859        )
10860        .await
10861        .expect("a stopped loop must return")
10862        .expect("the loop's own setup and teardown must not fail");
10863
10864        assert!(
10865            home.is_dir(),
10866            "the loop did publish a status file, so its removal is the teardown and not an absence"
10867        );
10868        assert!(
10869            !status_file.exists(),
10870            "a stopped loop clears its status file"
10871        );
10872        assert!(
10873            read_status(&home).is_none(),
10874            "a reader must see no daemon at all, not a heartbeat that merely stopped"
10875        );
10876    }
10877
10878    #[tokio::test]
10879    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10880        let dir = tempfile::tempdir().unwrap();
10881        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10882
10883        let mut settled = RunState::new(
10884            dir.path().join("repo"),
10885            "main".to_owned(),
10886            "abc1234".to_owned(),
10887            "fixture".to_owned(),
10888            Config::default(),
10889        );
10890        settled.status = RunStatus::Ready;
10891        let run_dir = home.join("runs").join(&settled.id);
10892        std::fs::create_dir_all(&run_dir).unwrap();
10893        std::fs::write(
10894            run_dir.join("run.json"),
10895            serde_json::to_string_pretty(&settled).unwrap(),
10896        )
10897        .unwrap();
10898        let questions = Questions::at(home.join("questions"));
10899        let mut question = ask::Question::new(
10900            settled.id.clone(),
10901            "review".to_owned(),
10902            "reviewer-1".to_owned(),
10903            "Continue?".to_owned(),
10904            String::new(),
10905            Vec::new(),
10906        );
10907        questions.put(&mut question).unwrap();
10908
10909        run_service_worker(
10910            &home,
10911            serde_json::to_value(ServiceWorker {
10912                opts,
10913                queue: queue.root().to_path_buf(),
10914                worktrees_root: worktrees,
10915                operation: "housekeeping".to_owned(),
10916            })
10917            .unwrap(),
10918        )
10919        .await
10920        .unwrap();
10921
10922        assert_eq!(
10923            questions.get(&question.id).unwrap().status,
10924            ask::QuestionStatus::Abandoned,
10925            "the independent housekeeping worker settles ended-run questions"
10926        );
10927    }
10928
10929    #[test]
10930    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10931        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10932
10933        assert!(
10934            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10935            "never checked before: due at once"
10936        );
10937
10938        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10939        assert!(
10940            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10941            "well inside the interval: not due yet"
10942        );
10943
10944        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10945        assert!(
10946            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10947            "exactly at the edge: not yet due, same convention as `clean::due`"
10948        );
10949
10950        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10951        assert!(
10952            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10953            "past the interval: due again"
10954        );
10955    }
10956
10957    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
10958    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
10959    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
10960    /// and the congestion test below both need, and must not drift apart.
10961    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10962        let config = dir.join("magi.toml");
10963        // A literal (single-quoted) TOML string, not a basic one: the cache
10964        // path is a Windows path full of backslashes, and a basic string
10965        // would have TOML try to interpret `\U` (from `\Users\...`) as a
10966        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
10967        // `{{ vars.cache }}` rendering documents.
10968        std::fs::write(
10969            &config,
10970            format!(
10971                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10972                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10973                cache_dir.display()
10974            ),
10975        )
10976        .unwrap();
10977        Opts {
10978            config: Some(config),
10979            repo: dir.join("repo"),
10980            ..Opts::default()
10981        }
10982    }
10983
10984    #[tokio::test]
10985    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10986        let dir = tempfile::tempdir().unwrap();
10987        let home = dir.path().join("home");
10988        let cache_dir = dir.path().join("cache");
10989        std::fs::create_dir_all(&cache_dir).unwrap();
10990        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10991        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10992
10993        // Nobody has asked this daemon to stop, which is the ordinary case;
10994        // the skip that a stop buys is asserted by its own test below.
10995        let running = Stop::new();
10996        let mut last_checked = None;
10997        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10998        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10999            .await;
11000        assert_eq!(
11001            crate::disk::dir_size(&cache_dir),
11002            0,
11003            "over the cap on the first check ever: pruned at once, no idle queue required"
11004        );
11005        assert_eq!(last_checked, Some(t0));
11006
11007        // A fresh oversized file lands, but the next check is not due yet.
11008        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
11009        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
11010        maybe_prune_cache_between_runs(
11011            &opts.repo,
11012            &opts,
11013            &home,
11014            &running,
11015            &mut last_checked,
11016            too_soon,
11017        )
11018        .await;
11019        assert_eq!(
11020            crate::disk::dir_size(&cache_dir),
11021            10,
11022            "too soon since the last check: left alone rather than rescanned every call"
11023        );
11024        assert_eq!(
11025            last_checked,
11026            Some(t0),
11027            "an idle check does not reset the clock"
11028        );
11029
11030        // Once the interval elapses, the same oversized cache is caught again.
11031        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11032        maybe_prune_cache_between_runs(
11033            &opts.repo,
11034            &opts,
11035            &home,
11036            &running,
11037            &mut last_checked,
11038            due_again,
11039        )
11040        .await;
11041        assert_eq!(
11042            crate::disk::dir_size(&cache_dir),
11043            0,
11044            "due again: pruned back under the cap"
11045        );
11046    }
11047
11048    /// A stop must not queue behind housekeeping. The prune below is a
11049    /// synchronous walk of the whole cache with no await point in it, so a
11050    /// loop that entered it could not get back to its own `stopped()` test
11051    /// until the walk finished - and because no run is in flight at this
11052    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
11053    /// the stop had already landed. The idle branch has always made this same
11054    /// check before reaching `janitor`; the between-runs path makes it too.
11055    #[tokio::test]
11056    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
11057        let dir = tempfile::tempdir().unwrap();
11058        let home = dir.path().join("home");
11059        let cache_dir = dir.path().join("cache");
11060        std::fs::create_dir_all(&cache_dir).unwrap();
11061        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11062        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11063
11064        let stop = Stop::new();
11065        stop.stop();
11066        assert!(
11067            !stop.finishing(),
11068            "no run is in flight at a between-runs boundary, so nothing else \
11069             would tell the operator this stop had not taken effect yet"
11070        );
11071
11072        let mut last_checked = None;
11073        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11074        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
11075            .await;
11076        assert_eq!(
11077            crate::disk::dir_size(&cache_dir),
11078            10,
11079            "over its cap, and due for the first check ever, but a stop outranks \
11080             it: the cap is a standing policy the next start measures again"
11081        );
11082        assert_eq!(
11083            last_checked, None,
11084            "a check that never happened must not claim the interval"
11085        );
11086    }
11087
11088    /// A backlog must not starve cache pruning. The finite cache worker runs
11089    /// independently of queue drain and must not consume any task attempts.
11090    #[tokio::test]
11091    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
11092        let dir = tempfile::tempdir().unwrap();
11093        let cache_dir = dir.path().join("cache");
11094        std::fs::create_dir_all(&cache_dir).unwrap();
11095        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
11096
11097        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
11098        opts.poll = Duration::from_millis(20);
11099        opts.max_attempts = 1_000;
11100
11101        let queue = Queue::at(dir.path().join("queue"));
11102        for i in 0..128 {
11103            let mut task = Task::new(
11104                format!("queued work {i}"),
11105                format!("queued work {i}"),
11106                opts.repo.clone(),
11107                Source::Human,
11108            );
11109            queue.put(&mut task).unwrap();
11110        }
11111
11112        let home = dir.path().join("home");
11113        let worktrees = dir.path().join("wt");
11114        run_service_worker(
11115            &home,
11116            serde_json::to_value(ServiceWorker {
11117                opts,
11118                queue: queue.root().to_path_buf(),
11119                worktrees_root: worktrees,
11120                operation: "cache".to_owned(),
11121            })
11122            .unwrap(),
11123        )
11124        .await
11125        .unwrap();
11126        let after = queue.list();
11127        assert_eq!(after.len(), 128);
11128        assert!(
11129            after
11130                .iter()
11131                .all(|task| task.status.runnable() && task.attempts == 0)
11132        );
11133
11134        assert_eq!(
11135            crate::disk::dir_size(&cache_dir),
11136            0,
11137            "an oversized cache must not be left to grow unboundedly just because the \
11138             queue kept the loop busy the whole time"
11139        );
11140    }
11141
11142    #[test]
11143    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
11144        let dir = tempfile::tempdir().unwrap();
11145        let queue = Queue::at(dir.path().join("queue"));
11146        let questions = Questions::at(dir.path().join("questions"));
11147        let mut task = task();
11148        queue.put(&mut task).unwrap();
11149
11150        let mut task_question = ask::Question::new(
11151            task.id.clone(),
11152            crate::conduct::NODE.to_owned(),
11153            "conduct".to_owned(),
11154            "Which backend?".to_owned(),
11155            String::new(),
11156            Vec::new(),
11157        );
11158        questions.put(&mut task_question).unwrap();
11159        task.block(vec![task_question.id.clone()], None);
11160        queue.put(&mut task).unwrap();
11161
11162        let mut run_question = ask::Question::new(
11163            "20260101-000000-run1".to_owned(),
11164            "review".to_owned(),
11165            "reviewer-1".to_owned(),
11166            "Run question".to_owned(),
11167            String::new(),
11168            Vec::new(),
11169        );
11170        questions.put(&mut run_question).unwrap();
11171
11172        // A question from another node whose `run` happens to equal this
11173        // task's id — the same field, filled in for an unrelated reason. Only
11174        // `crate::conduct::NODE` questions use `run` as a task id; this one
11175        // must never be touched by this reconciliation, even after release.
11176        let mut coincidental = ask::Question::new(
11177            task.id.clone(),
11178            "review".to_owned(),
11179            "reviewer-1".to_owned(),
11180            "Unrelated review question".to_owned(),
11181            String::new(),
11182            Vec::new(),
11183        );
11184        questions.put(&mut coincidental).unwrap();
11185
11186        reconcile_task_questions(&queue, &questions);
11187        assert!(questions.get(&task_question.id).unwrap().status.open());
11188        assert!(questions.get(&run_question.id).unwrap().status.open());
11189        assert!(questions.get(&coincidental.id).unwrap().status.open());
11190
11191        task.release();
11192        queue.put(&mut task).unwrap();
11193        reconcile_task_questions(&queue, &questions);
11194        assert_eq!(
11195            questions.get(&task_question.id).unwrap().status,
11196            ask::QuestionStatus::Abandoned
11197        );
11198        assert!(
11199            questions.get(&run_question.id).unwrap().status.open(),
11200            "run questions remain the run janitor's responsibility"
11201        );
11202        assert!(
11203            questions.get(&coincidental.id).unwrap().status.open(),
11204            "a non-conductor question must not be abandoned just because its \
11205             run id coincides with a task id"
11206        );
11207    }
11208
11209    #[test]
11210    fn a_freshly_started_running_task_is_never_stalled() {
11211        let dir = tempfile::tempdir().unwrap();
11212        let mut t = task();
11213        t.start("run-1".to_owned());
11214        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
11215        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
11216        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
11217    }
11218
11219    #[test]
11220    fn a_long_running_task_with_no_live_daemon_is_stalled() {
11221        let dir = tempfile::tempdir().unwrap();
11222        let mut t = task();
11223        t.start("run-1".to_owned());
11224        t.updated_at = Timestamp::now()
11225            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
11226        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
11227        assert_eq!(
11228            stalled_tasks(
11229                &Queue::at(dir.path().join("q")),
11230                dir.path(),
11231                Timestamp::now()
11232            )
11233            .len(),
11234            0,
11235            "the task was never written to this queue"
11236        );
11237    }
11238
11239    #[test]
11240    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
11241        let dir = tempfile::tempdir().unwrap();
11242        let mut t = task();
11243        t.id = "20260903-080340-0167".to_owned();
11244        t.start("20260903-080619-01c2".to_owned());
11245        t.updated_at = Timestamp::now()
11246            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
11247
11248        let mut status = Status::new();
11249        status.current = vec![Current {
11250            worker: None,
11251            task: t.id.clone(),
11252            run: "20260903-080619-01c2".to_owned(),
11253        }];
11254        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11255
11256        assert!(
11257            !is_stalled(&t, dir.path(), Timestamp::now()),
11258            "a live daemon's own heartbeat rules out stalled, however long the task has run"
11259        );
11260    }
11261
11262    /// Rewrite a task's `updated_at` on disk directly, bypassing
11263    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
11264    /// a fixture look like it has genuinely been `running` for a while.
11265    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
11266        let path = queue.path_of(id);
11267        let body = std::fs::read_to_string(&path).unwrap();
11268        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
11269        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
11270        v["updated_at"] = serde_json::Value::String(old.to_string());
11271        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
11272    }
11273
11274    #[test]
11275    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
11276        // The realistic `poll()` ordering, not `is_stalled` in isolation:
11277        // `reclaim_orphaned_running` runs first, on every poll, and settles
11278        // any `running` task whose claim it can actually take. For most
11279        // crashes that is immediate - a dead pid is proof enough for
11280        // `sweep_stale_claims` to drop the lock the same tick, and the very
11281        // next claim attempt succeeds. But a lock whose pid cannot be parsed
11282        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
11283        // `sweep_stale_claims`'s own doc), so the lock - and the claim
11284        // failure behind it - can legitimately outlive many polls. This is
11285        // exactly the gap `stalled_tasks` exists to surface well before that
11286        // six-hour sweep would: reclaim leaves the task `running`, and it
11287        // must still reach the conductor as stalled.
11288        let dir = tempfile::tempdir().unwrap();
11289        let queue = Queue::at(dir.path().join("queue"));
11290        let home = dir.path().join("home");
11291
11292        let mut t = task();
11293        t.id = "20260101-000001-lock".to_owned();
11294        t.start("run-1".to_owned());
11295        queue.put(&mut t).unwrap();
11296        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
11297        std::fs::write(
11298            dir.path().join("queue").join(format!("{}.lock", t.id)),
11299            "not a pid",
11300        )
11301        .unwrap();
11302
11303        let now = Timestamp::now();
11304        assert!(
11305            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
11306            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
11307             and reclaim must leave the task alone"
11308        );
11309        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
11310
11311        let stalled = stalled_tasks(&queue, &home, now);
11312        assert_eq!(
11313            stalled.len(),
11314            1,
11315            "reclaim's inability to claim it yet must not hide it from the conductor"
11316        );
11317        assert_eq!(stalled[0].id, t.id);
11318    }
11319
11320    #[test]
11321    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
11322        let dir = tempfile::tempdir().unwrap();
11323        crate::run::set_home(dir.path().join("run-home"));
11324        let queue = Queue::at(dir.path().join("queue"));
11325        let home = dir.path().join("home");
11326        let questions = Questions::at(dir.path().join("questions"));
11327
11328        let mut t = task();
11329        t.id = "20260101-000003-dead".to_owned();
11330        t.start("missing-run".to_owned());
11331        queue.put(&mut t).unwrap();
11332        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
11333
11334        // This is the real poll ordering: retain the deterministic stalled
11335        // input before a claim proves the owner is gone and reclaims it.
11336        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11337        assert_eq!(
11338            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
11339            [&t.id]
11340        );
11341        assert_eq!(
11342            reclaim_orphaned_running(&queue, 2, &Default::default()),
11343            [t.id.clone()]
11344        );
11345        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11346
11347        // Reclaim drops its guard before conductor decisions are applied, so
11348        // the decision for the captured stalled input has a real write path.
11349        crate::conduct::apply(
11350            &queue,
11351            &questions,
11352            &crate::conduct::Verdict {
11353                decisions: vec![crate::conduct::Decision {
11354                    id: t.id.clone(),
11355                    recovery: Some(crate::conduct::Recovery::Requeue),
11356                    ..crate::conduct::Decision::default()
11357                }],
11358            },
11359        )
11360        .unwrap();
11361        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11362    }
11363
11364    #[test]
11365    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
11366        let dir = tempfile::tempdir().unwrap();
11367        let queue = Queue::at(dir.path().join("queue"));
11368        let home = dir.path().join("home");
11369
11370        let mut fresh = task();
11371        fresh.id = "20260101-000001-aaaa".to_owned();
11372        fresh.start("run-1".to_owned());
11373        queue.put(&mut fresh).unwrap();
11374
11375        let mut old = task();
11376        old.id = "20260101-000002-bbbb".to_owned();
11377        old.start("run-2".to_owned());
11378        queue.put(&mut old).unwrap();
11379        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
11380
11381        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11382        assert_eq!(stalled.len(), 1);
11383        assert_eq!(stalled[0].id, old.id);
11384    }
11385
11386    #[test]
11387    fn queued_and_finished_task_views_partition_by_status() {
11388        let dir = tempfile::tempdir().unwrap();
11389        let queue = Queue::at(dir.path().join("queue"));
11390
11391        let mut queued = task();
11392        queued.id = "20260101-000001-aaaa".to_owned();
11393        queue.put(&mut queued).unwrap();
11394
11395        let mut failed = task();
11396        failed.id = "20260101-000002-bbbb".to_owned();
11397        failed.start("run-1".to_owned());
11398        failed.fail("gate red", 5);
11399        queue.put(&mut failed).unwrap();
11400
11401        let mut held = task();
11402        held.id = "20260101-000003-cccc".to_owned();
11403        held.hold_machine(None);
11404        queue.put(&mut held).unwrap();
11405
11406        let mut running = task();
11407        running.id = "20260101-000004-dddd".to_owned();
11408        running.start("run-2".to_owned());
11409        queue.put(&mut running).unwrap();
11410
11411        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
11412        assert_eq!(queued_ids, [queued.id.clone()]);
11413
11414        let mut finished_ids: Vec<String> =
11415            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
11416        finished_ids.sort_unstable();
11417        let mut want = vec![failed.id.clone(), held.id.clone()];
11418        want.sort_unstable();
11419        assert_eq!(finished_ids, want);
11420    }
11421
11422    #[test]
11423    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
11424        for short in [false, true] {
11425            let dir = tempfile::tempdir().unwrap();
11426            let queue = Queue::at(dir.path().join("queue"));
11427            let questions = ask::Questions::at(dir.path().join("questions"));
11428            let mut running = task();
11429            running.id = "20261013-192213-feb2".into();
11430            running.start("existing-run".into());
11431            queue.put(&mut running).unwrap();
11432            let mut middle = task();
11433            middle.id = "20261013-193611-ca5b".into();
11434            middle.block(
11435                vec![if short {
11436                    "feb2".into()
11437                } else {
11438                    running.id.clone()
11439                }],
11440                None,
11441            );
11442            queue.put(&mut middle).unwrap();
11443            let mut waiting = task();
11444            waiting.id = "20261013-202849-ee37".into();
11445            waiting.block(
11446                vec![if short {
11447                    "ca5b".into()
11448                } else {
11449                    middle.id.clone()
11450                }],
11451                Some("wait for implementation".into()),
11452            );
11453            queue.put(&mut waiting).unwrap();
11454            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
11455            let inv = crate::blockers::Inventory::load(&queue, &questions);
11456            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
11457            assert!(inv.stuck().is_empty());
11458            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11459            assert!(report.quarantined.is_empty());
11460            assert!(report.asked.is_empty());
11461            resolve_blockers(&queue, &questions);
11462            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11463            assert!(questions.list().is_empty());
11464            // Finishing the transitive prerequisite alone does not satisfy
11465            // the task's direct dependency.
11466            running.succeed();
11467            queue.put(&mut running).unwrap();
11468            resolve_blockers(&queue, &questions);
11469            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
11470            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11471            middle = queue.get(&middle.id).unwrap();
11472            middle.succeed();
11473            queue.put(&mut middle).unwrap();
11474            resolve_blockers(&queue, &questions);
11475            let after = queue.get(&waiting.id).unwrap();
11476            assert_eq!(after.status, TaskStatus::Queued);
11477            assert!(after.blocked_by.is_empty());
11478            assert_eq!(after.instruction, waiting.instruction);
11479        }
11480    }
11481
11482    #[test]
11483    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
11484        for future_schema in [false, true] {
11485            let name = "20261013-193611-ca5b";
11486            let mut future = task();
11487            future.id = name.into();
11488            future.schema = crate::queue::SCHEMA + 1;
11489            let contents = if future_schema {
11490                serde_json::to_string(&future).unwrap()
11491            } else {
11492                "corrupt".into()
11493            };
11494            let dir = tempfile::tempdir().unwrap();
11495            let queue = Queue::at(dir.path().join("queue"));
11496            let questions = ask::Questions::at(dir.path().join("questions"));
11497            let mut waiting = task();
11498            waiting.id = "20261013-202849-ee37".into();
11499            waiting.block(vec!["ca5b".into()], None);
11500            queue.put(&mut waiting).unwrap();
11501            std::fs::write(queue.path_of(name), contents).unwrap();
11502            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
11503            assert!(
11504                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
11505            );
11506            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11507            assert!(report.asked.is_empty());
11508            resolve_blockers(&queue, &questions);
11509            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11510            assert!(questions.list().is_empty());
11511        }
11512        let dir = tempfile::tempdir().unwrap();
11513        let queue = Queue::at(dir.path().join("queue"));
11514        let questions = ask::Questions::at(dir.path().join("questions"));
11515        let mut waiting = task();
11516        waiting.id = "20261013-202849-ee37".into();
11517        waiting.block(vec!["ca5b".into()], None);
11518        queue.put(&mut waiting).unwrap();
11519        let mut done = task();
11520        done.id = "20261013-193611-ca5b".into();
11521        done.succeed();
11522        queue.put(&mut done).unwrap();
11523        // An unreadable second match must not disappear from uniqueness
11524        // checks just because Queue::list skips it.
11525        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
11526        assert!(queue.get("ca5b").is_err());
11527        assert_eq!(
11528            crate::queue::dependency(&queue, &questions, "ca5b"),
11529            crate::queue::Dependency::Ambiguous
11530        );
11531        resolve_blockers(&queue, &questions);
11532        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11533        assert!(report.asked.is_empty());
11534        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11535        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
11536    }
11537
11538    #[test]
11539    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
11540        for held in [false, true] {
11541            for question in [false, true] {
11542                for reference in ["ca5b", "20261013-193611-ca5b"] {
11543                    let dir = tempfile::tempdir().unwrap();
11544                    let queue = Queue::at(dir.path().join("queue"));
11545                    let questions = ask::Questions::at(dir.path().join("questions"));
11546                    let mut prerequisite = task();
11547                    prerequisite.id = "20261013-193611-ca5b".into();
11548                    prerequisite.start("existing-run".into());
11549                    queue.put(&mut prerequisite).unwrap();
11550                    let mut waiting = task();
11551                    waiting.id = "20261013-202849-ee37".into();
11552                    if held {
11553                        waiting.hold_machine(Some("waiting for separate consent".into()));
11554                    }
11555                    queue.put(&mut waiting).unwrap();
11556                    let reason = "Deleting saved data requires separate owner consent";
11557                    crate::conduct::apply(
11558                        &queue,
11559                        &questions,
11560                        &crate::conduct::Verdict {
11561                            decisions: vec![crate::conduct::Decision {
11562                                id: waiting.id.clone(),
11563                                blocked_by: vec![reference.into()],
11564                                question: question.then(|| "May the saved data be deleted?".into()),
11565                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11566                                reason: Some(reason.into()),
11567                                ..crate::conduct::Decision::default()
11568                            }],
11569                        },
11570                    )
11571                    .unwrap();
11572                    let before = queue.get(&waiting.id).unwrap();
11573                    if question {
11574                        assert_eq!(before.status, TaskStatus::Blocked);
11575                        let q = questions.get(&before.blocked_by[0]).unwrap();
11576                        assert_eq!(q.summary, "May the saved data be deleted?");
11577                        assert!(q.status.open());
11578                    } else {
11579                        assert_eq!(before.status, TaskStatus::Held);
11580                        let recorded_reason = before.hold_reason.as_deref().unwrap();
11581                        assert!(recorded_reason.starts_with(reason));
11582                        if held {
11583                            assert!(recorded_reason.contains("waiting for separate consent"));
11584                        }
11585                    }
11586                    prerequisite.succeed();
11587                    queue.put(&mut prerequisite).unwrap();
11588                    resolve_blockers(&queue, &questions);
11589                    let after = queue.get(&waiting.id).unwrap();
11590                    assert_eq!(after.status, before.status);
11591                    assert_eq!(after.blocked_by, before.blocked_by);
11592                    assert_eq!(after.hold_reason, before.hold_reason);
11593                    assert_eq!(after.instruction, waiting.instruction);
11594                    if question {
11595                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11596                    }
11597                    assert!(
11598                        queue.next_runnable().is_none(),
11599                        "dependency completion is not consent"
11600                    );
11601                }
11602            }
11603        }
11604    }
11605
11606    #[test]
11607    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11608        let dir = tempfile::tempdir().unwrap();
11609        let queue = Queue::at(dir.path().join("queue"));
11610        let questions = ask::Questions::at(dir.path().join("questions"));
11611
11612        let mut dep = task();
11613        dep.id = "20260101-000001-dep0".to_owned();
11614        dep.succeed();
11615        queue.put(&mut dep).unwrap();
11616
11617        let mut still_going = task();
11618        still_going.id = "20260101-000002-dep1".to_owned();
11619        queue.put(&mut still_going).unwrap();
11620
11621        let mut blocked = task();
11622        blocked.id = "20260101-000003-main".to_owned();
11623        blocked.block(
11624            vec![dep.id.clone(), still_going.id.clone()],
11625            Some("waits on both".to_owned()),
11626        );
11627        queue.put(&mut blocked).unwrap();
11628
11629        resolve_blockers(&queue, &questions);
11630
11631        let after = queue.get(&blocked.id).unwrap();
11632        assert_eq!(
11633            after.status,
11634            TaskStatus::Blocked,
11635            "one dependency is still outstanding"
11636        );
11637        assert_eq!(after.blocked_by, [still_going.id.clone()]);
11638    }
11639
11640    #[test]
11641    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11642        let dir = tempfile::tempdir().unwrap();
11643        let queue = Queue::at(dir.path().join("queue"));
11644        let questions = ask::Questions::at(dir.path().join("questions"));
11645
11646        let mut q = crate::ask::Question::new(
11647            "20260101-000001-main".to_owned(),
11648            crate::conduct::NODE.to_owned(),
11649            "conduct".to_owned(),
11650            "Which backend?".to_owned(),
11651            String::new(),
11652            Vec::new(),
11653        );
11654        questions.put(&mut q).unwrap();
11655        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11656            .unwrap();
11657        questions.put(&mut q).unwrap();
11658
11659        let mut blocked = task();
11660        blocked.id = "20260101-000001-main".to_owned();
11661        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11662        queue.put(&mut blocked).unwrap();
11663
11664        resolve_blockers(&queue, &questions);
11665
11666        let after = queue.get(&blocked.id).unwrap();
11667        assert_eq!(
11668            after.status,
11669            TaskStatus::Queued,
11670            "the only blocker resolved"
11671        );
11672        assert_eq!(after.answers.len(), 1);
11673        assert_eq!(after.answers[0].question, "Which backend?");
11674        assert_eq!(after.answers[0].answer, "SQLite");
11675
11676        // And the run this task starts next is told about it.
11677        let instruction = instruction_for(&after);
11678        assert!(instruction.contains("Which backend?"));
11679        assert!(instruction.contains("SQLite"));
11680    }
11681
11682    #[test]
11683    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11684        let dir = tempfile::tempdir().unwrap();
11685        let queue = Queue::at(dir.path().join("queue"));
11686        let questions = ask::Questions::at(dir.path().join("questions"));
11687
11688        let mut q = crate::ask::Question::new(
11689            "20260101-000001-main".to_owned(),
11690            crate::conduct::NODE.to_owned(),
11691            "conduct".to_owned(),
11692            "Is the setup done?".to_owned(),
11693            String::new(),
11694            Vec::new(),
11695        );
11696        q.abandon("no answer within 60s of asking");
11697        questions.put(&mut q).unwrap();
11698
11699        let mut blocked = task();
11700        blocked.id = "20260101-000001-main".to_owned();
11701        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11702        queue.put(&mut blocked).unwrap();
11703
11704        resolve_blockers(&queue, &questions);
11705
11706        let after = queue.get(&blocked.id).unwrap();
11707        assert_eq!(
11708            after.status,
11709            TaskStatus::Held,
11710            "never left blocked on nothing"
11711        );
11712        assert!(!after.operator_held(), "a machine hold, for triage");
11713        assert!(
11714            after
11715                .hold_reason
11716                .as_deref()
11717                .unwrap_or_default()
11718                .contains("went unanswered")
11719        );
11720    }
11721
11722    #[test]
11723    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11724        // Reproduces the reported bug (task 3958): a task held out of
11725        // attempts, blocked on a `crate::conduct` follow-up question, must
11726        // come back `held` once that question is answered - never `queued`,
11727        // whatever the answer said - or it silently re-enters the
11728        // competition queue with its attempts already exhausted.
11729        let dir = tempfile::tempdir().unwrap();
11730        let queue = Queue::at(dir.path().join("queue"));
11731        let questions = ask::Questions::at(dir.path().join("questions"));
11732
11733        let mut q = crate::ask::Question::new(
11734            "20260101-000001-main".to_owned(),
11735            crate::conduct::NODE.to_owned(),
11736            "conduct".to_owned(),
11737            "How should this be handled?".to_owned(),
11738            String::new(),
11739            Vec::new(),
11740        );
11741        questions.put(&mut q).unwrap();
11742        q.answer(crate::ask::Answer::Text(
11743            "leave it held, a human will look at it later".to_owned(),
11744        ))
11745        .unwrap();
11746        questions.put(&mut q).unwrap();
11747
11748        let mut held = task();
11749        held.id = "20260101-000001-main".to_owned();
11750        held.hold_machine(Some("out of attempts".to_owned()));
11751        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11752        queue.put(&mut held).unwrap();
11753
11754        resolve_blockers(&queue, &questions);
11755
11756        let after = queue.get(&held.id).unwrap();
11757        assert_eq!(after.status, TaskStatus::Held);
11758        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11759        assert_eq!(
11760            after.answers[0].answer,
11761            "leave it held, a human will look at it later"
11762        );
11763    }
11764
11765    #[test]
11766    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11767        let dir = tempfile::tempdir().unwrap();
11768        let queue = Queue::at(dir.path().join("queue"));
11769        let questions = ask::Questions::at(dir.path().join("questions"));
11770        let mut dep = task();
11771        dep.id = "20260101-000001-gone".to_owned();
11772        queue.put(&mut dep).unwrap();
11773        let mut blocked = task();
11774        blocked.id = "20260101-000003-main".to_owned();
11775        blocked.block(vec![dep.id.clone()], None);
11776        queue.put(&mut blocked).unwrap();
11777
11778        // Claimed, so `remove` cannot rewrite it and the resolver must.
11779        let claim = queue.claim(&blocked.id).unwrap();
11780        queue.remove(&dep.id, false, &questions).unwrap();
11781        drop(claim);
11782        resolve_blockers(&queue, &questions);
11783
11784        let after = queue.get(&blocked.id).unwrap();
11785        assert_eq!(after.status, TaskStatus::Queued);
11786        assert!(after.blocked_by.is_empty());
11787    }
11788
11789    #[test]
11790    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11791        // Reproduces the reported bug: a task blocked on a task id that was
11792        // removed (`magi task rm`, or deleted by hand) can never see that id
11793        // reach `Done`, so the ordinary per-id loop has nothing to notice and
11794        // would otherwise leave the task `blocked` forever with no way for an
11795        // operator to find out why.
11796        let dir = tempfile::tempdir().unwrap();
11797        let queue = Queue::at(dir.path().join("queue"));
11798        let questions = ask::Questions::at(dir.path().join("questions"));
11799
11800        let mut still_going = task();
11801        still_going.id = "20260101-000002-dep1".to_owned();
11802        queue.put(&mut still_going).unwrap();
11803
11804        let mut blocked = task();
11805        blocked.id = "20260101-000003-main".to_owned();
11806        blocked.block(
11807            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11808            Some("waits on both".to_owned()),
11809        );
11810        queue.put(&mut blocked).unwrap();
11811
11812        resolve_blockers(&queue, &questions);
11813
11814        let after = queue.get(&blocked.id).unwrap();
11815        assert_eq!(
11816            after.status,
11817            TaskStatus::Held,
11818            "a missing dependency must not leave the task blocked forever"
11819        );
11820        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11821        assert!(after.blocked_by.is_empty());
11822        let reason = after.hold_reason.as_deref().unwrap_or_default();
11823        assert!(
11824            reason.contains("20260101-000001-gone"),
11825            "the missing id must be named so an operator can tell what happened: {reason}"
11826        );
11827        assert!(
11828            reason.contains(&still_going.id),
11829            "the still-valid dependency must not silently vanish from the record: {reason}"
11830        );
11831    }
11832
11833    #[test]
11834    fn instruction_for_is_unchanged_without_any_answers() {
11835        let t = task();
11836        assert_eq!(instruction_for(&t), t.instruction);
11837    }
11838
11839    #[test]
11840    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11841        let dir = tempfile::tempdir().unwrap();
11842        let q = Queue::at(dir.path().join("queue"));
11843        let src = dir.path().join("shot.png");
11844        std::fs::write(&src, "x").unwrap();
11845        let mut t = task();
11846        q.attach(&mut t, &[src]).unwrap();
11847        let paths = task_attachments(&q, &t).unwrap();
11848        assert_eq!(paths.len(), 1);
11849        assert!(paths[0].is_absolute() && paths[0].is_file());
11850        std::fs::remove_file(&paths[0]).unwrap();
11851        let err = task_attachments(&q, &t).unwrap_err().to_string();
11852        assert!(err.contains("shot.png"), "{err}");
11853    }
11854
11855    #[tokio::test]
11856    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11857        let dir = tempfile::tempdir().unwrap();
11858        let queue_path = dir.path().join("queue");
11859        let queue = Queue::at(queue_path.clone());
11860        let mut t = task();
11861        t.source = Source::Agent {
11862            run: "originating-chat".into(),
11863            node: crate::queue::CHAT_NODE.into(),
11864        };
11865        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11866            stage: "config-fetch",
11867            target: "origin/main".into(),
11868        });
11869        record_config_failure(&mut t, &fetch);
11870        t.hold_machine(Some(format!("{fetch:#}")));
11871        let fetch_key = t.chat_notice_due().unwrap();
11872        t.chat_notices.push(fetch_key.clone());
11873        queue.put(&mut t).unwrap();
11874
11875        let queue = Queue::at(queue_path);
11876        let mut t = queue.get(&t.id).unwrap();
11877        let a = dir.path().join("a.toml");
11878        let b = dir.path().join("b.toml");
11879        for (path, text, new_cause) in [
11880            (&a, "[graph", true),
11881            (&a, "[verify", false),
11882            (&a, "[graph]\nimplementers = 'invalid-type'", true),
11883            (&b, "[graph]\nimplementers = 'invalid-type'", true),
11884        ] {
11885            t.release_operator("test", None);
11886            std::fs::write(path, text).unwrap();
11887            let error = Config::discover_fetched(dir.path(), Some(path))
11888                .await
11889                .unwrap_err();
11890            record_config_failure(&mut t, &error);
11891            t.hold_machine(Some(format!("{error:#}")));
11892            let due = t.chat_notice_due();
11893            assert_eq!(due.is_some(), new_cause, "{error:#}");
11894            if let Some(key) = due {
11895                assert_ne!(key, fetch_key);
11896                t.chat_notices.push(key);
11897            }
11898        }
11899        t.succeed();
11900        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11901    }
11902
11903    #[test]
11904    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11905        let dir = tempfile::tempdir().unwrap();
11906        let queue_path = dir.path().join("queue");
11907        let queue = Queue::at(queue_path.clone());
11908        let mut t = task();
11909        t.source = crate::queue::Source::Agent {
11910            run: "originating-chat".into(),
11911            node: crate::queue::CHAT_NODE.into(),
11912        };
11913        let a = dir.path().join("a.png");
11914        let b = dir.path().join("b.png");
11915        std::fs::write(&a, "a").unwrap();
11916        std::fs::write(&b, "b").unwrap();
11917        queue.attach(&mut t, &[a, b]).unwrap();
11918        let paths = task_attachments(&queue, &t).unwrap();
11919        for path in &paths {
11920            std::fs::remove_file(path).unwrap();
11921        }
11922        let missing = task_attachments(&queue, &t).unwrap_err();
11923        t.attempts += 1;
11924        let reason = missing.to_string();
11925        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11926        let first = t.chat_notice_due().expect("first attachment notice");
11927        t.chat_notices.push(first.clone());
11928        queue.put(&mut t).unwrap();
11929
11930        let queue = Queue::at(queue_path.clone());
11931        let mut t = queue.get(&t.id).unwrap();
11932        assert!(t.chat_notice_due().is_none(), "restart does not replay");
11933        t.release_operator("test", None);
11934        t.attempts += 1;
11935        let missing = task_attachments(&queue, &t).unwrap_err();
11936        t.fail_startup_target(
11937            "startup-attachments",
11938            missing.name,
11939            "same missing attachment with regenerated wording",
11940            1,
11941        );
11942        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11943
11944        std::fs::write(&paths[0], "restored").unwrap();
11945        t.release_operator("test", None);
11946        t.attempts += 1;
11947        let missing = task_attachments(&queue, &t).unwrap_err();
11948        let reason = missing.to_string();
11949        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11950        let second = t
11951            .chat_notice_due()
11952            .expect("different attachment must notify");
11953        assert_ne!(first, second);
11954        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11955    }
11956
11957    #[test]
11958    fn resumed_instruction_is_unchanged_without_any_answers() {
11959        let t = task();
11960        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11961    }
11962
11963    #[test]
11964    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11965        let mut t = task();
11966        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11967        // The run's own instruction on disk predates the answer: it is the
11968        // plain original text `Runner::start` saved before the operator was
11969        // ever asked anything.
11970        let old = t.instruction.clone();
11971
11972        let refreshed = resumed_instruction(&old, &t);
11973        assert!(refreshed.starts_with(&old), "the original text is kept");
11974        assert!(refreshed.contains("Which backend?"));
11975        assert!(refreshed.contains("SQLite"));
11976    }
11977
11978    #[test]
11979    fn resumed_instruction_keeps_an_original_answers_heading() {
11980        let mut t = task();
11981        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11982        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11983
11984        let refreshed = resumed_instruction(&t.instruction, &t);
11985
11986        assert!(
11987            refreshed.starts_with(&t.instruction),
11988            "an answers heading in the original instruction is not the appended block"
11989        );
11990        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11991        assert!(refreshed.contains("Which backend?"));
11992        assert!(refreshed.contains("SQLite"));
11993
11994        let repeated = resumed_instruction(&refreshed, &t);
11995        assert_eq!(
11996            repeated, refreshed,
11997            "only the final appended block is refreshed"
11998        );
11999    }
12000
12001    #[test]
12002    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
12003        let mut t = task();
12004        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12005
12006        // A first resume appends the block; a second resume of the same run,
12007        // with no new answer in between, must reproduce exactly the same
12008        // text rather than appending the block a second time.
12009        let once = resumed_instruction(&t.instruction, &t);
12010        let twice = resumed_instruction(&once, &t);
12011        assert_eq!(once, twice);
12012        assert_eq!(once.matches("Which backend?").count(), 1);
12013
12014        // A later answer replaces the block wholesale rather than growing it.
12015        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
12016        let refreshed = resumed_instruction(&once, &t);
12017        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
12018        assert!(refreshed.contains("Which backend?"));
12019        assert!(refreshed.contains("Which cache?"));
12020    }
12021
12022    #[test]
12023    fn prepare_instruction_covers_all_three_starters() {
12024        let mut t = task();
12025        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12026
12027        // Start: a fresh run gets the task text plus every answer so far —
12028        // exactly `instruction_for`.
12029        assert_eq!(
12030            prepare_instruction(&Starter::Start, None, &t),
12031            Some(instruction_for(&t))
12032        );
12033
12034        // Resume: the run's prior instruction is refreshed with the answer,
12035        // not discarded and not left stale.
12036        let old = t.instruction.clone();
12037        assert_eq!(
12038            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
12039            Some(resumed_instruction(&old, &t))
12040        );
12041
12042        // Review: a review-only pass builds its own instruction from the
12043        // branch's history in `crate::graph`, with no task statement at all -
12044        // this boundary must leave it alone.
12045        assert_eq!(
12046            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
12047            None
12048        );
12049    }
12050
12051    #[test]
12052    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
12053        assert_eq!(
12054            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
12055            Starter::Review("magi/eba2/A".to_owned())
12056        );
12057    }
12058
12059    #[test]
12060    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
12061        assert_eq!(
12062            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
12063            Starter::Start,
12064            "a vanished review branch must not fall back to resuming the old run either"
12065        );
12066    }
12067
12068    #[test]
12069    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
12070        let mut t = task();
12071        t.start("old-run".to_owned());
12072        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
12073        t.release();
12074        let branch = t.review_branch.take();
12075        assert_eq!(
12076            choose_starter(branch.as_deref(), true, Some("old-run")),
12077            Starter::Review("magi/eba2/A".to_owned()),
12078            "a review wins over resuming the old run"
12079        );
12080    }
12081
12082    #[test]
12083    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
12084        assert_eq!(
12085            choose_starter(None, false, Some("some-run")),
12086            Starter::Resume("some-run".to_owned())
12087        );
12088        assert_eq!(choose_starter(None, false, None), Starter::Start);
12089    }
12090
12091    #[test]
12092    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
12093        let mut released = task();
12094        released.start("stalled-run".to_owned());
12095        released.requeue();
12096        let unfinished = (!released.fresh_start)
12097            .then(|| Some("stalled-run".to_owned()))
12098            .flatten();
12099        assert_eq!(
12100            choose_starter(None, false, unfinished.as_deref()),
12101            Starter::Start,
12102            "release keeps run history but must not resume it"
12103        );
12104        assert_eq!(released.runs, ["stalled-run"]);
12105    }
12106
12107    #[test]
12108    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
12109        let dir = tempfile::tempdir().unwrap();
12110        let queue = Queue::at(dir.path().join("queue"));
12111        let mut state = run_state(RunStatus::Blocked);
12112        state.merge_decision = Some(crate::merge_decision::Decision {
12113            question: "hold-inquiry".into(),
12114            target: crate::merge_decision::Target {
12115                pr: "https://example.test/pull/1".into(),
12116                head: "reviewed-head".into(),
12117                language: "en".into(),
12118            },
12119            choice: land::HOLD.into(),
12120            closed: false,
12121            replacement_run: None,
12122            replacement_pr: None,
12123        });
12124        let mut t = task();
12125        t.start(state.id.clone());
12126        settle_and_diagnose(
12127            &mut t,
12128            Verdict {
12129                status: RunStatus::Blocked,
12130                left_pr: true,
12131                quota_hit: false,
12132                parked: false,
12133                no_viable_candidates: false,
12134            },
12135            "held",
12136            2,
12137            &state,
12138        );
12139        queue.put(&mut t).unwrap();
12140        t.release_operator("chat", None);
12141        t.edit("revised".into(), "revised instruction".into())
12142            .unwrap();
12143        queue.put(&mut t).unwrap();
12144        drop(state);
12145        assert_eq!(
12146            queue
12147                .get(&t.id)
12148                .unwrap()
12149                .decision_effects
12150                .get("hold-inquiry"),
12151            Some(&format!("decision: {}", land::HOLD))
12152        );
12153    }
12154
12155    fn stopped_public_run(status: RunStatus) -> RunState {
12156        let mut state = run_state(status);
12157        state.driver_exited = true;
12158        state.config.graph.land = true;
12159        state.config.graph.review_rounds = 1;
12160        state.reviews = vec![review_round(1)];
12161        state.merge = Some(crate::run::MergeOutcome {
12162            mode: MergeMode::Pr,
12163            ok: false,
12164            detail: "landing stopped".into(),
12165            empty: false,
12166        });
12167        state.pr = Some(crate::run::PrRecord {
12168            url: "https://example.test/pull/1".into(),
12169            number: 1,
12170            state: "open".into(),
12171            checks: "red".into(),
12172            round: 1,
12173            rounds: 1,
12174            red_at_merge: Vec::new(),
12175        });
12176        state
12177    }
12178
12179    #[test]
12180    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
12181        for status in [RunStatus::Blocked, RunStatus::Gating] {
12182            let home = tempfile::tempdir().unwrap();
12183            let mut state = stopped_public_run(status);
12184            state.save_under(home.path()).unwrap();
12185            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
12186            assert!(!exhausted_review_budget(&state));
12187            let mut task = held_task_with(&state.id);
12188            task.release();
12189            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
12190            assert_eq!(
12191                choose_starter(None, false, unfinished.as_deref()),
12192                Starter::Resume(state.id.clone())
12193            );
12194            let question = action_question(&state.id, resume_action(&state.id));
12195            assert_eq!(
12196                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12197                    state.clone()
12198                )),
12199                ActionDecision::Resume(state.id.clone())
12200            );
12201            // The control-plane command uses this same preflight before pinning.
12202            assert_eq!(
12203                crate::resume::validate(home.path(), &state.id).unwrap().id,
12204                state.id
12205            );
12206            let queue = Queue::at(home.path().join("queue"));
12207            let mut controlled = Task::new(
12208                "resume land".into(),
12209                state.instruction.clone(),
12210                state.repo.clone(),
12211                Source::Agent {
12212                    run: "talk".into(),
12213                    node: crate::queue::CHAT_NODE.into(),
12214                },
12215            );
12216            controlled.runs.push(state.id.clone());
12217            controlled.hold_machine(Some("land stopped".into()));
12218            queue.put(&mut controlled).unwrap();
12219            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
12220            assert_eq!(resumed.status, TaskStatus::Queued);
12221            assert_eq!(
12222                resumed.resume_override.unwrap().pinned_run,
12223                Some(state.id.clone())
12224            );
12225            assert_eq!(resumed.attempts, 0);
12226        }
12227    }
12228
12229    #[test]
12230    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
12231        for review_rounds in [0, 1] {
12232            let home = tempfile::tempdir().unwrap();
12233            let mut state = run_state(RunStatus::Blocked);
12234            state.config.graph.review_rounds = review_rounds;
12235            if review_rounds > 0 {
12236                let mut review = review_round(1);
12237                review.clean = true;
12238                state.reviews = vec![review];
12239            }
12240            state.gate_ran = true;
12241            state.gate = vec![crate::run::CommandOutcome {
12242                command: "verify".into(),
12243                code: Some(1),
12244                output_tail: "gate failed after repair budget exhausted".into(),
12245                duration_ms: 0,
12246                resource_blocked: false,
12247            }];
12248            state.save_under(home.path()).unwrap();
12249            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
12250            assert!(exhausted_review_budget(&state));
12251            let mut task = held_task_with(&state.id);
12252            task.release();
12253            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
12254            let question = action_question(&state.id, resume_action(&state.id));
12255            assert_ne!(
12256                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12257                    state.clone()
12258                )),
12259                ActionDecision::Resume(state.id.clone())
12260            );
12261            let error = crate::resume::validate(home.path(), &state.id)
12262                .unwrap_err()
12263                .to_string();
12264            assert!(!error.contains("review budget exhausted"), "{error}");
12265            assert!(
12266                error.contains(if review_rounds == 0 {
12267                    "review is disabled"
12268                } else {
12269                    "gate already ran"
12270                }),
12271                "{error}"
12272            );
12273
12274            // An unexecuted gate still has work to do with or without reviews.
12275            state.gate_ran = false;
12276            state.gate.clear();
12277            assert!(!exhausted_review_budget(&state));
12278            assert_eq!(
12279                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
12280                Some(state.id)
12281            );
12282        }
12283    }
12284
12285    #[test]
12286    fn resource_blocked_verification_resumes_the_same_run() {
12287        for (kind, stage) in [
12288            ("cache", "clean"),
12289            ("coordination", "clean"),
12290            ("cache", "review-e2e"),
12291            ("coordination", "no-reviews"),
12292            ("coordination", "handoff"),
12293        ] {
12294            let home = tempfile::tempdir().unwrap();
12295            let mut state = run_state(RunStatus::Blocked);
12296            state.config.graph.review_rounds = 1;
12297            let mut review = review_round(1);
12298            review.clean = true;
12299            state.reviews = vec![review];
12300            if stage == "review-e2e" {
12301                let review = &mut state.reviews[0];
12302                review.clean = false;
12303                review.blocking = 1;
12304                review.e2e = vec![crate::run::CommandOutcome {
12305                    command: "verify".into(),
12306                    code: None,
12307                    output_tail: "resource wait expired".into(),
12308                    duration_ms: 0,
12309                    resource_blocked: true,
12310                }];
12311            } else if stage == "no-reviews" {
12312                state.config.graph.review_rounds = 0;
12313                state.reviews.clear();
12314            } else if stage == "handoff" {
12315                // A completed final verification can hand off to the gate
12316                // even when the review still carries contested findings.
12317                let review = &mut state.reviews[0];
12318                review.clean = false;
12319                review.blocking = 1;
12320                review.e2e = vec![crate::run::CommandOutcome {
12321                    command: "verify".into(),
12322                    code: Some(0),
12323                    output_tail: String::new(),
12324                    duration_ms: 0,
12325                    resource_blocked: false,
12326                }];
12327            }
12328            state.gate_ran = false;
12329            state.resource_block = Some(crate::run::ResourceBlock {
12330                cause: crate::run::ResourceBlockCause::Other,
12331                node: if stage == "review-e2e" {
12332                    "review"
12333                } else {
12334                    "gate"
12335                }
12336                .into(),
12337                kind: kind.into(),
12338                detail: "resource wait expired".into(),
12339                at: jiff::Timestamp::now(),
12340            });
12341            state.save_under(home.path()).unwrap();
12342            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
12343            assert!(!exhausted_review_budget(&state));
12344            let mut task = held_task_with(&state.id);
12345            task.release();
12346            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
12347            assert_eq!(
12348                choose_starter(None, false, unfinished.as_deref()),
12349                Starter::Resume(state.id.clone())
12350            );
12351            let question = action_question(&state.id, resume_action(&state.id));
12352            assert_eq!(
12353                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12354                    state.clone()
12355                )),
12356                ActionDecision::Resume(state.id.clone())
12357            );
12358            assert_eq!(
12359                crate::resume::validate(home.path(), &state.id).unwrap().id,
12360                state.id
12361            );
12362            let queue = Queue::at(home.path().join("queue"));
12363            let mut controlled = Task::new(
12364                "resume verification".into(),
12365                state.instruction.clone(),
12366                state.repo.clone(),
12367                Source::Agent {
12368                    run: "talk".into(),
12369                    node: crate::queue::CHAT_NODE.into(),
12370                },
12371            );
12372            controlled.runs.push(state.id.clone());
12373            controlled.hold_machine(Some("verification resource unavailable".into()));
12374            queue.put(&mut controlled).unwrap();
12375            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
12376            assert_eq!(resumed.status, TaskStatus::Queued);
12377            assert_eq!(
12378                resumed.resume_override.unwrap().pinned_run,
12379                Some(state.id.clone())
12380            );
12381            assert_eq!(resumed.attempts, 0);
12382
12383            // A genuinely unresolved final review still exhausts the budget.
12384            state.config.graph.review_rounds = 1;
12385            let mut unresolved = review_round(1);
12386            unresolved.blocking = 1;
12387            state.reviews = vec![unresolved];
12388            state.resource_block = None;
12389            state.save_under(home.path()).unwrap();
12390            assert!(exhausted_review_budget(&state));
12391            assert!(crate::resume::validate(home.path(), &state.id).is_err());
12392        }
12393    }
12394
12395    #[tokio::test]
12396    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
12397        if !crate::standalone_test(
12398            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
12399        ) {
12400            return;
12401        }
12402        let home = tempfile::tempdir().unwrap();
12403        let mut owner = stopped_public_run(RunStatus::Blocked);
12404        owner.save_under(home.path()).unwrap();
12405        let history = vec![owner.id.clone()];
12406        let repo = owner.repo.clone();
12407        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
12408        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
12409        let initial =
12410            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
12411        assert!(
12412            initial.is_pending(),
12413            "a busy record must not hold or resume the task"
12414        );
12415        owner.retired_to = Some("20260101-000001-bbbb".into());
12416        owner.save_under(home.path()).unwrap();
12417        drop(lock);
12418        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
12419            .await
12420            .expect("ownership lock released")
12421            .expect("read settled owner");
12422        assert!(
12423            result.is_none(),
12424            "the retired owner must not be resumed from a stale read"
12425        );
12426    }
12427
12428    #[tokio::test]
12429    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
12430        if !crate::standalone_test(
12431            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
12432        ) {
12433            return;
12434        }
12435        let home = tempfile::tempdir().unwrap();
12436        let mut owner = stopped_public_run(RunStatus::Blocked);
12437        let repo = tempfile::tempdir().unwrap();
12438        crate::git::git(repo.path(), &["init"]).await.unwrap();
12439        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
12440        owner.id = "20260101-000000-aaaa".into();
12441        owner.save_under(home.path()).unwrap();
12442        let mut successor = run_state(RunStatus::Blocked);
12443        successor.id = "20260101-000001-bbbb".into();
12444        successor.save_under(home.path()).unwrap();
12445        let runs = vec![owner.id.clone(), successor.id.clone()];
12446        assert_eq!(
12447            public_resume_owner(home.path(), &runs, &owner.repo)
12448                .await
12449                .unwrap()
12450                .unwrap()
12451                .id,
12452            owner.id
12453        );
12454        let subdir = owner.repo.join("nested");
12455        std::fs::create_dir(&subdir).unwrap();
12456        assert_eq!(
12457            public_resume_owner(home.path(), &runs, &subdir)
12458                .await
12459                .unwrap()
12460                .unwrap()
12461                .id,
12462            owner.id
12463        );
12464        #[cfg(unix)]
12465        {
12466            let alias = home.path().join("repo-alias");
12467            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
12468            assert_eq!(
12469                public_resume_owner(home.path(), &runs, &alias.join("nested"))
12470                    .await
12471                    .unwrap()
12472                    .unwrap()
12473                    .id,
12474                owner.id
12475            );
12476        }
12477        let different = tempfile::tempdir().unwrap();
12478        crate::git::git(different.path(), &["init"]).await.unwrap();
12479        assert!(
12480            public_resume_owner(home.path(), &runs, different.path())
12481                .await
12482                .is_err()
12483        );
12484        std::fs::remove_file(
12485            home.path()
12486                .join("runs")
12487                .join(&successor.id)
12488                .join("run.json"),
12489        )
12490        .unwrap();
12491        assert!(
12492            public_resume_owner(home.path(), &runs, &owner.repo)
12493                .await
12494                .is_err()
12495        );
12496    }
12497
12498    #[test]
12499    fn an_ordinary_release_keeps_a_resumable_run_available() {
12500        let mut released = task();
12501        released.start("stalled-run".to_owned());
12502        released.release();
12503        let unfinished = (!released.fresh_start)
12504            .then(|| Some("stalled-run".to_owned()))
12505            .flatten();
12506        assert_eq!(
12507            choose_starter(None, false, unfinished.as_deref()),
12508            Starter::Resume("stalled-run".to_owned()),
12509            "manual release must preserve the normal resume path"
12510        );
12511    }
12512
12513    #[test]
12514    fn resume_refusals_explain_admission_without_changing_task_or_run() {
12515        use crate::handover::{ResumeRefusal, resume_refusal_under};
12516        let home = tempfile::tempdir().unwrap();
12517        let mut exhausted = run_state(RunStatus::Blocked);
12518        exhausted.driver_exited = true;
12519        exhausted.config.graph.review_rounds = 3;
12520        exhausted.reviews = (1..=3).map(review_round).collect();
12521        for refusal in [
12522            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
12523            ResumeRefusal::Status(RunStatus::Ready),
12524            ResumeRefusal::Released("20261022-000000-aaaa".into()),
12525            ResumeRefusal::Retired("retirement-successor".into()),
12526            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
12527        ] {
12528            let mut state = exhausted.clone();
12529            let expected = match refusal {
12530                ResumeRefusal::Status(_) => {
12531                    state.status = RunStatus::Ready;
12532                    "status `ready`"
12533                }
12534                ResumeRefusal::Released(ref target) => {
12535                    state.released_to = Some(target.clone());
12536                    "execution was released"
12537                }
12538                ResumeRefusal::Retired(ref target) => {
12539                    state.retired_to = Some(target.clone());
12540                    "execution was retired"
12541                }
12542                ResumeRefusal::OwnershipTransferred(ref target) => {
12543                    state.pr_taken_over_by = Some(target.clone());
12544                    "PR ownership was transferred"
12545                }
12546                _ => "review budget exhausted (3/3 rounds used)",
12547            };
12548            assert_eq!(
12549                resume_refusal_under(&state, Some(home.path())),
12550                Some(refusal.clone())
12551            );
12552            assert_eq!(
12553                refusal.successor(),
12554                state
12555                    .released_to
12556                    .as_deref()
12557                    .or(state.retired_to.as_deref())
12558                    .or(state.pr_taken_over_by.as_deref())
12559            );
12560            state.save_under(home.path()).unwrap();
12561            let queue = Queue::at(home.path().join("queue"));
12562            let mut task = Task::new(
12563                "retained implementation".into(),
12564                state.instruction.clone(),
12565                state.repo.clone(),
12566                Source::Agent {
12567                    run: "talk".into(),
12568                    node: crate::queue::CHAT_NODE.into(),
12569                },
12570            );
12571            task.runs.push(state.id.clone());
12572            task.hold_machine(Some("stopped".into()));
12573            queue.put(&mut task).unwrap();
12574            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
12575            let before_run = serde_json::to_value(&state).unwrap();
12576            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
12577                .unwrap_err()
12578                .to_string();
12579            assert!(error.contains(expected), "{error}");
12580            assert!(!error.contains("only a stalled or blocked"), "{error}");
12581            if matches!(refusal, ResumeRefusal::Status(_)) {
12582                assert!(
12583                    error.contains("is final; there is nothing left to resume"),
12584                    "{error}"
12585                );
12586            }
12587            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
12588                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
12589                assert!(error.contains("review-only successor with a new review budget"));
12590                assert!(error.contains("does not resume this run"));
12591            }
12592            for target in [
12593                &state.released_to,
12594                &state.retired_to,
12595                &state.pr_taken_over_by,
12596            ]
12597            .into_iter()
12598            .flatten()
12599            {
12600                let short = if state.retired_to.as_ref() == Some(target) {
12601                    target.as_str()
12602                } else {
12603                    crate::run::short_of(target)
12604                };
12605                assert!(
12606                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
12607                    "{error}"
12608                );
12609                if short != target {
12610                    assert!(!error.contains(target), "full successor id leaked: {error}");
12611                }
12612            }
12613            assert_eq!(
12614                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12615                before_task
12616            );
12617            assert_eq!(
12618                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12619                    .unwrap(),
12620                before_run
12621            );
12622            let question = action_question(&state.id, resume_action(&state.id));
12623            for phrases in [&PHRASES_EN, &PHRASES_JA] {
12624                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
12625                    RunState::load_under(id, home.path())
12626                });
12627                let ActionDecision::Refuse(detail) = decision else {
12628                    panic!(
12629                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
12630                        state.id,
12631                        home.path().display()
12632                    );
12633                };
12634                assert!(detail.contains(expected), "{detail}");
12635            }
12636        }
12637        // Preserve predicate ordering, while keeping every recorded destination visible.
12638        exhausted.status = RunStatus::Ready;
12639        exhausted.released_to = Some("released".into());
12640        exhausted.retired_to = Some("retired".into());
12641        exhausted.pr_taken_over_by = Some("owner".into());
12642        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12643        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12644        let detail = reason.diagnostic(&exhausted);
12645        for target in ["released", "retired", "owner"] {
12646            assert!(detail.contains(&format!("magi show {target}")));
12647        }
12648    }
12649
12650    #[test]
12651    fn resume_action_ignores_question_checkpoints_in_another_home() {
12652        crate::run::pin_test_home();
12653        let home = tempfile::tempdir().unwrap();
12654        let mut state = run_state(RunStatus::Blocked);
12655        // The private directory reserves this fixture's identity even while
12656        // other tests write questions into the process-wide store.
12657        state.id = format!(
12658            "resume-context-{}",
12659            home.path().file_name().unwrap().to_str().unwrap()
12660        );
12661        state.driver_exited = true;
12662        state.config.graph.review_rounds = 1;
12663        state.reviews = vec![review_round(1)];
12664        state.save_under(home.path()).unwrap();
12665        let task = held_task_with(&state.id);
12666        let answer = action_question(&state.id, resume_action(&state.id));
12667        let mut checkpoint = approval_question(&state.id);
12668        let foreign = Questions::open();
12669        foreign.put(&mut checkpoint).unwrap();
12670        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
12671        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12672            RunState::load_under(id, home.path())
12673        });
12674        let matching: Vec<_> = foreign
12675            .list()
12676            .into_iter()
12677            .filter(|q| q.run == state.id && q.status.open())
12678            .collect();
12679        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
12680        assert!(
12681            matches!(decision, ActionDecision::Refuse(_)),
12682            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
12683            state.id,
12684            home.path().display(),
12685            crate::run::test_home().display()
12686        );
12687        assert_eq!(
12688            refusal,
12689            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
12690        );
12691        let local = Questions::at(home.path().join("questions"));
12692        for status in [
12693            ask::QuestionStatus::Open,
12694            ask::QuestionStatus::Answered,
12695            ask::QuestionStatus::Abandoned,
12696        ] {
12697            let mut question = checkpoint.clone();
12698            match status {
12699                ask::QuestionStatus::Open => {}
12700                ask::QuestionStatus::Answered => {
12701                    question
12702                        .answer(ask::Answer::Choice(question.choices[0].clone()))
12703                        .unwrap();
12704                }
12705                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
12706            }
12707            local.put(&mut question).unwrap();
12708            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12709                RunState::load_under(id, home.path())
12710            });
12711            if status.open() {
12712                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
12713            } else {
12714                assert!(
12715                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
12716                    "status={status:?}, decision={decision:?}"
12717                );
12718            }
12719        }
12720    }
12721
12722    #[test]
12723    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
12724        let home = tempfile::tempdir().unwrap();
12725        let mut state = run_state(RunStatus::Stalled);
12726        state.id = format!(
12727            "resume-driver-{}",
12728            home.path().file_name().unwrap().to_str().unwrap()
12729        );
12730        state.driver_claimed = Some(false);
12731        state.save_under(home.path()).unwrap();
12732        let task = held_task_with(&state.id);
12733        let question = action_question(&state.id, resume_action(&state.id));
12734        let decide = || {
12735            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
12736                RunState::load_under(id, home.path())
12737            })
12738        };
12739        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
12740        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
12741        assert_eq!(
12742            decide(),
12743            ActionDecision::Refuse("run already has a live driver".into())
12744        );
12745        drop(lease);
12746        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
12747    }
12748
12749    #[test]
12750    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12751        let home = tempfile::tempdir().unwrap();
12752        let mut state = run_state(RunStatus::Blocked);
12753        state.driver_exited = true;
12754        state.config.graph.review_rounds = 1;
12755        state.reviews = vec![review_round(1)];
12756        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12757        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12758            let mut saved = state.clone();
12759            match checkpoint {
12760                "publication" => saved.pr_publication_pending = true,
12761                "approval" => {
12762                    saved.land_approval = Some(crate::run::LandApproval {
12763                        question: "approval".into(),
12764                        head: "head".into(),
12765                    })
12766                }
12767                "armed" => saved.land_armed_head = Some("head".into()),
12768                "landing" => saved.status = RunStatus::Landing,
12769                _ => {
12770                    let mut question = ask::Question::new(
12771                        saved.id.clone(),
12772                        "review".into(),
12773                        "review-1".into(),
12774                        "continue?".into(),
12775                        String::new(),
12776                        vec!["continue".into()],
12777                    );
12778                    ask::Questions::at(home.path().join("questions"))
12779                        .put(&mut question)
12780                        .unwrap();
12781                }
12782            }
12783            saved.save_under(home.path()).unwrap();
12784            assert!(
12785                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12786                "{checkpoint}"
12787            );
12788            assert!(
12789                crate::resume::validate(home.path(), &saved.id).is_ok(),
12790                "{checkpoint}"
12791            );
12792        }
12793    }
12794
12795    #[test]
12796    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12797        let mut state = run_state(RunStatus::Blocked);
12798        state.config.graph.review_rounds = 3;
12799        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12800        assert!(exhausted_review_budget(&state));
12801
12802        // One round still unused: resuming can still ask a reviewer something.
12803        state.reviews.pop();
12804        assert!(!exhausted_review_budget(&state));
12805
12806        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
12807        // count: only a `Blocked` run re-enters the review loop on resume.
12808        let mut stalled = run_state(RunStatus::Stalled);
12809        stalled.config.graph.review_rounds = 1;
12810        stalled.reviews = vec![review_round(1)];
12811        assert!(!exhausted_review_budget(&stalled));
12812    }
12813
12814    fn review_round(round: usize) -> crate::run::ReviewRound {
12815        crate::run::ReviewRound {
12816            round,
12817            head: "deadbeef".to_owned(),
12818            verified_head: None,
12819            verified_at: None,
12820            reviews: Vec::new(),
12821            e2e: Vec::new(),
12822            verify_retried: false,
12823            e2e_deferred: false,
12824            e2e_defer_reason: None,
12825            fix: None,
12826            blocking: 0,
12827            answered: 1,
12828            expected: 1,
12829            clean: false,
12830            progressed: true,
12831            vote_split: false,
12832            reconsideration: Vec::new(),
12833            verdict: None,
12834        }
12835    }
12836
12837    #[test]
12838    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12839        let mut run = RunState::new(
12840            PathBuf::from("/repo"),
12841            "main".to_owned(),
12842            "abc1234def".to_owned(),
12843            "add retries".to_owned(),
12844            Config::default(),
12845        );
12846        run.status = RunStatus::Judging;
12847        run.parked = true;
12848        let mut task = Task::new(
12849            "add retries".to_owned(),
12850            "add retries".to_owned(),
12851            PathBuf::from("/repo"),
12852            crate::queue::Source::Human,
12853        );
12854        task.status = TaskStatus::Failed;
12855        task.runs = vec![run.id.clone()];
12856        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12857        assert!(with(&task, &run), "parked after judging is the case");
12858        let mut parked_task = task.clone();
12859        parked_task.status = TaskStatus::Parked;
12860        assert!(with(&parked_task, &run), "the Parked status is the case");
12861
12862        let mut not_parked = run.clone();
12863        not_parked.parked = false;
12864        not_parked.status = RunStatus::Stalled;
12865        assert!(!with(&task, &not_parked), "a stall is the conductor's");
12866
12867        let mut fresh = task.clone();
12868        fresh.fresh_start = true;
12869        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12870
12871        let mut review = task.clone();
12872        review.review_branch = Some("magi/x/A".to_owned());
12873        assert!(!with(&review, &run), "review is ranked before resume");
12874
12875        let mut held = task.clone();
12876        held.status = TaskStatus::Held;
12877        assert!(!with(&held, &run), "a hold stays visible to the conductor");
12878
12879        let mut released = run.clone();
12880        released.released_to = Some("20260901-000000-new1".to_owned());
12881        assert!(!with(&task, &released), "nothing left to resume into");
12882
12883        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12884            "unreadable"
12885        )));
12886    }
12887
12888    #[test]
12889    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12890        let mut released = RunState::new(
12891            PathBuf::from("/repo"),
12892            "main".to_owned(),
12893            "abc1234def".to_owned(),
12894            "add retries".to_owned(),
12895            Config::default(),
12896        );
12897        released.status = RunStatus::Blocked;
12898        assert_eq!(
12899            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12900            Some(released.id.clone())
12901        );
12902        released.released_to = Some("20260901-000000-new1".to_owned());
12903        assert_eq!(
12904            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12905            None,
12906            "there is nothing left to resume it into"
12907        );
12908    }
12909
12910    #[test]
12911    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12912        // Mirrors the failure this exists to close: a task's last run ended
12913        // `Blocked` with the review budget spent, `crate::conduct` chose
12914        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
12915        // evidence), and without this check `attempt` would go on treating
12916        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
12917        // review loop iterates zero times over an already-spent budget, so
12918        // the resumed run settles right back to `Blocked` having asked nobody
12919        // anything, and `Requeue`'s promised fresh competition never happens.
12920        let mut exhausted = RunState::new(
12921            PathBuf::from("/repo"),
12922            "main".to_owned(),
12923            "abc1234def".to_owned(),
12924            "add retries".to_owned(),
12925            Config::default(),
12926        );
12927        exhausted.status = RunStatus::Blocked;
12928        exhausted.config.graph.review_rounds = 1;
12929        exhausted.reviews = vec![review_round(1)];
12930
12931        assert_eq!(
12932            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12933            None,
12934            "an exhausted `Blocked` run must not be offered as resumable"
12935        );
12936
12937        // A `Blocked` run with rounds still unused is genuinely worth
12938        // resuming, and must still be found.
12939        let mut has_budget_left = RunState::new(
12940            PathBuf::from("/repo"),
12941            "main".to_owned(),
12942            "abc1234def".to_owned(),
12943            "add retries".to_owned(),
12944            Config::default(),
12945        );
12946        has_budget_left.status = RunStatus::Blocked;
12947        has_budget_left.config.graph.review_rounds = 3;
12948        has_budget_left.reviews = vec![review_round(1)];
12949
12950        assert_eq!(
12951            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12952                Ok(has_budget_left.clone())
12953            }),
12954            Some(has_budget_left.id.clone())
12955        );
12956    }
12957
12958    #[test]
12959    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12960        let mut run = RunState::new(
12961            PathBuf::from("/repo"),
12962            "main".to_owned(),
12963            "abc1234def".to_owned(),
12964            "add retries".to_owned(),
12965            Config::default(),
12966        );
12967        run.status = RunStatus::Blocked;
12968        run.config.graph.review_rounds = 1;
12969        run.reviews = vec![review_round(1)];
12970        run.pr_publication_pending = true;
12971        assert_eq!(
12972            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12973            Some(run.id.clone()),
12974            "a spent review budget must not turn a failed publication into a re-competition"
12975        );
12976    }
12977
12978    #[test]
12979    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12980        let mut task = Task::new(
12981            "recover work".into(),
12982            "recover work".into(),
12983            PathBuf::from("/repo"),
12984            crate::queue::Source::Human,
12985        );
12986        let mut history = std::collections::BTreeMap::new();
12987        for index in 0..8 {
12988            let mut run = run_state(RunStatus::Blocked);
12989            run.id = format!("20260101-000000-{index:04}");
12990            run.base_commit = format!("upstream-{index}");
12991            // Seven empty newer attempts must not erase the old recovery owner.
12992            if index > 0 {
12993                run.candidates.clear();
12994            }
12995            task.runs.extend([run.id.clone(), run.id.clone()]);
12996            history.insert(run.id.clone(), run);
12997            task.requeue();
12998        }
12999        let check = |task: &Task, starter: &Starter, limit| {
13000            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
13001        };
13002        assert!(
13003            check(&task, &Starter::Start, 8)
13004                .unwrap()
13005                .contains("8 unretired")
13006        );
13007        assert!(check(&task, &Starter::Start, 9).is_none());
13008        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
13009        task.release_operator("owner", None);
13010        assert_eq!(task.attempts, 0);
13011        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13012        assert!(check(&restored, &Starter::Start, 8).is_some());
13013        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
13014        assert!(check(&restored, &Starter::Start, 0).is_none());
13015    }
13016
13017    #[test]
13018    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
13019        let tmp = tempfile::tempdir().unwrap();
13020        let mut task = Task::new(
13021            "recover selected PR".into(),
13022            "preserve implementation".into(),
13023            tmp.path().join("repo"),
13024            crate::queue::Source::Human,
13025        );
13026        let mut failed = run_state(RunStatus::Failed);
13027        failed.id = "20260101-000000-fail".into();
13028        failed.candidates.clear();
13029        failed.prep_complete = Some(false);
13030        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
13031        failed.startup = Some(crate::run::Startup {
13032            kind: "pr-recovery".into(),
13033            branch: Some("selected-public-head".into()),
13034            stage: "worktree-setup".into(),
13035            complete: false,
13036            failure: Some("setup modified a tracked file and failed".into()),
13037        });
13038        // Setup may fail before a candidate is recorded; its dirty worktree
13039        // still needs protection and consumes the independent retained bound.
13040        let worktree = failed.worktree_root().join("under-review");
13041        std::fs::create_dir_all(&worktree).unwrap();
13042        let retained_edit = worktree.join("implementation");
13043        std::fs::write(&retained_edit, "retained setup edit").unwrap();
13044        task.record_startup_failure(crate::run::StartupFailure {
13045            run: failed.id.clone(),
13046            stage: "worktree-setup".into(),
13047        });
13048        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13049        assert!(task.runs.is_empty() && task.passes.is_empty());
13050        assert_eq!(task.attempts, 0);
13051        let starter = Starter::Review("selected-public-head".into());
13052        assert!(
13053            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
13054                .unwrap()
13055                .contains("1 unretired")
13056        );
13057        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
13058        assert!(
13059            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
13060                .unwrap()
13061                .contains("Cannot verify")
13062        );
13063        // Older or mixed writers can link the same reservation in both lists.
13064        let mut mixed = task.clone();
13065        mixed.runs.push(failed.id.clone());
13066        mixed
13067            .startup_failures
13068            .push(task.startup_failures[0].clone());
13069        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
13070        failed.retired_to = Some("verified-recovery-owner".into());
13071        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
13072        assert!(
13073            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
13074                panic!("resuming the existing owner must not allocate a new attempt")
13075            })
13076            .is_none()
13077        );
13078        assert_eq!(
13079            std::fs::read_to_string(retained_edit).unwrap(),
13080            "retained setup edit"
13081        );
13082        assert!(task.runs.is_empty() && task.passes.is_empty());
13083        assert_eq!(task.attempts, 0);
13084    }
13085
13086    #[test]
13087    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
13088        let mut task = Task::new(
13089            "recover work".into(),
13090            "recover work".into(),
13091            PathBuf::from("/repo"),
13092            crate::queue::Source::Human,
13093        );
13094        let mut run = run_state(RunStatus::Superseded);
13095        run.candidates.clear();
13096        task.runs.push(run.id.clone());
13097        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
13098        run.retired_to = Some("authority".into());
13099        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13100        run.retired_to = None;
13101        run.released_to = Some("authority".into());
13102        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13103        assert!(
13104            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
13105                .unwrap()
13106                .contains("Cannot verify")
13107        );
13108        // Resuming an existing owner needs no new inventory or worktree budget.
13109        assert!(
13110            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
13111                panic!("resume must not load historical attempts")
13112            })
13113            .is_none()
13114        );
13115    }
13116
13117    #[test]
13118    fn retired_resume_requires_a_valid_same_repository_authority() {
13119        let mut source = run_state(RunStatus::Blocked);
13120        let mut empty = run_state(RunStatus::Blocked);
13121        empty.retired_to = Some(source.id.clone());
13122        let runs = vec![source.id.clone(), empty.id.clone()];
13123        let resolve = |source: &RunState, empty: &RunState| {
13124            unfinished_run_with(&runs, "fixture", |id| {
13125                if id == source.id {
13126                    Ok(source.clone())
13127                } else if id == empty.id {
13128                    Ok(empty.clone())
13129                } else {
13130                    bail!("unreadable authority")
13131                }
13132            })
13133        };
13134        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
13135        assert_eq!(
13136            choose_starter(None, false, resolve(&source, &empty).as_deref()),
13137            Starter::Resume(source.id.clone())
13138        );
13139        source.retired_to = Some(empty.id.clone());
13140        assert!(
13141            resolve(&source, &empty).is_none(),
13142            "cycles do not revive obsolete runs"
13143        );
13144        source.retired_to = None;
13145        source.repo = PathBuf::from("/another-repository");
13146        assert!(resolve(&source, &empty).is_none());
13147        source.repo = empty.repo.clone();
13148        source.released_to = Some("later".into());
13149        assert!(resolve(&source, &empty).is_none());
13150        empty.retired_to = Some("unlisted-run".into());
13151        assert!(resolve(&source, &empty).is_none());
13152    }
13153
13154    #[test]
13155    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
13156        // A task whose history holds an *older* run that still looks
13157        // resumable (say, a competition `Runner::review` was started
13158        // alongside after that older run went `Stalled`) and a *newest* run
13159        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
13160        // on this task must mean a fresh competition — falling back to the
13161        // stale, superseded `Stalled` run instead would resurrect history
13162        // nothing asked to revisit and silently defeat the requeue.
13163        let mut older_stalled = RunState::new(
13164            PathBuf::from("/repo"),
13165            "main".to_owned(),
13166            "abc1234def".to_owned(),
13167            "add retries".to_owned(),
13168            Config::default(),
13169        );
13170        older_stalled.status = RunStatus::Stalled;
13171
13172        let mut newest_exhausted = RunState::new(
13173            PathBuf::from("/repo"),
13174            "main".to_owned(),
13175            "abc1234def".to_owned(),
13176            "add retries".to_owned(),
13177            Config::default(),
13178        );
13179        newest_exhausted.status = RunStatus::Blocked;
13180        newest_exhausted.config.graph.review_rounds = 1;
13181        newest_exhausted.reviews = vec![review_round(1)];
13182
13183        assert_eq!(
13184            unfinished_run_with(
13185                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
13186                "t",
13187                |_| Ok(newest_exhausted.clone())
13188            ),
13189            None,
13190            "the newest run is exhausted, so nothing here is worth resuming - \
13191             least of all the older, already-superseded run"
13192        );
13193    }
13194
13195    #[test]
13196    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
13197        assert_eq!(
13198            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
13199                Err(anyhow::anyhow!("fixture is absent"))
13200            }),
13201            None
13202        );
13203    }
13204
13205    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
13206        let mut q = ask::Question::new(
13207            run.to_owned(),
13208            "implement".to_owned(),
13209            "impl-A".to_owned(),
13210            "continue?".to_owned(),
13211            String::new(),
13212            vec!["resume で続行する".to_owned(), "other".to_owned()],
13213        );
13214        q.actions.insert("resume で続行する".to_owned(), action);
13215        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
13216            .unwrap();
13217        q
13218    }
13219
13220    fn held_task_with(run: &str) -> Task {
13221        let mut t = task();
13222        t.runs = vec![run.to_owned()];
13223        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
13224        t
13225    }
13226
13227    fn resume_action(run: &str) -> ask::ChoiceAction {
13228        ask::ChoiceAction::Resume { run: run.into() }
13229    }
13230
13231    #[test]
13232    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
13233        let home = crate::run::test_home();
13234        for parked in [false, true] {
13235            let mut t = task();
13236            t.start("A".into());
13237            t.start("B".into());
13238            assert_eq!(t.runs, vec!["A", "B"]);
13239            t.start("A".into());
13240            let mut resumed = run_state(RunStatus::Blocked);
13241            resumed.id = "A".into();
13242            resumed.parked = parked;
13243            resumed.driver_exited = true;
13244            t.hold_machine(Some("resumed run stopped".into()));
13245            let q = action_question("A", resume_action("A"));
13246            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13247            assert_eq!(
13248                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
13249                    assert_eq!(id, "A");
13250                    Ok(resumed.clone())
13251                }),
13252                ActionDecision::Resume("A".into())
13253            );
13254            assert_eq!(
13255                action_standing(&t, &action_question("B", resume_action("B"))),
13256                ActionStanding::Stale
13257            );
13258            t.release_operator("cli", None);
13259            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
13260                assert_eq!(id, "A");
13261                Ok(resumed.clone())
13262            });
13263            assert_eq!(
13264                choose_starter(None, false, unfinished.as_deref()),
13265                Starter::Resume("A".into())
13266            );
13267            assert_eq!(t.runs, vec!["B", "A"]);
13268        }
13269    }
13270
13271    #[test]
13272    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
13273        let home = crate::run::test_home();
13274        let mut state = crate::land::tests::repair_state(true, true);
13275        state.status = RunStatus::Landing;
13276        state.parked = true;
13277        state.driver_exited = true;
13278        let mut q = ask::Question::new(
13279            state.id.clone(),
13280            land::APPROVAL_NODE.into(),
13281            "land".into(),
13282            "Merge?".into(),
13283            String::new(),
13284            vec![land::APPROVE.into(), land::HOLD.into()],
13285        );
13286        q.id = state.id.clone();
13287        state.land_approval = Some(crate::run::LandApproval {
13288            question: q.id.clone(),
13289            head: "current-head".into(),
13290        });
13291        assert!(land::upgrade_repair_choice(&mut q, &state));
13292        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13293        let mut task = held_task_with(&state.id);
13294        task.status = TaskStatus::Parked;
13295        assert_eq!(
13296            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
13297            ActionDecision::Resume(state.id.clone())
13298        );
13299        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13300        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
13301        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
13302        assert_eq!(
13303            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
13304            ActionDecision::Resume(state.id.clone()),
13305            "a repair answer newer than the manual hold resumes the existing owner"
13306        );
13307        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
13308        for answered_at in [q.answered_at, None] {
13309            let mut older = q.clone();
13310            older.answered_at = answered_at;
13311            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
13312                panic!("a later manual hold must prevent dispatch")
13313            });
13314            let ActionDecision::Refuse(reason) = refused else {
13315                panic!("expected an actionable refusal, got {refused:?}");
13316            };
13317            assert!(reason.contains("later operator decision"));
13318            assert!(reason.contains(&format!("magi task release {}", task.id)));
13319        }
13320        task.operator_decided_at = None;
13321        let mut superseded = state.clone();
13322        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
13323        assert_eq!(
13324            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
13325            ActionDecision::Stale
13326        );
13327        for case in 1..4 {
13328            let mut changed = state.clone();
13329            match case {
13330                1 => changed.status = RunStatus::Blocked,
13331                2 => changed.released_to = Some("new-owner".into()),
13332                _ => changed.land_approval.as_mut().unwrap().head.clear(),
13333            }
13334            assert!(matches!(
13335                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
13336                ActionDecision::Refuse(_)
13337            ));
13338        }
13339        assert!(matches!(
13340            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
13341                "missing owner"
13342            )),
13343            ActionDecision::Refuse(_)
13344        ));
13345        task.runs.push("replacement".into());
13346        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
13347        assert_eq!(
13348            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
13349                "old owner must not load"
13350            )),
13351            ActionDecision::Stale
13352        );
13353    }
13354
13355    #[test]
13356    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
13357        let mut state = crate::land::tests::repair_state(true, true);
13358        state.status = RunStatus::Landing;
13359        state.parked = true;
13360        state.driver_exited = true;
13361        let mut q = ask::Question::new(
13362            state.id.clone(),
13363            land::APPROVAL_NODE.into(),
13364            "land".into(),
13365            "Merge?".into(),
13366            String::new(),
13367            vec![land::APPROVE.into(), land::HOLD.into()],
13368        );
13369        q.id = state.id.clone();
13370        state.land_approval = Some(crate::run::LandApproval {
13371            question: q.id.clone(),
13372            head: "current-head".into(),
13373        });
13374        state.save().unwrap();
13375        land::upgrade_repair_choice(&mut q, &state);
13376        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13377        Questions::open().put(&mut q).unwrap();
13378        let tmp = tempfile::tempdir().unwrap();
13379        let queue = Queue::at(tmp.path().join("queue"));
13380        let mut task = held_task_with(&state.id);
13381        task.status = TaskStatus::Parked;
13382        queue.put(&mut task).unwrap();
13383        let empty = Arc::new(tokio::sync::Semaphore::new(0));
13384        let free = Arc::new(tokio::sync::Semaphore::new(1));
13385        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
13386        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
13387        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
13388        assert!(claim.permit.is_some());
13389        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
13390        drop(claim);
13391        Questions::open()
13392            .update(&q.id, |q| {
13393                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
13394                Ok(())
13395            })
13396            .unwrap();
13397        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
13398        assert!(claim.permit.is_none());
13399        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
13400    }
13401
13402    #[test]
13403    fn decide_action_resumes_only_the_latest_resumable_run() {
13404        let home = crate::run::test_home();
13405        let t = held_task_with("r1");
13406        let q = action_question("r1", resume_action("r1"));
13407        let load = |s: RunState| move |_: &str| Ok(s);
13408        assert_eq!(
13409            decide_action(
13410                &home,
13411                &t,
13412                &q,
13413                &PHRASES_EN,
13414                load(run_state(RunStatus::Blocked))
13415            ),
13416            ActionDecision::Resume("r1".into())
13417        );
13418        // Not the latest run of the task.
13419        let q_other = action_question("r1", resume_action("r0"));
13420        assert!(matches!(
13421            decide_action(
13422                &home,
13423                &t,
13424                &q_other,
13425                &PHRASES_EN,
13426                load(run_state(RunStatus::Blocked))
13427            ),
13428            ActionDecision::Refuse(_)
13429        ));
13430        // A finished run cannot make progress.
13431        assert!(matches!(
13432            decide_action(
13433                &home,
13434                &t,
13435                &q,
13436                &PHRASES_EN,
13437                load(run_state(RunStatus::Ready))
13438            ),
13439            ActionDecision::Refuse(_)
13440        ));
13441        // A released one either.
13442        let mut released = run_state(RunStatus::Blocked);
13443        released.released_to = Some("elsewhere".into());
13444        assert!(matches!(
13445            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
13446            ActionDecision::Refuse(_)
13447        ));
13448        // Unreadable state is a refusal, never a fresh competition.
13449        assert!(matches!(
13450            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
13451            ActionDecision::Refuse(_)
13452        ));
13453    }
13454
13455    #[test]
13456    fn decide_action_ignores_a_question_about_an_earlier_run() {
13457        let home = crate::run::test_home();
13458        let mut t = held_task_with("r1");
13459        t.runs.push("r2".to_owned());
13460        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13461        assert_eq!(
13462            decide_action(
13463                &home,
13464                &t,
13465                &action_question("r1", ask::ChoiceAction::Done),
13466                &PHRASES_EN,
13467                never
13468            ),
13469            ActionDecision::Stale
13470        );
13471    }
13472
13473    #[test]
13474    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
13475        let home = crate::run::test_home();
13476        let mut t = held_task_with("r1");
13477        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13478        assert_eq!(
13479            decide_action(
13480                &home,
13481                &t,
13482                &action_question("r1", ask::ChoiceAction::Requeue),
13483                &PHRASES_EN,
13484                never
13485            ),
13486            ActionDecision::Requeue
13487        );
13488        let done_q = action_question("r1", ask::ChoiceAction::Done);
13489        assert_eq!(
13490            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13491            ActionDecision::Done
13492        );
13493        t.mark_action_applied(&done_q.id);
13494        assert_eq!(
13495            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13496            ActionDecision::Skip
13497        );
13498
13499        // A plain answer (no action for that label) does nothing.
13500        let mut plain = action_question("r1", ask::ChoiceAction::Done);
13501        plain.actions.clear();
13502        assert_eq!(
13503            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
13504            ActionDecision::Skip
13505        );
13506        // A running task is left alone.
13507        let mut running = held_task_with("r1");
13508        running.status = TaskStatus::Running;
13509        assert_eq!(
13510            decide_action(
13511                &home,
13512                &running,
13513                &action_question("r1", ask::ChoiceAction::Done),
13514                &PHRASES_EN,
13515                never
13516            ),
13517            ActionDecision::Skip
13518        );
13519    }
13520
13521    #[test]
13522    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
13523        crate::run::pin_test_home();
13524        for legacy in [false, true] {
13525            let dir = tempfile::tempdir().unwrap();
13526            let queue = Queue::at(dir.path().join("queue"));
13527            let questions = Questions::at(dir.path().join("questions"));
13528            let run = "20260101-000000-hold";
13529            let mut task = held_task_with(run);
13530            task.status = TaskStatus::Parked;
13531            let mut q = ask::Question::new(
13532                run.into(),
13533                land::APPROVAL_NODE.into(),
13534                "land".into(),
13535                "Repair?".into(),
13536                String::new(),
13537                vec![land::REPAIR.into()],
13538            );
13539            q.actions.insert(land::REPAIR.into(), resume_action(run));
13540            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13541            // Deterministically order the answer before the actual manual hold.
13542            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13543            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
13544            questions.put(&mut q).unwrap();
13545            task.hold_manual(Some("Keep this PR paused".into()));
13546            if legacy {
13547                task.hold_source = None;
13548            }
13549            queue.put(&mut task).unwrap();
13550
13551            apply_task_choice_actions(&queue, &questions, dir.path());
13552            let after = queue.get(&task.id).unwrap();
13553            assert!(after.operator_held());
13554            assert_eq!(after.hold_source, task.hold_source);
13555            assert_eq!(after.operator_decided_at, task.operator_decided_at);
13556            assert_eq!(after.runs, task.runs);
13557            assert_eq!(after.instruction, task.instruction);
13558            assert!(after.resume_override.is_none());
13559            assert!(after.action_applied(&q.id));
13560            let reason = after.hold_reason.as_deref().unwrap();
13561            assert!(reason.starts_with("Keep this PR paused"));
13562            assert!(reason.contains("later operator decision"));
13563            assert!(reason.contains(&format!("magi task release {}", task.id)));
13564
13565            for recovery in [
13566                crate::conduct::Recovery::Review,
13567                crate::conduct::Recovery::Requeue,
13568            ] {
13569                crate::conduct::apply(
13570                    &queue,
13571                    &questions,
13572                    &crate::conduct::Verdict {
13573                        decisions: vec![crate::conduct::Decision {
13574                            id: task.id.clone(),
13575                            recovery: Some(recovery),
13576                            ..Default::default()
13577                        }],
13578                    },
13579                )
13580                .unwrap();
13581            }
13582            // Reconciliation is idempotent, and automatic recovery cannot
13583            // reopen this owner after it observes the rejected repair answer.
13584            apply_task_choice_actions(&queue, &questions, dir.path());
13585            let still_held = queue.get(&task.id).unwrap();
13586            assert!(still_held.operator_held());
13587            assert_eq!(still_held.hold_reason, after.hold_reason);
13588            assert_eq!(still_held.runs, task.runs);
13589            assert!(still_held.review_branch.is_none());
13590            assert!(!still_held.fresh_start);
13591            assert!(queue.next_runnable().is_none());
13592        }
13593    }
13594
13595    #[test]
13596    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
13597        for held in [false, true] {
13598            for retry in [false, true] {
13599                let dir = tempfile::tempdir().unwrap();
13600                let queue = Queue::at(dir.path().join("queue"));
13601                let questions = Questions::at(dir.path().join("questions"));
13602                let home = dir.path().join("home");
13603                let mut t = task();
13604                if held {
13605                    t.hold_machine(Some("driver state unknown".into()));
13606                }
13607                queue.put(&mut t).unwrap();
13608                let verdict = serde_json::from_value(serde_json::json!({
13609                    "decisions": [{
13610                        "id": t.id,
13611                        "question": "Driver state unknown; retry the checks or hold?",
13612                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
13613                        "actions": {
13614                            "daemon: recheck and retry": {"do": "requeue"},
13615                            "daemon: hold the task": {"do": "hold"}
13616                        }
13617                    }]
13618                }))
13619                .unwrap();
13620                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
13621                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13622                let mut q = questions.list().pop().unwrap();
13623                let choice = if retry {
13624                    "daemon: recheck and retry"
13625                } else {
13626                    "daemon: hold the task"
13627                };
13628                assert_eq!(q.actions.len(), 2);
13629                q.answer(ask::Answer::Choice(choice.into())).unwrap();
13630                questions.put(&mut q).unwrap();
13631
13632                // A Web answer does not remove the deputy's fresh lease.
13633                questions.beat(&q.id, ask::WaiterKind::Deputy);
13634                for _ in 0..2 {
13635                    resolve_blockers(&queue, &questions);
13636                    apply_task_choice_actions(&queue, &questions, &home);
13637                    let waiting = queue.get(&t.id).unwrap();
13638                    assert_eq!(waiting.status, TaskStatus::Blocked);
13639                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
13640                    assert!(waiting.answers.is_empty());
13641                    assert!(!waiting.action_applied(&q.id));
13642                    assert!(runnable(&queue).is_empty());
13643                    let free = Arc::new(tokio::sync::Semaphore::new(1));
13644                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
13645                }
13646                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13647
13648                // Releasing the blocker and applying the operation share one save.
13649                resolve_blockers(&queue, &questions);
13650                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13651                apply_task_choice_actions(&queue, &questions, &home);
13652                let after = queue.get(&t.id).unwrap();
13653                assert_eq!(
13654                    after.status,
13655                    if retry {
13656                        TaskStatus::Queued
13657                    } else {
13658                        TaskStatus::Held
13659                    }
13660                );
13661                assert!(after.action_applied(&q.id));
13662                assert_eq!(after.operator_held(), !retry);
13663                assert_eq!(after.answers.len(), 1);
13664
13665                // A later operator decision must not replay this answer.
13666                let mut changed = after;
13667                if retry {
13668                    changed.hold_manual(Some("later hold".into()));
13669                } else {
13670                    changed.release_operator("test", None);
13671                }
13672                let expected = changed.status;
13673                queue.put(&mut changed).unwrap();
13674                apply_task_choice_actions(&queue, &questions, &home);
13675                assert_eq!(queue.get(&t.id).unwrap().status, expected);
13676            }
13677        }
13678    }
13679
13680    #[test]
13681    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
13682        let dir = tempfile::tempdir().unwrap();
13683        let queue = Queue::at(dir.path().join("queue"));
13684        let questions = Questions::at(dir.path().join("questions"));
13685        let home = dir.path().join("home");
13686        let mut state = run_state(RunStatus::Blocked);
13687        state.id = "20260101-000000-act1".to_owned();
13688        state.save_under(&home).unwrap();
13689
13690        let mut t = held_task_with(&state.id);
13691        queue.put(&mut t).unwrap();
13692        let mut q = action_question(&state.id, resume_action(&state.id));
13693        questions.put(&mut q).unwrap();
13694
13695        apply_task_choice_actions(&queue, &questions, &home);
13696        let after = queue.get(&t.id).unwrap();
13697        assert_eq!(after.status, TaskStatus::Queued);
13698        assert!(!after.fresh_start);
13699        assert!(after.action_applied(&q.id));
13700        let pin = after.resume_override.clone().unwrap();
13701        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
13702        assert!(pin.forced);
13703
13704        // Held again later: the same answer does not release it a second time.
13705        let mut again = queue.get(&t.id).unwrap();
13706        again.hold_machine(Some("later".into()));
13707        queue.put(&mut again).unwrap();
13708        apply_task_choice_actions(&queue, &questions, &home);
13709        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13710    }
13711
13712    #[test]
13713    fn a_delivered_answer_is_still_acted_on_exactly_once() {
13714        let dir = tempfile::tempdir().unwrap();
13715        let queue = Queue::at(dir.path().join("queue"));
13716        let questions = Questions::at(dir.path().join("questions"));
13717        let home = dir.path().join("home");
13718        let mut state = run_state(RunStatus::Blocked);
13719        state.id = "20260101-000000-act2".to_owned();
13720        state.save_under(&home).unwrap();
13721
13722        let mut t = held_task_with(&state.id);
13723        queue.put(&mut t).unwrap();
13724        let mut q = action_question(&state.id, resume_action(&state.id));
13725        q.answer_delivered = true;
13726        questions.put(&mut q).unwrap();
13727
13728        // Delivered, and the agent then died: the task is still held, so the
13729        // chosen action applies.
13730        apply_task_choice_actions(&queue, &questions, &home);
13731        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13732        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
13733
13734        // Held again: the same answer does nothing a second time.
13735        let mut again = queue.get(&t.id).unwrap();
13736        again.hold_machine(Some("later".into()));
13737        queue.put(&mut again).unwrap();
13738        apply_task_choice_actions(&queue, &questions, &home);
13739        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13740    }
13741
13742    #[test]
13743    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
13744        let dir = tempfile::tempdir().unwrap();
13745        let queue = Queue::at(dir.path().join("queue"));
13746        let questions = Questions::at(dir.path().join("questions"));
13747        let home = dir.path().join("home");
13748        let mut state = run_state(RunStatus::Blocked);
13749        state.id = "20260101-000000-act3".to_owned();
13750        state.save_under(&home).unwrap();
13751        let mut t = held_task_with(&state.id);
13752        queue.put(&mut t).unwrap();
13753        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
13754        questions.put(&mut q).unwrap();
13755
13756        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
13757        apply_task_choice_actions(&queue, &questions, &home);
13758        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13759
13760        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13761        apply_task_choice_actions(&queue, &questions, &home);
13762        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13763    }
13764
13765    #[test]
13766    fn action_standing_tells_the_reasons_apart() {
13767        let mut t = held_task_with("r1");
13768        let q = action_question("r1", ask::ChoiceAction::Requeue);
13769        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13770        let mut plain = q.clone();
13771        plain.actions.clear();
13772        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
13773
13774        // Applied wins over everything, even a running task.
13775        t.mark_action_applied(&q.id);
13776        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
13777
13778        // A newer attempt running: the old question is Stale, not Busy.
13779        let mut t = held_task_with("r1");
13780        t.start("r2".to_owned());
13781        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
13782        // The same question about the latest run just waits.
13783        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
13784        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13785        t.status = TaskStatus::Blocked;
13786        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13787
13788        // A conductor question is keyed by the task, never stale.
13789        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
13790        c.node = crate::conduct::NODE.to_owned();
13791        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
13792        assert!(!ActionStanding::Busy.daemon_owns());
13793    }
13794
13795    #[test]
13796    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
13797        let dir = tempfile::tempdir().unwrap();
13798        let queue = Queue::at(dir.path().join("queue"));
13799        let questions = Questions::at(dir.path().join("questions"));
13800        let home = dir.path().join("home");
13801        let mut state = run_state(RunStatus::Blocked);
13802        state.id = "20260101-000000-act4".to_owned();
13803        state.save_under(&home).unwrap();
13804        let mut t = held_task_with(&state.id);
13805        t.status = TaskStatus::Running;
13806        queue.put(&mut t).unwrap();
13807        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13808        q.cwd = Some(dir.path().display().to_string());
13809        questions.put(&mut q).unwrap();
13810
13811        // While the task runs the daemon will not act, so the waiter still
13812        // delivers the word to the dead asker's seat ...
13813        let running = queue.get(&t.id).unwrap();
13814        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13815        assert!(matches!(
13816            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13817            crate::waiter::Action::Deliver(_)
13818        ));
13819        // ... and the daemon waits while the task runs, then applies once.
13820        apply_task_choice_actions(&queue, &questions, &home);
13821        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13822        let mut back = queue.get(&t.id).unwrap();
13823        back.hold_machine(Some("later".into()));
13824        queue.put(&mut back).unwrap();
13825        apply_task_choice_actions(&queue, &questions, &home);
13826        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13827        let mut again = queue.get(&t.id).unwrap();
13828        again.hold_machine(Some("again".into()));
13829        queue.put(&mut again).unwrap();
13830        apply_task_choice_actions(&queue, &questions, &home);
13831        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13832    }
13833}