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    for q in questions.list_for_effects().into_iter().filter(|q| {
1222        q.status.open()
1223            && q.node == crate::conduct::NODE
1224            && q.choices
1225                .iter()
1226                .any(|c| crate::choice_effect::describe(q, c).is_none())
1227    }) {
1228        let _ = questions.update(&q.id, |current| {
1229            if current.status.open() {
1230                crate::choice_effect::executable_conductor(current);
1231                if let Some(deputy) = &mut current.deputy {
1232                    deputy.brief = crate::deputy::brief(
1233                        &current.run,
1234                        &current.detail,
1235                        &current.choices,
1236                        &current.actions,
1237                    );
1238                }
1239            }
1240            Ok(())
1241        });
1242    }
1243}
1244
1245/// Apply answered typed choices. Only the daemon calls this in production;
1246/// deputies settle the question and never execute its actions.
1247pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1248    apply_maintenance_choices(queue, questions, home).await;
1249    apply_task_choice_actions(queue, questions, home);
1250}
1251
1252/// Apply bounded maintenance effects independently of question ownership: a
1253/// release watcher need not have a queue task, and a predecessor is another run.
1254async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1255    for q in questions.list_for_effects() {
1256        // Read again under the same fence used by explicit settlement.
1257        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1258            continue;
1259        };
1260        let Ok(q) = questions.get_for_effects(&q.id) else {
1261            continue;
1262        };
1263        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1264            continue;
1265        };
1266        // Receipt paths use question IDs, whose format is independent of run
1267        // IDs. Apply the question store's filename safety rule to both eras.
1268        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1269            continue;
1270        }
1271        if queue.list().iter().any(|task| {
1272            (task.id == q.run
1273                || task.runs.contains(&q.run)
1274                || q.routed_task.as_deref() == Some(&task.id))
1275                && task.stale_question(&q)
1276        }) {
1277            continue;
1278        }
1279        if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1280            let tasks = queue.list();
1281            let owner = crate::task_chat::task_of(&q, &tasks);
1282            if let Some(owner) = owner
1283                && q.routed_task
1284                    .as_deref()
1285                    .is_none_or(|routed| routed == owner)
1286            {
1287                let result = crate::base_recovery_control::recover(
1288                    queue,
1289                    home,
1290                    crate::base_recovery_control::Request {
1291                        run: run.clone(),
1292                        head: stop.head.clone(),
1293                        actor: "decisions".into(),
1294                        request: q.id.clone(),
1295                        decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1296                        expected_stop: Some((stop.clone(), *episode)),
1297                    },
1298                )
1299                .await;
1300                if let Err(error) = result {
1301                    tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1302                    notices::raise_in(home, Notice::warn(
1303                        &format!("base-recovery:{}", q.id),
1304                        format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1305                    ).link(Link::Run { id: run.clone() }));
1306                }
1307            }
1308            continue;
1309        }
1310        let dir = home.join("choice-actions");
1311        if std::fs::create_dir_all(&dir).is_err() {
1312            continue;
1313        }
1314        let Ok(lock) = std::fs::OpenOptions::new()
1315            .create(true)
1316            .truncate(false)
1317            .write(true)
1318            .open(dir.join(format!("{}.lock", q.id)))
1319        else {
1320            continue;
1321        };
1322        if crate::pr_head::try_lock_file(&lock).is_err() {
1323            continue;
1324        }
1325        let fresh = !home
1326            .join("choice-actions")
1327            .join(format!("{}.json", q.id))
1328            .exists();
1329        let result = async {
1330            let receipt = dir.join(format!("{}.json", q.id));
1331            if receipt.exists() {
1332                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1333                anyhow::ensure!(
1334                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1335                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1336                );
1337                return Ok::<_, anyhow::Error>(());
1338            }
1339            // Never retry an uncertain external effect. The receipt is written
1340            // before calling gh, exactly like release_watch's rerun record.
1341            let record = |status: &str| -> anyhow::Result<()> {
1342                let tmp = receipt.with_extension("tmp");
1343                std::fs::write(
1344                    &tmp,
1345                    serde_json::to_vec(&serde_json::json!({
1346                        "action": action, "status": status,
1347                    }))?,
1348                )?;
1349                std::fs::rename(tmp, &receipt)?;
1350                Ok(())
1351            };
1352            let applied = async {
1353                match action {
1354                    ask::ChoiceAction::ResumeRun { run } => {
1355                        crate::resume::validate(home, run)?;
1356                        record("started")?;
1357                        let decided = q.answered_at.unwrap_or(q.asked_at);
1358                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1359                            crate::resume::validate_unqueued(home, run)?;
1360                            crate::resume::start(home, run.clone()).await?;
1361                        }
1362                    }
1363                    ask::ChoiceAction::ReleaseTask {
1364                        task,
1365                        held_at,
1366                        reason,
1367                    } => {
1368                        anyhow::ensure!(
1369                            queue.resolve_id(task)? == *task,
1370                            "task action requires an exact task ID"
1371                        );
1372                        let _claim = queue.claim(task)?;
1373                        let mut task = queue.get(task)?;
1374                        if task.action_applied(&q.id) {
1375                            return Ok(());
1376                        }
1377                        // Filing this conductor question temporarily wraps the
1378                        // original hold in a Blocked state. Restore only that
1379                        // exact blocker on the local copy before checking the
1380                        // hold binding; unrelated waits never authorize release.
1381                        if q.node == crate::conduct::NODE
1382                            && q.run == task.id
1383                            && task.status == TaskStatus::Blocked
1384                            && task.blocked_from == Some(TaskStatus::Held)
1385                            && task.blocked_by.as_slice() == [q.id.as_str()]
1386                        {
1387                            task.unblock(&q.id);
1388                        }
1389                        anyhow::ensure!(
1390                            task.status == TaskStatus::Held
1391                                && task.held_at == Some(*held_at)
1392                                && task.hold_reason.as_deref() == reason.as_deref()
1393                                && task
1394                                    .operator_decided_at
1395                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1396                            "task no longer has the hold this question names"
1397                        );
1398                        task.release_operator("choice", Some(&q.id));
1399                        task.mark_action_applied(&q.id);
1400                        queue.put(&mut task)?;
1401                    }
1402                    ask::ChoiceAction::AbandonRun { run } => {
1403                        record("started")?;
1404                        crate::driver::abandon_proven_dead(home, run)?;
1405                    }
1406                    ask::ChoiceAction::RerunChecks {
1407                        repo,
1408                        pr,
1409                        head,
1410                        runs,
1411                    } => {
1412                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1413                            .await?;
1414                    }
1415                    _ => unreachable!(),
1416                }
1417                Ok::<_, anyhow::Error>(())
1418            }
1419            .await;
1420            match applied {
1421                Ok(()) => record("applied"),
1422                Err(e) => {
1423                    record(&format!("refused or failed: {e:#}"))?;
1424                    Err(e)
1425                }
1426            }
1427        }
1428        .await;
1429        // Retire the originating blocker as well as the target operation.
1430        // A foreign resume leaves its issuer held instead of competing beside
1431        // the execution just started. Other successful maintenance lets the
1432        // original task retry its normal, guarded path.
1433        if home
1434            .join("choice-actions")
1435            .join(format!("{}.json", q.id))
1436            .exists()
1437            && let Some(listed) = task_of_question(&queue.list(), &q)
1438            && !listed.action_applied(&q.id)
1439            && let Ok(_claim) = queue.claim(&listed.id)
1440            && let Ok(mut origin) = queue.get(&listed.id)
1441        {
1442            if !origin.operator_held()
1443                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1444                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1445            {
1446                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1447                    origin.hold_machine(Some(format!(
1448                        "Maintenance choice {} settled; inspect its target before releasing this task",
1449                        q.id
1450                    )));
1451                } else {
1452                    origin.unblock(&q.id);
1453                }
1454            }
1455            origin.mark_action_applied(&q.id);
1456            let _ = queue.put(&mut origin);
1457        }
1458        if let Err(e) = result
1459            && fresh
1460        {
1461            notices::raise_in(
1462                home,
1463                Notice::warn(
1464                    &format!("action:{}", q.id),
1465                    format!("Choice action {} was not completed: {e:#}", q.id),
1466                )
1467                .link(if q.run_names_task() {
1468                    Link::Task { id: q.run.clone() }
1469                } else {
1470                    Link::Run { id: q.run.clone() }
1471                }),
1472            );
1473        }
1474    }
1475}
1476
1477/// Rerun the named failed workflow runs of a pull request, each at most once
1478/// per `request` (a question id, or a chat operation identity). The head,
1479/// lifecycle and failed state are re-read from the forge first; `started` is
1480/// called once those checks pass and before the first external call, and the
1481/// ledger entry is written before every `gh` call, so an uncertain result is
1482/// never repeated automatically.
1483pub(crate) async fn rerun_checks_once(
1484    home: &Path,
1485    request: &str,
1486    repo: &Path,
1487    pr: &str,
1488    head: &str,
1489    runs: &[String],
1490    started: impl FnOnce() -> anyhow::Result<()>,
1491) -> anyhow::Result<()> {
1492    use crate::release_watch::{GhForge, ReleaseForge};
1493    anyhow::ensure!(
1494        !runs.is_empty()
1495            && runs.len() <= 20
1496            && runs
1497                .iter()
1498                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1499            && !pr.starts_with('-'),
1500        "invalid rerun targets"
1501    );
1502    let snap = GhForge.snapshot(repo, pr).await?;
1503    anyhow::ensure!(
1504        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1505        "pull request head or lifecycle changed"
1506    );
1507    anyhow::ensure!(
1508        runs.iter().all(|r| snap
1509            .checks
1510            .iter()
1511            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1512        "named workflow is no longer failed on this pull request"
1513    );
1514    started()?;
1515    let dir = home.join("choice-actions");
1516    std::fs::create_dir_all(&dir)?;
1517    let rerun_lock = std::fs::OpenOptions::new()
1518        .create(true)
1519        .truncate(false)
1520        .write(true)
1521        .open(dir.join("reruns.lock"))?;
1522    crate::pr_head::try_lock_file(&rerun_lock)?;
1523    let ledger = dir.join("reruns.json");
1524    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1525        serde_json::from_slice(&std::fs::read(&ledger)?)?
1526    } else {
1527        Default::default()
1528    };
1529    for run in runs {
1530        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1531        if !recorded.insert(key) {
1532            continue;
1533        }
1534        let tmp = ledger.with_extension("tmp");
1535        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1536        std::fs::rename(tmp, &ledger)?;
1537        GhForge.rerun(repo, run).await?;
1538    }
1539    Ok(())
1540}
1541
1542/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1543///
1544/// Runs on every poll before the conductor looks at the queue. The task is
1545/// re-read under its claim, so a task somebody completed or held by hand in
1546/// the meantime is judged on what it is now. `Resume` releases the task and
1547/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1548/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1549/// ordinary `unfinished_run` logic resumes that same run.
1550pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1551    let tasks = queue.list();
1552    for q in questions.list_for_effects() {
1553        // Read again under the same fence used by explicit settlement.
1554        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1555            continue;
1556        };
1557        let Ok(q) = questions.get_for_effects(&q.id) else {
1558            continue;
1559        };
1560        // Dismissal is committed by the question writer, never a resume.
1561        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1562            continue;
1563        }
1564        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1565            continue;
1566        }
1567        let Some(listed) = task_of_question(&tasks, &q) else {
1568            if q.node == land::APPROVAL_NODE
1569                && q.resolution().as_deref().is_some_and(|choice| {
1570                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1571                })
1572            {
1573                notices::raise_in(
1574                    home,
1575                    Notice::warn(
1576                        &format!("repair-owner:{}", q.id),
1577                        format!(
1578                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1579                            q.run, q.run
1580                        ),
1581                    ).link(Link::Run { id: q.run.clone() }),
1582                );
1583            }
1584            continue;
1585        };
1586        if listed.action_applied(&q.id) {
1587            continue;
1588        }
1589        let Ok(_claim) = queue.claim(&listed.id) else {
1590            continue;
1591        };
1592        let Ok(mut task) = queue.get(&listed.id) else {
1593            continue;
1594        };
1595        // Work only on this local copy until the action can be committed.
1596        // In particular, a fresh lease below leaves the persisted task blocked.
1597        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1598            let blockers: Vec<_> = task
1599                .blocked_by
1600                .iter()
1601                .filter(|id| {
1602                    crate::queue::dependency(queue, questions, id)
1603                        == crate::queue::Dependency::Question(q.id.clone())
1604                })
1605                .cloned()
1606                .collect();
1607            if !blockers.is_empty() {
1608                for id in blockers {
1609                    task.unblock(&id);
1610                }
1611                let answer = match &q.answer {
1612                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1613                    None => String::new(),
1614                };
1615                task.record_answer(q.summary.clone(), answer);
1616            }
1617        }
1618        let language = language_of(&task, Path::new("."));
1619        let decision = decide_action(home, &task, &q, phrases(&language), |id| {
1620            RunState::load_under(id, home)
1621        });
1622        let ran = matches!(
1623            decision,
1624            ActionDecision::Resume(_)
1625                | ActionDecision::Requeue
1626                | ActionDecision::Hold
1627                | ActionDecision::Done
1628        );
1629        if ran && asker_may_still_read(questions, &q, home) {
1630            // The asking process or its seat can still take the word; act
1631            // once it has gone quiet. Bound on the remaining window: the
1632            // check is not atomic with the write below, so an asker that
1633            // takes the word in between (at most one poll, never more than
1634            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1635            // and `Task::actions_applied` under the claim keeps the action to
1636            // one application. The waiter does not deliver an answer that
1637            // carries an action (`waiter::decide_owned`), so it cannot race.
1638            continue;
1639        }
1640        let done = matches!(decision, ActionDecision::Done);
1641        // Resume owes an execution pass; only these task-local effects finish
1642        // in this write. Stale/refused actions never acquire an effect receipt.
1643        let completed = matches!(
1644            decision,
1645            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1646        );
1647        match decision {
1648            ActionDecision::Skip => continue,
1649            ActionDecision::Resume(run) => {
1650                task.release_operator("choice", Some(&q.id));
1651                task.resume_override = Some(crate::queue::OperatorResume {
1652                    question_id: q.id.clone(),
1653                    at: Timestamp::now(),
1654                    conductor_rehold: None,
1655                    forced: true,
1656                    pinned_run: Some(run),
1657                });
1658            }
1659            ActionDecision::Stale => {}
1660            ActionDecision::Requeue => {
1661                task.release_operator("choice-requeue", Some(&q.id));
1662                task.requeue();
1663            }
1664            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1665            ActionDecision::Done => task.succeed(),
1666            ActionDecision::Refuse(why) => {
1667                let _ =
1668                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1669                if task.operator_held() {
1670                    // A rejected answer does not release the operator's hold
1671                    // or reclassify it as recoverable by the conductor.
1672                    task.hold_reason = Some(match task.hold_reason.take() {
1673                        Some(reason) => format!("{reason}\n\n{why}"),
1674                        None => why,
1675                    });
1676                } else {
1677                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1678                    task.hold_machine(Some(why));
1679                }
1680                notices::raise(
1681                    Notice::warn(
1682                        &format!("action:{}", q.id),
1683                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1684                    )
1685                    .link(Link::Task {
1686                        id: task.id.clone(),
1687                    }),
1688                );
1689            }
1690        }
1691        task.mark_action_applied(&q.id);
1692        if completed {
1693            task.decision_effects.insert(
1694                q.id.clone(),
1695                format!("decision: {}", q.resolution().expect("answered action")),
1696            );
1697        }
1698        // The applied id travels with the transition, so a failed save loses
1699        // neither and the answer is acted on at the next poll.
1700        record(queue, &mut task);
1701        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1702            supersede_prior_runs(&task, home);
1703        }
1704        // Delivery is only a note of who has read the answer; the task's own
1705        // mark above is the authority. Best effort.
1706        let _ = questions.update(&q.id, |r| {
1707            r.answer_delivered = true;
1708            Ok(())
1709        });
1710    }
1711}
1712
1713/// Whether something may still read the answer to `q`: a fresh lease, or the
1714/// asking seat still listed as active in its run (its CLI can outlive the
1715/// `magi ask` that was killed).
1716fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1717    let now = Timestamp::now();
1718    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1719        return true;
1720    }
1721    q.node != crate::conduct::NODE
1722        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1723            s.seats_active()
1724                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1725        })
1726}
1727
1728/// Retire an unanswered conductor question after its task no longer refers to
1729/// it. Conductor questions use the task id in `Question::run`, so run-based
1730/// cleanup cannot observe a manual release or completion.
1731///
1732/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1733/// own question also carries a `run`, and a run id that happens to collide
1734/// with some task's id is not this loop's business — only a conductor
1735/// question actually uses the task id that way. One `Questions::list()` scan
1736/// is taken up front and matched against the in-memory task set, rather than
1737/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1738fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1739    let tasks = queue.list();
1740    let by_id: std::collections::BTreeMap<&str, &Task> =
1741        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1742    let referenced: Vec<&str> = tasks
1743        .iter()
1744        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1745        .collect();
1746
1747    for mut question in questions.list_for_effects() {
1748        if !question.status.open()
1749            || question.node != crate::conduct::NODE
1750            || questions.held_reply(&question.id)
1751        {
1752            continue;
1753        }
1754        // Keep questions a task still names, including when the reference
1755        // moved to a dependent task.
1756        // Preserve even ambiguous references: retiring a possibly referenced
1757        // question is unsafe until the operator disambiguates it.
1758        if referenced
1759            .iter()
1760            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1761        {
1762            continue;
1763        }
1764        let Some(task) = by_id.get(question.run.as_str()) else {
1765            continue;
1766        };
1767        question.abandon(format!(
1768            "task {} no longer waits for this answer",
1769            task.short()
1770        ));
1771        if let Err(e) = questions.put(&mut question) {
1772            tracing::warn!(
1773                "could not retire question {} for task {}: {e:#}",
1774                question.short(),
1775                task.short()
1776            );
1777        }
1778    }
1779}
1780
1781/// What a finished run tells the queue about the task it came from.
1782///
1783/// A struct rather than a fourth and fifth boolean argument: the two flags
1784/// answer different questions about the same run, and a call site passing
1785/// `(…, true, false)` is one transposition away from refunding attempts
1786/// forever.
1787#[derive(Debug, Clone, Copy)]
1788pub struct Verdict {
1789    /// Where the graph stopped.
1790    pub status: RunStatus,
1791    /// The run opened a pull request.
1792    pub left_pr: bool,
1793    /// At least one seat was lost to a rate limit.
1794    pub quota_hit: bool,
1795    /// The run parked at a node boundary because it was asked to.
1796    pub parked: bool,
1797    /// The run never produced a single candidate a judge could look at.
1798    ///
1799    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1800    /// still have another candidate worth judging, in which case the loss was
1801    /// not the reason nothing came of the run. This is `true` only when the
1802    /// implement wave ended with nothing viable at all.
1803    pub no_viable_candidates: bool,
1804}
1805
1806/// Record a finished run against the task it came from.
1807///
1808/// Kept pure and separate from the loop because this mapping *is* the retry
1809/// policy, and a policy that can only be exercised by spawning a graph is a
1810/// policy nobody checks. The table:
1811///
1812/// | run status                           | task becomes        | attempt spent |
1813/// |---------------------------------------|---------------------|---------------|
1814/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1815/// | `Merged`, `Ready`                      | `Done`               | yes          |
1816/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1817/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1818/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1819/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1820/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1821/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1822/// | `Blocked` with a PR                    | `Held`               | yes          |
1823/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1824/// | `VerifiedNoop`                          | `Held`               | yes          |
1825/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1826///
1827/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1828/// deliberately: every candidate agreeing there is nothing to write is not a
1829/// machine fact about a rate limit, it is an unverified claim about the
1830/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1831/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1832/// claim could be wrong (a misread instruction, a stale check), and closing
1833/// the task automatically on an implementer's say-so would be the exact
1834/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1835/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1836/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1837/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1838/// claim regardless of whether the one already-spent attempt is refunded, and
1839/// [`Task::release`] resets the count to zero anyway the moment a human looks
1840/// at the evidence and lets it run again.
1841///
1842/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1843/// twice, together. A quorum lost to rate limits is a property of the machine
1844/// and not of the task, so the attempt is refunded and a reset quota picks
1845/// the work up where it stopped — and that is just as true when every
1846/// implement seat lost the same race and `after_implement` bails with nothing
1847/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1848/// machine fact. The `no_viable_candidates` guard is what keeps that row
1849/// narrow: a `Failed` run that produced a real candidate which then lost for
1850/// some other reason still spends the attempt, exactly like the quorum lost
1851/// to judges that answered with the wrong shape is ordinary flakiness, and
1852/// refunding *that* takes the bound off the retry loop entirely: run e633
1853/// stalled with `quota: []` after two judges wrote unusable JSON, was
1854/// refunded, and the next attempt paid for a fresh hour-long implement wave
1855/// before it could fail the same way. `max_attempts` exists precisely so
1856/// that cannot repeat forever.
1857///
1858/// A non-terminal status means `execute` returned while the graph was still
1859/// mid-flight, which is a bug rather than a verdict; it is treated as a
1860/// failure so that a task cannot loop on it either.
1861///
1862/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1863/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1864pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1865    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1866}
1867
1868/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1869fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1870    // A parked run is the operator's own doing, and its work is intact on
1871    // disk. The task goes back in line with its attempt refunded so the next
1872    // loop resumes the same run - which `one_task` prefers over competing
1873    // again - and so that swapping the binary a few times cannot exhaust a
1874    // budget meant for agents that actually misbehaved.
1875    if verdict.parked {
1876        task.park(detail);
1877        return;
1878    }
1879    match verdict.status {
1880        RunStatus::Merged | RunStatus::Ready
1881            if task.pr_recovery.as_ref().is_some_and(|s| {
1882                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1883            }) =>
1884        {
1885            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()));
1886        }
1887        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1888        RunStatus::AlreadyInBase => task.already_landed(detail),
1889        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1890        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1891            task.stall(detail)
1892        }
1893        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1894        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1895        RunStatus::Blocked => task.fail(detail, max_attempts),
1896        RunStatus::VerifiedNoop => task.handed_off(detail),
1897        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1898    }
1899}
1900
1901/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1902/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1903/// itself has actually finished *and* its own last attempt is provably why:
1904/// this loads that run and requires `Merged`/`Ready` before touching
1905/// anything earlier in `runs`, since `Task::succeed` can also be called
1906/// directly on a task whose last attempt never landed at all.
1907///
1908/// Called right after whatever call set `task.status` to
1909/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1910/// `reclaim`'s, but also every other place a task can be closed by hand
1911/// without the loop ever settling it itself: `magi task done`
1912/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1913/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1914/// GitHub merge, say, exactly the workflow this repository's own
1915/// "Landing a run's winner by hand" documents — is just as much "this task's
1916/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1917/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1918/// forever, which is the exact backlog this status exists to clear. `pub`
1919/// for those two out-of-module callers; everything else about this stays
1920/// internal bookkeeping.
1921///
1922/// A run something is still actually driving is left alone: a
1923/// task cannot be `Done` while one of its *own* attempts is still in flight,
1924/// so a live one at this point can only be an unrelated process — a manual
1925/// `--resume` of this old, now-moot run — and rewriting under it would just
1926/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1927/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1928/// pair `run_report`/`run_detail` use for the same question elsewhere:
1929/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1930/// --resume` invoked by hand outside it, which `liveness` also checks via
1931/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1932/// (already terminal in some other way, or itself mid-run) is left untouched
1933/// too.
1934///
1935/// Best-effort, like the rest of this module's bookkeeping: a load or save
1936/// failure here is a `tracing::warn`, not a failed settle, and the next time
1937/// this same task's completion is recorded — or a daemon restart replays
1938/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1939/// separate reconciliation pass; if that gap ever matters in practice, one
1940/// can be added then.
1941///
1942/// `home` is a parameter, not the process-global [`crate::run::home`], for
1943/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1944/// calls this with `ui.home`, which is `crate::run::home()` in a real
1945/// process but a fixture's own directory under test — falling through to
1946/// the global there would read and write through whichever home some other
1947/// test in the same binary happened to pin into that `OnceLock` first, not
1948/// the run this call actually means.
1949pub fn supersede_prior_runs(task: &Task, home: &Path) {
1950    let now = Timestamp::now();
1951    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1952    // right behind a `Merged`/`Ready` verdict) from one set directly by
1953    // `magi task done`/its web equivalent/the conductor on a task whose last
1954    // recorded attempt never actually landed - that requires reading the
1955    // run itself, which is exactly what this does before trusting anything
1956    // in `runs` is safe to relabel.
1957    let last_run_succeeded = task
1958        .runs
1959        .last()
1960        .and_then(|id| RunState::load_under(id, home).ok())
1961        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1962    for id in task.superseded_attempts(last_run_succeeded) {
1963        let mut state = match RunState::load_under(id, home) {
1964            Ok(s) => s,
1965            Err(e) => {
1966                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1967                continue;
1968            }
1969        };
1970        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1971            continue;
1972        }
1973        let daemon_claims = is_working_on(home, id, now);
1974        if state.liveness(daemon_claims) == Liveness::Live {
1975            continue;
1976        }
1977        state.status = RunStatus::Superseded;
1978        if let Err(e) = state.save_under(home) {
1979            tracing::warn!("could not mark run {id} superseded: {e:#}");
1980        }
1981    }
1982}
1983
1984/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1985/// finish the moment it was called, because one of its earlier attempts was
1986/// still live then - a `magi run --resume` invoked by hand on an old run,
1987/// most likely.
1988///
1989/// That skip is correct at the time (rewriting under a run something is
1990/// still actively saving would just be undone), but a task only ever
1991/// reaches `Done` once, so without this nothing would ever look at it
1992/// again: if that manual process later ends anywhere other than
1993/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1994/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1995/// backlog this status exists to clear. Called on the same idle-only
1996/// cadence as [`janitor`], next to it rather than folded into it: this
1997/// walks `queue` and `janitor` never otherwise needs one.
1998///
1999/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
2000/// more than one attempt, every pass: each call is a handful of local file
2001/// reads bounded by that task's own attempt count, the same order of cost
2002/// [`clean::fold_due`] already pays scanning every run on disk on the same
2003/// cadence, and a task already fully resolved costs one failed liveness
2004/// check turned no-op the moment its lingering attempt is no longer live.
2005fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2006    for task in queue.list() {
2007        if task.status != TaskStatus::Done || task.runs.len() < 2 {
2008            continue;
2009        }
2010        supersede_prior_runs(&task, home);
2011    }
2012}
2013
2014/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
2015/// task ends up held.
2016///
2017/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
2018/// dead daemon never got back to) share this, so the two cannot drift into
2019/// disagreeing about which held tasks get a diagnostic.
2020fn settle_and_diagnose(
2021    task: &mut Task,
2022    verdict: Verdict,
2023    detail: &str,
2024    max_attempts: usize,
2025    state: &RunState,
2026) {
2027    let p = phrases(&state.config.graph.language);
2028    // Shared by normal completion and crash recovery, under the task claim.
2029    // No new attempt can own the task until the old driver has exited.
2030    if let Some(d) = &state.merge_decision {
2031        use crate::merge_decision as md;
2032        if task
2033            .execution_runs()
2034            .last()
2035            .is_some_and(|id| id != &state.id)
2036        {
2037            return;
2038        }
2039        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2040            task.succeed();
2041        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2042            if state.liveness(false) != Liveness::Dead {
2043                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2044                return;
2045            }
2046            let replacement = md::Replacement {
2047                question: d.question.clone(),
2048                run: state.id.clone(),
2049                pr: d.target.pr.clone(),
2050                agent: agent.to_owned(),
2051                context: format!(
2052                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2053                    d.target.pr,
2054                    state.id,
2055                    serde_json::to_string(&state.reviews).unwrap_or_default()
2056                ),
2057            };
2058            task.requeue();
2059            task.pr_recovery = None;
2060            task.review_of = None;
2061            task.replacement = Some(replacement);
2062        } else {
2063            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2064                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2065            } 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())) }));
2066        }
2067        task.mark_action_applied(&d.question);
2068        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2069            task.decision_effects
2070                .insert(d.question.clone(), format!("decision: {}", d.choice));
2071        }
2072        if let Some(pass) = state.passes.last() {
2073            task.record_pass_at(
2074                &state.id,
2075                pass.index,
2076                Some(pass.started_at),
2077                task.attempts,
2078                None,
2079            );
2080        }
2081        return;
2082    }
2083    if let Some(replacement) = &task.replacement
2084        && !state.parked
2085        && state.resource_block.is_none()
2086        && (state.viable().is_empty()
2087            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2088    {
2089        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)));
2090        return;
2091    }
2092    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2093        let mut agents: Vec<_> = state
2094            .quota
2095            .iter()
2096            .filter(|q| {
2097                q.cause == crate::agent::QuotaCause::Authentication
2098                    && state
2099                        .passes
2100                        .last()
2101                        .is_none_or(|pass| q.at >= pass.started_at)
2102            })
2103            .map(|q| q.agent.as_str())
2104            .collect();
2105        agents.sort_unstable();
2106        agents.dedup();
2107        if !agents.is_empty() {
2108            task.stall(detail);
2109            task.notice_cause("agent-authentication", None, None);
2110            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2111            return;
2112        }
2113    }
2114    let attempts_before = task.attempts;
2115    // A run that stopped because a shared resource stayed busy was never a
2116    // failure of the task or of an agent. Earlier nodes may have run; only
2117    // the blocked operation lacks a result. The attempt is
2118    // refunded and the task is held by the machine, under a reason `triage`
2119    // can re-check, so the same run resumes with the same agents once the
2120    // resource is free. A park request still wins (it is the operator's).
2121    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2122        task.notice_cause(
2123            &format!("resource:{}:{}", block.kind, block.node),
2124            None,
2125            None,
2126        );
2127        task.last_error = Some(detail.to_owned());
2128        task.diagnostic = None;
2129        task.attempts = task.attempts.saturating_sub(1);
2130        if block.kind == "agent authentication" {
2131            task.hold_machine(Some(format!(
2132                "[authentication] {}; no attempt was spent",
2133                block.detail
2134            )));
2135        } else if block.kind == "agent usage limit" {
2136            // Usage limits keep the existing cooldown-and-resume policy.
2137            if let Some(agent) = &state.config.graph.selected_implementer {
2138                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.")));
2139            } else {
2140                task.status = TaskStatus::Failed;
2141                task.last_error = Some(block.detail.clone());
2142            }
2143        } else if block.kind == "disk pressure" {
2144            task.hold_machine(Some(format!(
2145                "{}{}",
2146                crate::disk::RUNNING_PRESSURE,
2147                block.detail
2148            )));
2149        } else {
2150            task.hold_machine(Some(format!(
2151                "{}{}; no attempt was spent; resume to retry the affected operation",
2152                crate::cache::RESOURCE_HOLD,
2153                block.description()
2154            )));
2155        }
2156        if let Some(pass) = state.passes.last() {
2157            task.record_pass_at(
2158                &state.id,
2159                pass.index,
2160                Some(pass.started_at),
2161                attempts_before,
2162                None,
2163            );
2164        }
2165        return;
2166    }
2167    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2168        state.parked
2169            && state.status == RunStatus::Landing
2170            && state
2171                .pr_pushed_head
2172                .as_ref()
2173                .is_none_or(|h| h == &hold.head)
2174            && task.execution_runs().last() == Some(&state.id)
2175    }) {
2176        // Settlement and crash recovery share this idempotency key. A later
2177        // explicit resume is a new pass and may refund its own attempt once.
2178        let pass = state.passes.last().map_or(0, |p| p.index);
2179        if !task
2180            .passes
2181            .iter()
2182            .any(|p| p.run == state.id && p.pass_index == pass)
2183        {
2184            task.attempts = task.attempts.saturating_sub(1);
2185        }
2186        task.hold_machine(Some(format!(
2187            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2188            hold.question
2189        )));
2190        task.last_error = Some(detail.to_owned());
2191        task.diagnostic = None;
2192        task.record_pass_at(
2193            &state.id,
2194            pass,
2195            state.passes.last().map(|p| p.started_at),
2196            attempts_before,
2197            Some(crate::run::ParkCause::Question),
2198        );
2199        return;
2200    }
2201    let unresolved = task.hold_notice_cause.clone();
2202    if state.base_sync_blocked() {
2203        // No automatic retry may turn a retained sync stop into a new competition.
2204        task.hold_machine(Some(detail.to_owned()));
2205        task.last_error = Some(detail.to_owned());
2206    } else if !verdict.parked
2207        && task
2208            .pr_recovery
2209            .as_ref()
2210            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2211        && matches!(
2212            verdict.status,
2213            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2214        )
2215    {
2216        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2217            task.succeed();
2218        } else {
2219            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()));
2220        }
2221    } else if !verdict.parked
2222        && task.pr_recovery.is_some()
2223        && matches!(
2224            verdict.status,
2225            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2226        )
2227        && !verdict.quota_hit
2228    {
2229        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.")));
2230    } else {
2231        settle_in(task, verdict, detail, max_attempts, p);
2232    }
2233    if !verdict.parked
2234        && !verdict.quota_hit
2235        && matches!(
2236            verdict.status,
2237            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2238        )
2239    {
2240        task.recovery_failed(state);
2241    }
2242    if state.prep_failure.is_some() {
2243        // Minting a run whose candidates could not be prepared is not work
2244        // on a newly approved attempt. Keep the unresolved outcome anchor.
2245        task.hold_notice_cause = unresolved;
2246        task.startup_notice_cause("startup-candidates");
2247    }
2248    // Written here, where the refund (or not) is decided, so the history is a
2249    // fact and not a later guess from the run's status.
2250    if let Some(pass) = state.passes.last() {
2251        let parked = match &pass.end {
2252            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2253            _ => None,
2254        };
2255        task.record_pass_at(
2256            &state.id,
2257            pass.index,
2258            Some(pass.started_at),
2259            attempts_before,
2260            parked,
2261        );
2262    }
2263    if task.status == TaskStatus::Held {
2264        if state.base_sync_blocked() {
2265            task.base_sync_notice(state);
2266        } else if state.prep_failure.is_none() {
2267            task.notice_cause(
2268                label(verdict.status),
2269                Some(&state.id),
2270                state.passes.last().map(|p| p.index),
2271            );
2272        }
2273        task.diagnostic = diagnostic(state);
2274        note_open_question(task, &state.id, p);
2275    }
2276}
2277
2278/// If `task` is held with a `magi ask` question still open on `run`, name the
2279/// question in [`Task::hold_reason`] rather than leaving the hold reading
2280/// only [`describe`]'s run summary.
2281///
2282/// This is the shape task 20260928-191407-05fd left underspecified: an
2283/// implementer settled a verified no-op and filed a question for the
2284/// operator, and the hold that followed said nothing about the question
2285/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2286/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2287/// marker) and must keep seeing it unchanged.
2288///
2289/// Best-effort: an unreadable question store must not stop a run from
2290/// settling, so this is a no-op rather than a propagated error when
2291/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2292fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2293    let Some(home) = crate::run::try_home() else {
2294        return;
2295    };
2296    let open = Questions::at(home.join("questions")).open_for(run);
2297    let Some(q) = open.first() else {
2298        return;
2299    };
2300    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2301    decisions.sort_unstable();
2302    task.notice_cause(
2303        &format!("questions:{}", decisions.join(",")),
2304        Some(run),
2305        None,
2306    );
2307    let base = task.hold_reason.clone().unwrap_or_default();
2308    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2309}
2310
2311/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2312/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2313/// by some other means entirely, like a manual `magi run` resume that
2314/// finishes the graph outside the queue's bookkeeping.
2315///
2316/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2317/// `settle` is separate from `attempt`: a task recovered this way must land
2318/// exactly where a live daemon would have put it — the same policy table,
2319/// not a second one that quietly drifts from it — and that is only checkable
2320/// without spawning a real run.
2321fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2322    match last_run {
2323        Some(state) => {
2324            let verdict = Verdict {
2325                status: state.status,
2326                left_pr: state.pr.is_some(),
2327                quota_hit: state.quota.iter().any(|loss| {
2328                    state
2329                        .passes
2330                        .last()
2331                        .is_none_or(|pass| loss.at >= pass.started_at)
2332                }),
2333                parked: state.parked,
2334                no_viable_candidates: state.viable().is_empty(),
2335            };
2336            let detail = format!(
2337                "{}{}",
2338                phrases(&state.config.graph.language).recovered_running,
2339                describe(&state)
2340            );
2341            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2342        }
2343        None => {
2344            // No run, so no config of its own: `language` is the task's
2345            // repository's setting, read by the caller.
2346            let why = phrases(language).no_run_to_recover;
2347            task.last_error = Some(why.to_owned());
2348            // The phone shows `hold_reason`, so a task held by the machine
2349            // says why there too and not only in `last_error`.
2350            task.notice_cause("missing-run", None, None);
2351            task.hold_machine(Some(why.to_owned()));
2352        }
2353    }
2354}
2355
2356/// Find every task left at `running` that no live process is actually
2357/// driving, and settle each one against whatever its last run became.
2358///
2359/// # Why a claim is proof, not a guess
2360///
2361/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2362/// `running`, and the guard is held for the task's whole time in that status:
2363/// `attempt` does not return, and the loop does not move past the scope
2364/// holding the claim, until the run has settled. So a `running` task whose
2365/// lock is gone cannot have a live owner — this process or any other —
2366/// without needing a staleness threshold or a pid check the way
2367/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2368/// task that never got as far as `running` at all. Taking the claim here is
2369/// the whole test: it either fails, because something really does hold it
2370/// and the task is left alone, or it succeeds, which is the proof — and it is
2371/// kept for the rest of the decision so nothing else can start a competing
2372/// run while this one is being written.
2373///
2374/// Called on every poll, not only at startup, for the reason
2375/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2376/// keep noticing this, not only on the one morning it happened to restart.
2377fn reclaim_orphaned_running(
2378    queue: &Queue,
2379    max_attempts: usize,
2380    live_workers: &std::collections::BTreeSet<String>,
2381) -> Vec<String> {
2382    let mut reclaimed = Vec::new();
2383    for listed in queue.list() {
2384        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2385            continue;
2386        }
2387        let Ok(_claim) = queue.claim(&listed.id) else {
2388            continue;
2389        };
2390        // Re-read under the claim: a release or an edit landed by a human
2391        // between the listing above and the claim just taken must not be
2392        // clobbered by a decision based on the stale copy.
2393        let Ok(mut task) = queue.get(&listed.id) else {
2394            continue;
2395        };
2396        if task.status != TaskStatus::Running {
2397            continue;
2398        }
2399        let last_run = task
2400            .execution_runs()
2401            .last()
2402            .and_then(|id| RunState::load(id).ok());
2403        // `execute` normally abandons a run's own open questions the moment
2404        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2405        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2406        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2407        // with the question still `open`, because the process died before
2408        // reaching that call. `reclaim` itself stays pure on purpose (see its
2409        // own doc), so the same cleanup runs here instead, against the run
2410        // this reclaim is already reading. `settle_run` costs nothing when
2411        // `execute` already got there first.
2412        if let Some(state) = &last_run
2413            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2414        {
2415            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2416        }
2417        let language = if last_run.is_none() {
2418            language_of(&task, Path::new("."))
2419        } else {
2420            String::new()
2421        };
2422        reclaim(&mut task, last_run, max_attempts, &language);
2423        if task.status == TaskStatus::Done {
2424            supersede_prior_runs(&task, &crate::run::home());
2425        }
2426        record(queue, &mut task);
2427        reclaimed.push(task.id.clone());
2428    }
2429    reclaimed
2430}
2431
2432/// Find every run whose `run.json` is provably dead — every seat it still
2433/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2434/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2435/// not merely "no daemon claims it" — and fail it, clearing the leftover
2436/// active seats so the run stops reading as `implementing` (or whichever
2437/// node) forever.
2438///
2439/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2440/// `running`, using whatever `run.json` already says — but nothing in that
2441/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2442/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2443/// never got back to sits exactly where it was left: `active` full of seats
2444/// nobody will ever answer for, `status` stuck on whatever node was in
2445/// flight. `magi show` already tells an operator this in prose (`no live
2446/// daemon claims this run right now`); this is what makes that fact durable
2447/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2448/// stay stuck once nothing is driving it.
2449///
2450/// Runs on every poll, not only at startup, for the reason
2451/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2452/// daemon up for days must keep noticing a run some other, now-dead, daemon
2453/// left behind just as readily as one it trips over on the way up.
2454///
2455/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2456/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2457/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2458/// `runs` directory instead: `home` here is a parameter precisely so a test
2459/// can point it away from the operator's real history (see [`drive`]'s own
2460/// doc), and a scan that fell through to the global home anyway would walk
2461/// whichever directory some *other* process or test pinned into that
2462/// `OnceLock` first — mutating runs this call was never handed.
2463fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2464    reclaim_abandoned_runs_with(
2465        home,
2466        now,
2467        crate::proc::pid_status,
2468        crate::proc::process_started_at,
2469    )
2470}
2471
2472/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2473/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2474/// for the identical reason: this sweep's real damage (wiping a run's active
2475/// seats and failing it) has to be provable against an injected answer in a
2476/// test, not just the real process table.
2477fn reclaim_abandoned_runs_with<F, G>(
2478    home: &Path,
2479    now: Timestamp,
2480    query: F,
2481    identity: G,
2482) -> Vec<String>
2483where
2484    F: Fn(u32) -> Option<bool>,
2485    G: Fn(u32) -> Option<String>,
2486{
2487    let mut abandoned = Vec::new();
2488    for entry in std::fs::read_dir(home.join("runs"))
2489        .into_iter()
2490        .flatten()
2491        .flatten()
2492    {
2493        let id = entry.file_name().to_string_lossy().into_owned();
2494        if !crate::run::is_run_id(&id) {
2495            continue;
2496        }
2497        // Serialize the proof and save with claims and takeover: a new
2498        // execution must not be overwritten after the liveness observation.
2499        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2500            continue;
2501        };
2502        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2503        // that module's docs for why a run this cannot parse is left alone
2504        // rather than guessed at. A different schema number is not that: this
2505        // touches only `status` and `active`, never a field whose meaning a
2506        // schema bump changed, so an old record's values serve this exactly
2507        // as well as a current one's (see `clean::read_state`'s own doc for
2508        // the same reasoning applied to folding).
2509        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2510            continue;
2511        };
2512        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2513            continue;
2514        };
2515        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2516            continue;
2517        }
2518        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2519        // it", which is also the normal, healthy shape of a manual `magi
2520        // run` / `magi review` sharing this same home — this scan walks
2521        // every run on disk, not only ones this daemon itself started. Such
2522        // a run's active seats can legitimately sit past their own timeout
2523        // for a little while (the CLI finishing up, its result still being
2524        // collected) without the process driving it having died. `liveness`
2525        // is what actually tells the two apart, by corroborating
2526        // `driver_pid` against the process it names — see its own doc. Only
2527        // its strongest, provable answer licenses wiping this run's active
2528        // seats and failing it out from under whatever is still running it.
2529        let daemon_claims = is_working_on(home, &id, now);
2530        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2531            != crate::run::Liveness::Dead
2532        {
2533            continue;
2534        }
2535        state.abandon("daemon");
2536        if let Err(e) = state.save_under(home) {
2537            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2538            continue;
2539        }
2540        // This run never passes through `Runner::execute` again, so its end
2541        // is announced here.
2542        if let Some(notice) = notices::run_ended(&state) {
2543            notices::raise_in(home, notice);
2544        }
2545        // The seat that asked is gone for good now, exactly like any other
2546        // door `graph::Runner::settle_questions` closes the moment `status`
2547        // lands somewhere non-resumable - see that method's own doc. Nothing
2548        // else reaches this one before the next `janitor()` startup pass
2549        // (`clean::abandon_settled_questions`), and a daemon that stays up
2550        // for days must not leave an open question badging the operator
2551        // until it happens to restart.
2552        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2553            tracing::warn!("abandon questions for {id}: {e:#}");
2554        }
2555        abandoned.push(id);
2556    }
2557    abandoned
2558}
2559
2560#[derive(Debug, Clone, Serialize, Deserialize)]
2561struct TaskWorker {
2562    opts: Opts,
2563    queue: PathBuf,
2564    task: String,
2565    #[serde(default)]
2566    lane: PermitKind,
2567    #[serde(default)]
2568    standalone: bool,
2569}
2570
2571fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2572    Ok(crate::worker::active(home)?
2573        .into_iter()
2574        .filter(|job| job.kind == "task")
2575        .collect())
2576}
2577
2578fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2579    task_jobs(home)?
2580        .into_iter()
2581        .filter_map(
2582            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2583                Ok(request) if !request.standalone => Some(Ok(job)),
2584                Ok(_) => None,
2585                Err(error) => Some(Err(error.into())),
2586            },
2587        )
2588        .collect()
2589}
2590
2591/// Whether an independent scheduler can be controlled without its web parent.
2592#[must_use]
2593pub fn managed(home: &Path) -> bool {
2594    match crate::worker::active(home) {
2595        Err(error) => {
2596            tracing::error!("cannot determine scheduler ownership: {error:#}");
2597            true
2598        }
2599        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2600        Ok(_) => {
2601            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2602                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2603        }
2604    }
2605}
2606
2607/// Start a detached, singleton scheduler using this executable generation.
2608pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2609    anyhow::ensure!(
2610        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2611        "the scheduler is stopping; wait for retirement before starting it again"
2612    );
2613    crate::worker::spawn(
2614        home,
2615        "scheduler",
2616        "scheduler",
2617        serde_json::to_value(opts.absolute()?)?,
2618    )
2619    .await
2620}
2621
2622fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2623    home.join("worker-parks").join(format!("{}.json", job.id))
2624}
2625
2626fn request_task_park(
2627    home: &Path,
2628    job: &crate::worker::Job,
2629    cause: crate::run::ParkCause,
2630) -> Result<()> {
2631    let path = park_request_path(home, job);
2632    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2633    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2634    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2635}
2636
2637/// Stop dispatch immediately; only an explicit park reaches existing workers.
2638pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2639    if control == crate::worker::Control::Park {
2640        for job in owned_task_jobs(home)? {
2641            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2642        }
2643    }
2644    crate::worker::request(home, "scheduler", control)
2645}
2646
2647/// Replace the scheduler, leaving all active task and conversation jobs alone.
2648pub async fn restart_detached(home: &Path) -> Result<()> {
2649    let active = crate::worker::active(home)?;
2650    let prior = active.into_iter().find(|job| job.kind == "scheduler");
2651    if prior.is_none() && !managed(home) {
2652        return Ok(());
2653    }
2654    let opts: Opts = match prior {
2655        Some(job) => serde_json::from_value(job.payload)?,
2656        None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2657    };
2658    request_control(home, crate::worker::Control::Stop)?;
2659    loop {
2660        let reserved = crate::worker::active(home)?
2661            .iter()
2662            .any(|job| job.kind == "scheduler");
2663        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2664            break;
2665        }
2666        tokio::time::sleep(Duration::from_millis(100)).await;
2667    }
2668    spawn_detached(home, &opts).await?;
2669    Ok(())
2670}
2671
2672/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2673pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2674    let opts: Opts = serde_json::from_value(payload)?;
2675    let _ = home;
2676    serve_until(opts, Stop::new()).await
2677}
2678
2679/// Execute and settle one task with the queue claim owned by this process.
2680pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2681    let request: TaskWorker = serde_json::from_value(payload)?;
2682    let queue = Queue::at(request.queue);
2683    let key = format!("task:{}", request.task);
2684    let job = task_jobs(home)?
2685        .into_iter()
2686        .find(|job| job.key == key)
2687        .context("task worker reservation is missing")?;
2688    let park_path = park_request_path(home, &job);
2689    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2690    // our durable reservation. Never execute before that ownership hand-off.
2691    let _claim = loop {
2692        match queue.claim(&request.task) {
2693            Ok(claim) => break claim,
2694            // Only contention (the claim file exists) is worth waiting out; an
2695            // I/O failure must end this worker instead of pinning its lane.
2696            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2697                return Err(e.context("claim the task for its worker"));
2698            }
2699            Err(_) => {
2700                sweep_stale_claims(&queue, STALE_CLAIM);
2701                tokio::time::sleep(Duration::from_millis(50)).await;
2702            }
2703        }
2704    };
2705    let mut task = queue.get(&request.task)?;
2706    if !task.status.runnable()
2707        || (!request.standalone
2708            && request.lane
2709                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2710    {
2711        return Ok(());
2712    }
2713    let stop = Stop::new();
2714    let watcher = {
2715        let home = home.to_path_buf();
2716        let stop = stop.clone();
2717        let park_path = park_path.clone();
2718        tokio::spawn(async move {
2719            loop {
2720                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2721                    let cause = std::fs::read(&park_path)
2722                        .ok()
2723                        .and_then(|body| serde_json::from_slice(&body).ok())
2724                        .unwrap_or(crate::run::ParkCause::Operator);
2725                    stop.park(cause);
2726                    return;
2727                }
2728                tokio::time::sleep(Duration::from_millis(200)).await;
2729            }
2730        })
2731    };
2732    let quota = if request.standalone {
2733        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2734    } else {
2735        let status = Arc::new(Mutex::new(Status::new()));
2736        Box::pin(attempt(
2737            &request.opts,
2738            &queue,
2739            &status,
2740            &stop,
2741            crate::graph::Pause::new(),
2742            &mut task,
2743        ))
2744        .await
2745    };
2746    watcher.abort();
2747    let _ = std::fs::remove_file(park_path);
2748    persist_cooldown(home, &quota).await?;
2749    Ok(())
2750}
2751
2752/// Launch the standalone task worker with a claim-to-reservation handoff.
2753/// Returns only after the worker owns a durable execution reservation.
2754pub async fn spawn_claimed(
2755    home: &Path,
2756    opts: &Opts,
2757    queue: &Queue,
2758    task: &Task,
2759    claim: crate::queue::Claim,
2760) -> Result<crate::worker::Job> {
2761    let request = TaskWorker {
2762        opts: opts.absolute()?,
2763        queue: std::path::absolute(queue.root())?,
2764        task: task.id.clone(),
2765        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2766        standalone: true,
2767    };
2768    let job = crate::worker::spawn(
2769        home,
2770        "task",
2771        &format!("task:{}", task.id),
2772        serde_json::to_value(request)?,
2773    )
2774    .await?;
2775    drop(claim);
2776    Ok(job)
2777}
2778
2779/// Transfer a standalone caller's claim only after the detached worker is live,
2780/// then follow that worker to its final (non-automatically-retrying) outcome.
2781pub async fn run_detached_claimed(
2782    opts: &Opts,
2783    queue: &Queue,
2784    task: &mut Task,
2785    claim: crate::queue::Claim,
2786) -> Result<()> {
2787    let home = crate::run::home();
2788    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2789    loop {
2790        // Reconcile execution leases even without a scheduler. A dead worker
2791        // must become a reported failure, never an infinite persisted wait.
2792        crate::worker::active(&home)?;
2793        let current = crate::worker::get(&home, &job.id)?;
2794        if matches!(
2795            current.status,
2796            crate::worker::Status::Finished | crate::worker::Status::Failed
2797        ) {
2798            *task = queue.get(&task.id)?;
2799            anyhow::ensure!(
2800                current.status != crate::worker::Status::Failed,
2801                "task worker failed: {}",
2802                current.result.as_deref().unwrap_or("unknown failure")
2803            );
2804            return Ok(());
2805        }
2806        tokio::time::sleep(Duration::from_millis(200)).await;
2807    }
2808}
2809
2810async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2811    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2812        let _lease = loop {
2813            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2814                break lease;
2815            }
2816            tokio::time::sleep(Duration::from_millis(10)).await;
2817        };
2818        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2819            let path = home.join("task-quota-cooldown.json");
2820            let temporary = path.with_extension("json.tmp");
2821            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2822            std::fs::rename(temporary, path)?;
2823        }
2824    }
2825    Ok(())
2826}
2827
2828fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2829    match std::fs::read(home.join("task-quota-cooldown.json")) {
2830        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2831        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2832        Err(error) => Err(error.into()),
2833    }
2834}
2835
2836/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2837///
2838/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2839/// sets, so there is one loop body rather than two that drift apart the first
2840/// time the retry policy changes on only one of them.
2841pub async fn serve(opts: Opts) -> Result<()> {
2842    tracing::info!(
2843        "automatic update and restart requires magi web; standalone serve does not restart"
2844    );
2845    serve_until(opts, Stop::new()).await
2846}
2847
2848/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2849///
2850/// A stop retires dispatch promptly, including while a worker launch is being
2851/// acknowledged. Already reserved workers own their attempts independently and
2852/// finish with their started executable. Explicit park additionally forwards
2853/// durable park requests; neither scheduler retirement nor update does so.
2854///
2855/// While the queue is empty the stop is honoured within one wakeup rather than
2856/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2857/// caller that taps stop does not sit through the remainder of a sleep.
2858pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2859    let opts = opts.absolute()?;
2860    let home = crate::run::home();
2861    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2862        .context("another scheduler already owns this home")?;
2863    if let Some(reading) = read_status(&home)
2864        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2865    {
2866        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2867    }
2868    if !crate::worker::active(&home)?
2869        .iter()
2870        .any(|job| job.kind == "scheduler")
2871    {
2872        crate::worker::clear_control(&home, "scheduler")?;
2873    }
2874    std::fs::write(
2875        home.join("scheduler-options.json"),
2876        serde_json::to_vec(&opts)?,
2877    )?;
2878    let control = {
2879        let home = home.clone();
2880        let stop = stop.clone();
2881        tokio::spawn(async move {
2882            loop {
2883                match crate::worker::control(&home, "scheduler").ok().flatten() {
2884                    Some(crate::worker::Control::Park) => {
2885                        let _ = request_control(&home, crate::worker::Control::Park);
2886                        stop.park(crate::run::ParkCause::Operator);
2887                        break;
2888                    }
2889                    Some(crate::worker::Control::Stop) => {
2890                        stop.stop();
2891                        break;
2892                    }
2893                    None => {}
2894                }
2895                tokio::time::sleep(Duration::from_millis(100)).await;
2896            }
2897        })
2898    };
2899    let signal = {
2900        let stop = stop.clone();
2901        tokio::spawn(async move {
2902            if tokio::signal::ctrl_c().await.is_ok() {
2903                stop.stop();
2904                tracing::info!("scheduler shutdown requested; independent workers continue");
2905            }
2906        })
2907    };
2908
2909    let worktrees_root = opts
2910        .worktrees_root
2911        .clone()
2912        .unwrap_or_else(crate::run::default_worktree_root);
2913    let outcome = drive(
2914        &opts,
2915        &Queue::open(),
2916        &status_path(),
2917        &crate::run::home(),
2918        &worktrees_root,
2919        &stop,
2920    )
2921    .await;
2922
2923    signal.abort();
2924    control.abort();
2925    outcome
2926}
2927
2928/// The loop proper: setup, poll, teardown, with the queue and the status file
2929/// supplied rather than discovered.
2930///
2931/// All three of `home`, `worktrees_root` and the queue/status paths are
2932/// parameters rather than resolved here, for the same reason:
2933/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2934/// so a unit test that pinned it would fight every other test in the binary,
2935/// and a loop that resolved its own worktree bay could only be exercised
2936/// against the operator's real `~/wt/<repo>` - publishing over a live
2937/// daemon's status file, claiming tasks out of a live backlog, and, since
2938/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2939/// whatever the operator actually has on disk.
2940async fn drive(
2941    opts: &Opts,
2942    queue: &Queue,
2943    status_file: &Path,
2944    home: &Path,
2945    worktrees_root: &Path,
2946    stop: &Stop,
2947) -> Result<()> {
2948    // The status file is a *snapshot*, not a stream of events: a reader only
2949    // ever wants the latest values, and every tick rewrites the whole file
2950    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2951    // while an mpsc channel would force the loop to re-send unchanged fields on
2952    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2953    // for no gain. The lock is only ever held across a field assignment, never
2954    // across an await.
2955    let recovery_cfg = prepare(&opts.repo, opts).ok();
2956    let daemon_cfg = recovery_cfg
2957        .as_ref()
2958        .map(|c| c.daemon.clone())
2959        .unwrap_or_default();
2960    let reconciled = crate::driver::reconcile(home);
2961    if !reconciled.is_empty() {
2962        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2963    }
2964    let mut initial_status = Status::new();
2965    let owned = owned_task_jobs(home)?;
2966    initial_status.current = current_work(home, Timestamp::now())
2967        .into_iter()
2968        .filter(|current| {
2969            owned
2970                .iter()
2971                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2972        })
2973        .collect();
2974    initial_status.idle = initial_status.current.is_empty();
2975    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2976        recovery_cfg.as_ref(),
2977        daemon_cfg.max_deputies,
2978    ));
2979    let status = Arc::new(Mutex::new(initial_status));
2980    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2981    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2982
2983    // Read once at startup, not per task: how many runs this loop drives at
2984    // once is a property of the machine running it, not of whichever
2985    // repository a given task happens to name - see
2986    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
2987    // fact in the same sense the agent roster is.
2988    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2989
2990    tracing::info!(
2991        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2992        queue.root().display(),
2993        opts.poll.as_secs(),
2994        opts.max_attempts,
2995        concurrency,
2996        if daemon_cfg.pause_for_interrupts {
2997            ", interrupts enabled"
2998        } else {
2999            ""
3000        }
3001    );
3002
3003    let outcome = tokio::select! {
3004        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3005            max_concurrent: concurrency,
3006            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3007            recovery_cfg,
3008        }) => outcome,
3009        () = async {
3010            while !stop.stopped() {
3011                tokio::time::sleep(Duration::from_millis(25)).await;
3012            }
3013        } => {
3014            if stop.parking() {
3015                request_control(home, crate::worker::Control::Park)?;
3016            }
3017            Ok(())
3018        }
3019    };
3020
3021    stop.busy.store(0, Ordering::SeqCst);
3022    beat.abort();
3023    clear_status_at(status_file);
3024    outcome
3025}
3026
3027/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3028/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3029pub(crate) fn release_watch_settings_from_config(
3030    home: &Path,
3031    repo: &Path,
3032    cfg: &Config,
3033) -> (Vec<PathBuf>, u64) {
3034    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3035        .into_iter()
3036        .map(|r| r.path)
3037        .collect();
3038    // Repositories the daemon has worked in, wherever they live: a task may
3039    // name one outside `[repos] roots`, and its release PR must be watched too.
3040    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3041        .list()
3042        .into_iter()
3043        .map(|t| t.repo)
3044        .collect();
3045    let runs = home.join("runs");
3046    for id in crate::run::list_ids_in(&runs) {
3047        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3048            .ok()
3049            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3050            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3051        known.extend(repo);
3052    }
3053    for k in known {
3054        let k = k.canonicalize().unwrap_or(k);
3055        if k.join(".git").exists() && !paths.contains(&k) {
3056            paths.push(k);
3057        }
3058    }
3059    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3060    if !paths.contains(&own) {
3061        paths.push(own);
3062    }
3063    (paths, cfg.daemon.release_stall_minutes)
3064}
3065
3066/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3067const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3068
3069/// Refresh the status file on a fixed tick.
3070///
3071/// Separate from the loop because a run takes tens of minutes: a status file
3072/// written only between tasks would look stale for the whole of every run, and
3073/// a reader would report the daemon dead exactly while it was busiest.
3074async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3075    loop {
3076        tokio::time::sleep(HEARTBEAT).await;
3077        let snapshot = {
3078            let mut guard = lock(&status);
3079            guard.updated_at = Timestamp::now();
3080            guard.clone()
3081        };
3082        if let Err(e) = write_status_to(&path, &snapshot) {
3083            // A failed heartbeat must not take the daemon down: the loop is the
3084            // product, the status file is only the window onto it.
3085            tracing::warn!("could not refresh the daemon status file: {e:#}");
3086        }
3087    }
3088}
3089
3090/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3091/// if so, whether that wait is over.
3092#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3093enum LandResume {
3094    /// The task's last run is not parked on a land approval; schedule it
3095    /// like any other candidate.
3096    NotLanding,
3097    /// Parked in `land`, waiting on a question nobody has answered yet.
3098    /// Left alone: attempting it now would only re-observe the same pull
3099    /// request and park again, spending a `gh` call on a decision that has
3100    /// not changed since the last time this was checked.
3101    StillWaiting,
3102    /// Parked in `land`, and the question is settled - answered or
3103    /// abandoned. Resuming this is the one kind of candidate that must not
3104    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3105    Ready,
3106}
3107
3108/// Classify a runnable candidate by whether it is parked on a land-merge
3109/// approval. Read-only - no claim taken, nothing written - so it is cheap
3110/// enough to call on every candidate, every poll.
3111fn land_resume_state(task: &Task) -> LandResume {
3112    let Some(run_id) = task.execution_runs().last() else {
3113        return LandResume::NotLanding;
3114    };
3115    let Ok(state) = RunState::load(run_id) else {
3116        return LandResume::NotLanding;
3117    };
3118    if !state.parked {
3119        return LandResume::NotLanding;
3120    }
3121    if state.status == RunStatus::Landing
3122        && state.land_approval.as_ref().is_some_and(|binding| {
3123            ask::Questions::open()
3124                .get_for_effects(&binding.question)
3125                .is_ok_and(|q| {
3126                    q.run == state.id
3127                        && q.resolution()
3128                            .as_deref()
3129                            .is_some_and(crate::merge_decision::stops)
3130                })
3131        })
3132    {
3133        return LandResume::Ready;
3134    }
3135    if !implementers_match(task, &state) {
3136        return LandResume::NotLanding;
3137    }
3138    // Parked in `land` on the merge approval, or at `merge` on the owner's
3139    // word about a title/body the posting gate withheld. Told apart by the
3140    // run's own record, not by a status both can share.
3141    let node = if state.status == RunStatus::Landing {
3142        land::APPROVAL_NODE
3143    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3144        crate::github_text::ASK_NODE
3145    } else {
3146        return LandResume::NotLanding;
3147    };
3148    let store = ask::Questions::open();
3149    let waiting = store
3150        .list_for_effects()
3151        .into_iter()
3152        .filter(|q| &q.run == run_id && q.node == node)
3153        .max_by(|a, b| a.id.cmp(&b.id));
3154    let Some(mut q) = waiting else {
3155        return LandResume::Ready;
3156    };
3157    if !q.status.open() {
3158        // Repair spends agent resources and must obey concurrency and quota
3159        // waits; only a merge/hold decision may use the decision-only lane.
3160        if q.resolution().as_deref() == Some(land::REPAIR) {
3161            return if state.liveness(false) == Liveness::Live {
3162                LandResume::StillWaiting
3163            } else {
3164                LandResume::NotLanding
3165            };
3166        }
3167        return LandResume::Ready;
3168    }
3169    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3170    // nobody ever answered; land's approval bypasses that wait entirely (see
3171    // `land::approval_gate`), so the same deadline has to be enforced here
3172    // instead, or `graph.answer_timeout` silently stops meaning anything for
3173    // a land approval and a run can sit `StillWaiting` forever with nobody
3174    // told to look at it.
3175    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3176    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3177    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3178        q.abandon(format!(
3179            "no answer within {}s of asking",
3180            timeout.as_secs().max(1)
3181        ));
3182        // If this can't be persisted, do not treat the wait as settled on a
3183        // guess: fall through and try again next poll.
3184        if store.put(&mut q).is_ok() {
3185            return LandResume::Ready;
3186        }
3187    }
3188    LandResume::StillWaiting
3189}
3190
3191/// How often the loop rechecks for new work while something it already
3192/// started is still running, rather than sleeping out the whole
3193/// [`Opts::poll`] interval.
3194///
3195/// Short on purpose: this is what lets a land-merge approval that comes back
3196/// while another task is mid-competition be noticed and resumed within a
3197/// fraction of a second, not within the next multi-second poll.
3198const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3199
3200/// How often [`poll`] rechecks the shared build cache against its cap at a
3201/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3202/// waiting for the queue to run dry.
3203///
3204/// A queue that never empties means the `janitor` call at the bottom of this
3205/// loop's fully-idle branch can go unreached for as long as the backlog
3206/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3207/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3208/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3209/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3210/// backlog of short tasks does not pay for that walk on every poll.
3211const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3212
3213/// State of [`poll`]'s own interrupt-scheduling sequence - see
3214/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3215/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3216/// both kept free of `Task`'s non-identity fields on purpose: every decision
3217/// here turns only on task ids and which ones are in flight, so the "never
3218/// more than one run at once" and "exactly one resume" invariants can be
3219/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3220/// queue - which is exactly the coverage this feature's first two attempts
3221/// were missing.
3222///
3223/// Persisted after every transition, so scheduler replacement preserves the
3224/// interrupt's exclusive turn and the interrupted task's priority resume.
3225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3226enum Interrupt {
3227    /// No interrupt sequence in progress. Ordinary dispatch applies.
3228    Idle,
3229    /// `interrupt_task` is runnable and exactly one other run is in flight;
3230    /// `parked` names that one task's id. Dispatch is withheld from
3231    /// everyone, including `interrupt_task` itself, until it has left
3232    /// flight - only then is `interrupt_task` let through.
3233    ///
3234    /// `parked` is a `Vec` rather than a bare id for symmetry with
3235    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3236    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3237    /// when exactly one run is in flight, so it is guaranteed to hold
3238    /// exactly one entry in practice - see that branch's own doc for why
3239    /// more than one is deliberately never attempted.
3240    Parking {
3241        parked: Vec<String>,
3242        interrupt_task: String,
3243    },
3244    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3245    /// withheld from everyone until it leaves flight - merged, failed, held,
3246    /// it makes no difference - at which point the sequence moves to
3247    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3248    /// going straight to `Idle` would hand `parked` back to ordinary
3249    /// priority-order dispatch, where a higher-priority task filed in the
3250    /// meantime could start ahead of it.
3251    Running {
3252        parked: Vec<String>,
3253        interrupt_task: String,
3254    },
3255    /// `interrupt_task` left flight; `parked` still names the one run this
3256    /// sequence owes a resume. Dispatch is withheld from everyone except
3257    /// that task - see [`interrupt_gate`] - so the resume this feature
3258    /// promises is never raced by, or run alongside, an unrelated candidate.
3259    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3260    /// own doc on abandonment - the moment it is no longer runnable at all.
3261    Resuming { parked: Vec<String> },
3262}
3263
3264/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3265/// and `runnable` are read-only snapshots of this tick's reality, and the
3266/// only side effect the caller still owes the world is asking whichever
3267/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3268/// site.
3269///
3270/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3271/// accepted rather than a narrower type because that is what [`poll`] already
3272/// has on hand from [`runnable`], and building a second, smaller list on
3273/// every tick just to satisfy this signature would cost more than it proves.
3274///
3275/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3276/// back to a task they are waiting on no longer being [`runnable`] - held,
3277/// blocked, deleted, or finished by some other means entirely, all of which
3278/// an operator can do to a task sitting in the queue with no claim on it at
3279/// all, at any moment, interrupt sequence or not. Without this check the
3280/// sequence would wait forever for a dispatch that can never come, and
3281/// `interrupt_gate` would withhold every other task in the queue right along
3282/// with it - a single `magi task hold` on the wrong id turning into a
3283/// daemon that never dispatches anything again.
3284fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3285    match state {
3286        Interrupt::Idle => {
3287            // Not just "something to interrupt": exactly one thing. More
3288            // than one run in flight only happens above the default
3289            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3290            // one resume, never run alongside anything else" only because
3291            // it is only ever seeded with exactly one id - see
3292            // `Interrupt::Resuming`'s own doc on why releasing more than one
3293            // parked id back to ordinary dispatch cannot be made safe
3294            // against that same setting's own extra concurrency slots.
3295            // Waiting here for the herd to settle to one is the
3296            // simplification this feature's own constraints ask for rather
3297            // than a second concurrency model to reconcile with the first.
3298            if in_flight.len() != 1 {
3299                return Interrupt::Idle;
3300            }
3301            match runnable.iter().find(|t| t.interrupt) {
3302                Some(t) => Interrupt::Parking {
3303                    parked: in_flight.to_vec(),
3304                    interrupt_task: t.id.clone(),
3305                },
3306                None => Interrupt::Idle,
3307            }
3308        }
3309        Interrupt::Parking {
3310            parked,
3311            interrupt_task,
3312        } => {
3313            if in_flight.iter().any(|id| parked.contains(id)) {
3314                // Still waiting for what was in flight to actually stop.
3315                Interrupt::Parking {
3316                    parked,
3317                    interrupt_task,
3318                }
3319            } else if in_flight.contains(&interrupt_task) {
3320                Interrupt::Running {
3321                    parked,
3322                    interrupt_task,
3323                }
3324            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3325                // The parked run(s) are gone, but the interrupt task has not
3326                // been dispatched yet on this tick - `interrupt_gate` is
3327                // what lets it through next.
3328                Interrupt::Parking {
3329                    parked,
3330                    interrupt_task,
3331                }
3332            } else {
3333                // The interrupt task itself is no longer runnable - see this
3334                // function's own doc on abandonment. The parked run(s) still
3335                // get their guaranteed resume; there is simply no interrupt
3336                // to run ahead of them any longer.
3337                Interrupt::Resuming { parked }
3338            }
3339        }
3340        Interrupt::Running {
3341            parked,
3342            interrupt_task,
3343        } => {
3344            if in_flight.contains(&interrupt_task) {
3345                Interrupt::Running {
3346                    parked,
3347                    interrupt_task,
3348                }
3349            } else {
3350                // The interrupt task's own run reached a terminal status,
3351                // whichever one - this is the *only* trigger that moves the
3352                // sequence on, driven straight off the same in-flight
3353                // bookkeeping `poll` already reaps every tick, not a second,
3354                // independent poll of anything.
3355                Interrupt::Resuming { parked }
3356            }
3357        }
3358        Interrupt::Resuming { parked } => {
3359            if in_flight.iter().any(|id| parked.contains(id)) {
3360                // One of the parked runs has been dispatched - the resume
3361                // this sequence owed is fulfilled. Whatever else is left in
3362                // `parked` (ordinarily nothing, at the default concurrency
3363                // of one) rejoins ordinary priority-order dispatch, same as
3364                // any other runnable task.
3365                Interrupt::Idle
3366            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3367                Interrupt::Resuming { parked }
3368            } else {
3369                // Abandonment (see this function's own doc): nothing left in
3370                // `parked` is even runnable any longer.
3371                Interrupt::Idle
3372            }
3373        }
3374    }
3375}
3376
3377/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3378/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3379/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3380/// indistinguishable from any other runnable task - exactly the "off does
3381/// nothing" this feature promises.
3382fn advance_interrupt_tick(
3383    enabled: bool,
3384    state: Interrupt,
3385    in_flight: &[String],
3386    runnable: &[Task],
3387) -> Interrupt {
3388    if !enabled {
3389        return Interrupt::Idle;
3390    }
3391    advance_interrupt(state, in_flight, runnable)
3392}
3393
3394/// Which of this tick's runnable candidates the interrupt sequence actually
3395/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3396/// each half is assertable on its own: this is the half that keeps a
3397/// competition and an interrupt from ever running at the same moment.
3398fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3399    match state {
3400        Interrupt::Idle => candidates,
3401        Interrupt::Parking {
3402            parked,
3403            interrupt_task,
3404        } => {
3405            if in_flight.iter().any(|id| parked.contains(id)) {
3406                Vec::new()
3407            } else {
3408                candidates
3409                    .into_iter()
3410                    .filter(|t| &t.id == interrupt_task)
3411                    .collect()
3412            }
3413        }
3414        Interrupt::Running { .. } => Vec::new(),
3415        // At most one: even if `parked` names more than one id (more than
3416        // one run was in flight when the sequence began, only possible
3417        // above the default `max_concurrent_runs = 1`), only the first match
3418        // is offered. Capping this to a single candidate - not merely to
3419        // `parked`'s own ids - is what makes "exactly one resume, never two
3420        // dispatched together" true regardless of how many ordinary slots
3421        // happen to be free this tick.
3422        Interrupt::Resuming { parked } => candidates
3423            .into_iter()
3424            .find(|t| parked.contains(&t.id))
3425            .into_iter()
3426            .collect(),
3427    }
3428}
3429
3430/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3431/// bundled into one parameter so `poll`'s own signature stays readable -
3432/// see [`drive`]'s call site for where these are actually read.
3433struct DispatchLimits {
3434    /// How many *ordinary* candidates run at once. See
3435    /// [`crate::config::Daemon::max_concurrent_runs`].
3436    max_concurrent: usize,
3437    /// See [`crate::config::Daemon::pause_for_interrupts`].
3438    pause_for_interrupts: bool,
3439    recovery_cfg: Option<Config>,
3440}
3441
3442/// Which semaphore, if any, dispatching a candidate should draw its permit
3443/// from.
3444///
3445/// Pure and separate from [`poll`]'s loop body for the same reason
3446/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3447/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3448/// exactly the policy this feature adds, and a policy only exercisable by
3449/// running the whole loop is a policy nobody checks.
3450#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3451enum PermitKind {
3452    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3453    /// Checked first - a task can be both a land resume and marked
3454    /// [`Task::urgent`], and the resume's own "must not queue behind
3455    /// anything" guarantee takes precedence.
3456    None,
3457    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3458    /// (never in addition to trying) the ordinary pool. This is what lets
3459    /// an urgent task dispatch while every ordinary slot is already checked
3460    /// out, and what stops a second urgent task from opening a third run: it
3461    /// waits on this same one-slot semaphore rather than falling through to
3462    /// the ordinary one.
3463    Urgent,
3464    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3465    /// above.
3466    #[default]
3467    Ordinary,
3468}
3469
3470/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3471/// own boolean, already computed by the caller from [`land_resume_state`].
3472fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3473    if priority {
3474        PermitKind::None
3475    } else if urgent {
3476        PermitKind::Urgent
3477    } else {
3478        PermitKind::Ordinary
3479    }
3480}
3481
3482fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3483    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3484        (0usize, 0usize),
3485        |(ordinary, urgent), request| match request.lane {
3486            PermitKind::Ordinary => (ordinary + 1, urgent),
3487            PermitKind::Urgent => (ordinary, urgent + 1),
3488            PermitKind::None => (ordinary, urgent),
3489        },
3490    );
3491    (
3492        limit.saturating_sub(ordinary),
3493        1usize.saturating_sub(urgent),
3494    )
3495}
3496
3497struct DispatchClaim {
3498    task: Task,
3499    claim: crate::queue::Claim,
3500    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3501}
3502
3503/// Claim and re-read before choosing a lane: a queue listing may predate an
3504/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3505fn claim_dispatch(
3506    queue: &Queue,
3507    candidate: &Task,
3508    cooling_down: bool,
3509    ordinary: &Arc<tokio::sync::Semaphore>,
3510    urgent: &Arc<tokio::sync::Semaphore>,
3511) -> Option<DispatchClaim> {
3512    let Ok(claim) = queue.claim(&candidate.id) else {
3513        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3514        return None;
3515    };
3516    let task = match queue.get(&candidate.id) {
3517        Ok(t) if t.status.runnable() => t,
3518        Ok(_) => return None,
3519        Err(e) => {
3520            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3521            return None;
3522        }
3523    };
3524    let resume = land_resume_state(&task);
3525    if resume == LandResume::StillWaiting {
3526        return None;
3527    }
3528    let priority = resume == LandResume::Ready;
3529    if !priority && cooling_down {
3530        return None;
3531    }
3532    // Never borrow an ordinary slot when the single urgent slot is busy.
3533    // Keep scanning other candidates when either pool has no free slot.
3534    let permit = match permit_kind(priority, task.urgent) {
3535        PermitKind::None => None,
3536        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3537        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3538    };
3539    // Persist the dispatch order under the claim, before config discovery or
3540    // coordination waits can reorder concurrent starts.
3541    let stamp = Timestamp::now();
3542    let mut task = task;
3543    task.dispatched_at = Some(stamp);
3544    if let Err(e) = queue.modify(&task.id, |t| {
3545        t.dispatched_at = Some(stamp);
3546        true
3547    }) {
3548        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3549    }
3550    Some(DispatchClaim {
3551        task,
3552        claim,
3553        permit,
3554    })
3555}
3556
3557/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3558/// teardown and cannot skip the teardown on an early return.
3559///
3560/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3561/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3562/// land approval that has since been answered is dispatched outside that
3563/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3564/// the whole point of parking there is that it must not queue behind
3565/// whatever else the loop happens to be running, even at the default of one.
3566/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3567/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3568/// these exemptions is still subject to the interrupt gate below, urgent
3569/// included: a land-resume or urgent candidate is exactly as much "something
3570/// else running" as an ordinary one from the interrupt sequence's point of
3571/// view, and letting either slip through while a run is being parked, or
3572/// while the interrupt task itself has the floor, is precisely the second
3573/// run 75dd's own "at most one run, ever, at once" guarantee must never
3574/// allow - see [`Interrupt`]'s own doc.
3575#[derive(Serialize, Deserialize)]
3576struct ServiceWorker {
3577    opts: Opts,
3578    queue: PathBuf,
3579    worktrees_root: PathBuf,
3580    operation: String,
3581}
3582
3583fn load_conductor(home: &Path) -> Result<Conductor> {
3584    match std::fs::read(home.join("conductor-state.json")) {
3585        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3586        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3587        Err(error) => Err(error.into()),
3588    }
3589}
3590
3591fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3592    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3593        .into_iter()
3594        .map(|c| c.task)
3595        .collect();
3596    let stalled = stalled_tasks(queue, home, Timestamp::now());
3597    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3598    let finished = finished_tasks(queue)
3599        .into_iter()
3600        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3601        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3602        .collect();
3603    let queued = queued_tasks(queue)
3604        .into_iter()
3605        .filter(|t| !live.contains(&t.id))
3606        .collect();
3607    (queued, stalled, finished)
3608}
3609
3610// Separate latest dispatch and worker receipts expose version handoff and skips
3611// without erasing the last completed scan or treating observations as authority.
3612fn retention_service_receipt(
3613    home: &Path,
3614    operation: &str,
3615    phase: &str,
3616    outcome: &str,
3617    detail: &str,
3618    cfg: Option<&Config>,
3619) {
3620    if !matches!(operation, "housekeeping" | "disk-pressure") {
3621        return;
3622    }
3623    let receipt = serde_json::json!({"checked_at": Timestamp::now(),
3624        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
3625        "operation": operation, "outcome": outcome, "detail": detail,
3626        "auto_fold": cfg.map(|c| c.disk.auto_fold),
3627        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
3628    if let Err(error) = crate::fold_evidence::atomic_write(
3629        &home.join(format!("source-eviction-{operation}-{phase}.json")),
3630        &serde_json::to_vec(&receipt).expect("service receipt"),
3631    ) {
3632        tracing::warn!("retention service receipt failed: {error:#}");
3633    }
3634}
3635
3636async fn start_service(
3637    home: &Path,
3638    opts: &Opts,
3639    queue: &Queue,
3640    worktrees_root: &Path,
3641    operation: &str,
3642    cfg: Option<&Config>,
3643    busy: bool,
3644) -> Result<()> {
3645    // Fetch policy is live configuration, unlike question recovery capacity.
3646    // Reload before both cadence and eligibility, including disabled -> enabled.
3647    let fetch_cfg = if operation == "fetch" {
3648        match prepare(&opts.repo, opts) {
3649            Ok(cfg) => Some(cfg),
3650            Err(error) => {
3651                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3652                return Ok(());
3653            }
3654        }
3655    } else {
3656        None
3657    };
3658    let cfg = fetch_cfg.as_ref().or(cfg);
3659    let ticks = home.join("service-ticks");
3660    std::fs::create_dir_all(&ticks)?;
3661    let receipt = ticks.join(format!("daemon-{operation}"));
3662    let last = std::fs::read(&receipt)
3663        .ok()
3664        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3665    let interval = match operation {
3666        "disk-pressure" => 30,
3667        "cache" => CACHE_CHECK_INTERVAL_SECS,
3668        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3669        _ => opts.poll.as_secs().max(1),
3670    };
3671    let now = Timestamp::now();
3672    if !cache_check_due(last, now, interval) {
3673        retention_service_receipt(
3674            home,
3675            operation,
3676            "dispatch",
3677            "skipped",
3678            "cadence not due",
3679            cfg,
3680        );
3681        return Ok(());
3682    }
3683    let key = format!("service:daemon-{operation}");
3684    if crate::worker::active(home)?
3685        .iter()
3686        .any(|job| job.key == key)
3687    {
3688        retention_service_receipt(
3689            home,
3690            operation,
3691            "dispatch",
3692            "skipped",
3693            "service worker already active",
3694            cfg,
3695        );
3696        return Ok(());
3697    }
3698    let eligible = match operation {
3699        "conductor" => {
3700            let (queued, stalled, finished) = conductor_work(queue, home);
3701            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3702                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3703        }
3704        "maintenance" => Questions::at(home.join("questions"))
3705            .list_for_effects()
3706            .iter()
3707            .any(|q| {
3708                q.chosen_action().is_some_and(|action| action.maintenance())
3709                    && !home
3710                        .join("choice-actions")
3711                        .join(format!("{}.json", q.id))
3712                        .exists()
3713            }),
3714        "housekeeping" => !busy && runnable(queue).is_empty(),
3715        "cache" => {
3716            !busy
3717                && !runnable(queue).is_empty()
3718                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3719        }
3720        "disk-pressure" => busy,
3721        "fetch" => {
3722            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3723        }
3724        _ => false,
3725    };
3726    if !eligible {
3727        retention_service_receipt(
3728            home,
3729            operation,
3730            "dispatch",
3731            "skipped",
3732            if operation == "housekeeping" {
3733                "active work or runnable task queue"
3734            } else {
3735                "no active work; idle housekeeping owns scan"
3736            },
3737            cfg,
3738        );
3739        return Ok(());
3740    }
3741    retention_service_receipt(
3742        home,
3743        operation,
3744        "dispatch",
3745        "launching",
3746        "eligible and cadence due",
3747        cfg,
3748    );
3749    let request = ServiceWorker {
3750        opts: opts.absolute()?,
3751        queue: std::path::absolute(queue.root())?,
3752        worktrees_root: std::path::absolute(worktrees_root)?,
3753        operation: operation.to_owned(),
3754    };
3755    if let Err(error) =
3756        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3757    {
3758        retention_service_receipt(
3759            home,
3760            operation,
3761            "dispatch",
3762            "error",
3763            &format!("worker launch: {error:#}"),
3764            cfg,
3765        );
3766        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3767    }
3768    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3769    Ok(())
3770}
3771
3772/// Finite maintenance jobs survive scheduler replacement without duplicating
3773/// agent calls or cancelling an operation between its effect and receipt.
3774pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3775    let request: ServiceWorker = serde_json::from_value(payload)?;
3776    let opts = &request.opts;
3777    let queue = Queue::at(request.queue);
3778    let questions = Questions::at(home.join("questions"));
3779    match request.operation.as_str() {
3780        "maintenance" => apply_maintenance_choices(&queue, &questions, home).await,
3781        "conductor" => {
3782            let path = home.join("conductor-state.json");
3783            let mut conductor = load_conductor(home)?;
3784            let (queued, stalled, finished) = conductor_work(&queue, home);
3785            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3786                && conductor.worth_a_look(&queue, &stalled, &finished)
3787            {
3788                let cfg = prepare(&opts.repo, opts)?;
3789                conductor
3790                    .maybe_run(
3791                        &cfg,
3792                        &opts.repo,
3793                        &queue,
3794                        &questions,
3795                        home,
3796                        &queued,
3797                        &stalled,
3798                        &finished,
3799                        opts.max_attempts,
3800                    )
3801                    .await;
3802                let temporary = path.with_extension("json.tmp");
3803                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3804                std::fs::rename(temporary, path)?;
3805            }
3806        }
3807        "fetch" => {
3808            let cfg = prepare(&opts.repo, opts)?;
3809            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3810                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3811                tracing::debug!("fetch origins: {outcome:?}");
3812            }
3813        }
3814        "cache" => {
3815            if task_jobs(home)?.is_empty() {
3816                let mut checked = None;
3817                maybe_prune_cache_between_runs(
3818                    &opts.repo,
3819                    opts,
3820                    home,
3821                    &Stop::new(),
3822                    &mut checked,
3823                    Timestamp::now(),
3824                )
3825                .await;
3826            }
3827        }
3828        "disk-pressure" => {
3829            if let Ok(cfg) = prepare(&opts.repo, opts) {
3830                retention_service_receipt(
3831                    home,
3832                    "disk-pressure",
3833                    "worker",
3834                    "running",
3835                    "retention sweep",
3836                    Some(&cfg),
3837                );
3838                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3839                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3840                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3841                }
3842                for current in current_work(home, Timestamp::now()) {
3843                    if let Ok(state) = RunState::load_under(&current.run, home)
3844                        && let Some(reason) = disk_gate(&state.repo, &state.config)
3845                    {
3846                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
3847                            job.key.strip_prefix("task:") == Some(current.task.as_str())
3848                        }) {
3849                            request_task_park(
3850                                home,
3851                                &job,
3852                                crate::run::ParkCause::Interrupt {
3853                                    reason: reason.clone(),
3854                                },
3855                            )?;
3856                        }
3857                        notices::raise_in(
3858                            home,
3859                            Notice::warn(
3860                                "disk:pressure",
3861                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
3862                            ),
3863                        );
3864                    }
3865                }
3866            } else {
3867                retention_service_receipt(
3868                    home,
3869                    "disk-pressure",
3870                    "worker",
3871                    "error",
3872                    "configuration could not be loaded",
3873                    None,
3874                );
3875            }
3876        }
3877        "housekeeping" => {
3878            if task_jobs(home)?.is_empty() {
3879                match prepare(&opts.repo, opts) {
3880                    Ok(cfg) => {
3881                        retention_service_receipt(
3882                            home,
3883                            "housekeeping",
3884                            "worker",
3885                            "running",
3886                            "retention sweep",
3887                            Some(&cfg),
3888                        );
3889                        crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3890                    }
3891                    Err(error) => retention_service_receipt(
3892                        home,
3893                        "housekeeping",
3894                        "worker",
3895                        "error",
3896                        &format!("configuration: {error:#}"),
3897                        None,
3898                    ),
3899                }
3900                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
3901                resweep_superseded_attempts(&queue, home);
3902                triage_held(&queue, home, opts).await;
3903            } else {
3904                retention_service_receipt(
3905                    home,
3906                    "housekeeping",
3907                    "worker",
3908                    "skipped",
3909                    "task worker became active",
3910                    None,
3911                );
3912            }
3913        }
3914        operation => bail!("unknown daemon service {operation}"),
3915    }
3916    Ok(())
3917}
3918
3919/// Only a different request under the same key is a dispatch handoff race.
3920/// Our own unacknowledged reservation is a startup failure, not competing work:
3921/// stop dispatch without fencing it, so an already detached child may still run.
3922fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
3923    let key = format!("task:{}", request.task);
3924    let payload = serde_json::to_value(request)?;
3925    if crate::worker::active(home)?
3926        .iter()
3927        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
3928    {
3929        tracing::warn!(
3930            "task {} acquired a competing worker reservation: {error:#}",
3931            crate::run::short_of(&request.task)
3932        );
3933        return Ok(());
3934    }
3935    tracing::error!("task worker startup stopped dispatch: {error:#}");
3936    notices::raise_in(
3937        home,
3938        Notice::error(
3939            "loop:worker-startup",
3940            // Startup diagnostics may contain private child-process details;
3941            // keep them in the local error/log rather than the chat or notifier.
3942            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),
3943        ).link(Link::Task { id: request.task.clone() }),
3944    );
3945    Err(error).with_context(|| {
3946        format!(
3947            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
3948            crate::run::short_of(&request.task)
3949        )
3950    })
3951}
3952
3953async fn poll(
3954    opts: &Opts,
3955    queue: &Queue,
3956    status: &Arc<Mutex<Status>>,
3957    home: &Path,
3958    worktrees_root: &Path,
3959    stop: &Stop,
3960    limits: DispatchLimits,
3961) -> Result<()> {
3962    let mut attempted = Vec::new();
3963    let mut settling_once_services = false;
3964    let interrupt_path = home.join("scheduler-interrupt.json");
3965    let mut interrupt = match std::fs::read(&interrupt_path) {
3966        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
3967        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
3968        Err(error) => return Err(error.into()),
3969    };
3970    let mut previous = std::collections::BTreeSet::<String>::new();
3971    while !stop.stopped() {
3972        let jobs: Vec<_> = crate::worker::active(home)?
3973            .into_iter()
3974            .filter(|job| job.kind == "task")
3975            .collect();
3976        let requests: Vec<_> = jobs
3977            .iter()
3978            .map(|job| {
3979                serde_json::from_value::<TaskWorker>(job.payload.clone())
3980                    .with_context(|| format!("read live task worker {}", job.id))
3981            })
3982            .collect::<Result<_>>()?;
3983        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
3984        let owned: std::collections::BTreeSet<_> = requests
3985            .iter()
3986            .filter(|r| !r.standalone)
3987            .map(|r| r.task.clone())
3988            .collect();
3989        let current: Vec<_> = requests
3990            .iter()
3991            .zip(&jobs)
3992            .filter(|(request, _)| !request.standalone)
3993            .map(|(request, job)| Current {
3994                worker: Some(job.id.clone()),
3995                task: request.task.clone(),
3996                run: queue
3997                    .get(&request.task)
3998                    .ok()
3999                    .and_then(|task| task.execution_runs().last().cloned())
4000                    .unwrap_or_default(),
4001            })
4002            .collect();
4003        {
4004            let mut snapshot = lock(status);
4005            snapshot.polls += 1;
4006            snapshot.completed += previous.difference(&owned).count();
4007            snapshot.current = current;
4008            snapshot.idle = owned.is_empty();
4009        }
4010        previous = owned.clone();
4011        stop.busy.store(owned.len(), Ordering::SeqCst);
4012
4013        // Slots are reconstructed from durable reservations and OS-held worker
4014        // leases, not this scheduler's lifetime or mutable task urgency.
4015        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4016        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4017        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4018        let mut permits = Vec::new();
4019        sweep_stale_claims(queue, STALE_CLAIM);
4020        reclaim_orphaned_running(queue, opts.max_attempts, &live);
4021        reclaim_abandoned_runs(home, Timestamp::now());
4022        let questions = Questions::at(home.join("questions"));
4023
4024        // Deterministic: no model, run before the conductor sees anything so
4025        // its input reflects the queue's current, already-resolved state.
4026        crate::task_chat::sweep(
4027            queue,
4028            &crate::talk::Talks::at(home.join("talks")),
4029            &questions,
4030            home,
4031        );
4032        if let Err(error) = crate::task_inquiry::Outbox::at(home)
4033            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4034        {
4035            tracing::warn!("task inquiry delivery remains pending: {error:#}");
4036        }
4037        repair_choice_offers(&questions);
4038        resolve_blockers(queue, &questions);
4039        apply_task_choice_actions(queue, &questions, home);
4040        triage::apply_answers(queue, &questions);
4041        reconcile_task_questions(queue, &questions);
4042        let talks = crate::talk::Talks::at(home.join("talks"));
4043        crate::chat_notify::sweep(queue, &talks, home);
4044        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4045        crate::chat_watch::sweep(home, &talks);
4046        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4047            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4048        }
4049        let mut turns = tokio::task::JoinSet::new();
4050        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4051        // start_turns dispatches detached turns; no paid work lives in this set.
4052        while turns.join_next().await.is_some() {}
4053
4054        crate::consult::start_services(
4055            home,
4056            &opts.repo,
4057            limits.recovery_cfg.as_ref(),
4058            opts.config.as_deref(),
4059        )
4060        .await?;
4061        for operation in [
4062            "conductor",
4063            "maintenance",
4064            "housekeeping",
4065            "disk-pressure",
4066            "cache",
4067            "fetch",
4068        ] {
4069            // Once an idle --once drain starts settling services, subsequent
4070            // scans only consume their effects. An expired cadence receipt
4071            // must not start another service and keep the drain alive.
4072            if settling_once_services {
4073                break;
4074            }
4075            start_service(
4076                home,
4077                opts,
4078                queue,
4079                worktrees_root,
4080                operation,
4081                limits.recovery_cfg.as_ref(),
4082                !live.is_empty(),
4083            )
4084            .await?;
4085        }
4086        let latest = crate::worker::active(home)?;
4087        if latest.iter().any(|job| job.key == "service:daemon-cache")
4088            || latest
4089                .iter()
4090                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4091        {
4092            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4093            continue;
4094        }
4095        let candidates: Vec<Task> = runnable(queue)
4096            .into_iter()
4097            .filter(|task| !live.contains(&task.id))
4098            .filter(|task| !opts.once || !attempted.contains(&task.id))
4099            .collect();
4100        let in_flight: Vec<_> = owned.iter().cloned().collect();
4101        let prior_interrupt = std::mem::discriminant(&interrupt);
4102        interrupt = advance_interrupt_tick(
4103            limits.pause_for_interrupts,
4104            interrupt,
4105            &in_flight,
4106            &candidates,
4107        );
4108        // Same-variant transitions preserve their identities. Only an actual
4109        // transition needs a durable write, atomically before sending controls.
4110        if prior_interrupt != std::mem::discriminant(&interrupt) {
4111            let temporary = interrupt_path.with_extension("json.tmp");
4112            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4113            std::fs::rename(temporary, &interrupt_path)?;
4114        }
4115        if let Interrupt::Parking {
4116            parked,
4117            interrupt_task,
4118        } = &interrupt
4119        {
4120            for job in jobs.iter().filter(|job| {
4121                parked
4122                    .iter()
4123                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4124            }) {
4125                if crate::worker::control(home, &job.key)?.is_none() {
4126                    request_task_park(
4127                        home,
4128                        job,
4129                        crate::run::ParkCause::Interrupt {
4130                            reason: format!(
4131                                "task {} asked to run first",
4132                                crate::run::short_of(interrupt_task)
4133                            ),
4134                        },
4135                    )?;
4136                }
4137            }
4138        }
4139        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4140        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4141        let mut started = false;
4142        let mut resync = false;
4143        for candidate in candidates {
4144            if stop.stopped() {
4145                break;
4146            }
4147            let Some(DispatchClaim {
4148                task,
4149                claim,
4150                permit,
4151            }) = claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem)
4152            else {
4153                continue;
4154            };
4155            if crate::worker::active(home)?
4156                .iter()
4157                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4158            {
4159                drop(claim);
4160                resync = true;
4161                break;
4162            }
4163            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4164            let request = TaskWorker {
4165                opts: opts.absolute()?,
4166                queue: std::path::absolute(queue.root())?,
4167                task: task.id.clone(),
4168                lane,
4169                standalone: false,
4170            };
4171            // Keep the claim until spawn acknowledges the worker's durable
4172            // reservation. The worker then claims and re-reads before attempt.
4173            if let Err(error) = crate::worker::spawn(
4174                home,
4175                "task",
4176                &format!("task:{}", task.id),
4177                serde_json::to_value(&request)?,
4178            )
4179            .await
4180            {
4181                task_worker_spawn_error(home, &request, error)?;
4182                drop(claim);
4183                resync = true;
4184                break;
4185            }
4186            drop(claim);
4187            permits.extend(permit);
4188            attempted.push(task.id);
4189            started = true;
4190        }
4191        if started || resync {
4192            continue;
4193        }
4194        if owned.is_empty() && opts.once {
4195            settling_once_services = true;
4196            // These finite services can own queue claims or publish answers.
4197            // A skipped claim is not an idle queue until they have finished;
4198            // scan again afterwards so their changes are actually scheduled.
4199            if crate::worker::active(home)?.iter().any(|job| {
4200                job.kind == "daemon-service"
4201                    && matches!(
4202                        job.key.as_str(),
4203                        "service:daemon-housekeeping"
4204                            | "service:daemon-conductor"
4205                            | "service:daemon-maintenance"
4206                    )
4207            }) {
4208                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4209                continue;
4210            }
4211            break;
4212        }
4213        stop.idle(if live.is_empty() {
4214            opts.poll
4215        } else {
4216            RECHECK_WHILE_BUSY.min(opts.poll)
4217        })
4218        .await;
4219    }
4220    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4221    // every queue claim and Runner driver lease through outcome settlement.
4222    stop.busy.store(0, Ordering::SeqCst);
4223    Ok(())
4224}
4225
4226/// A maintenance pass may briefly own the same record while a worker starts.
4227/// Wait without blocking the executor or charging an agent attempt, then read
4228/// ownership again under the acquired lock. Other I/O failures still fail closed.
4229async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4230    let busy = |error: &anyhow::Error| {
4231        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4232            error.kind() == std::io::ErrorKind::WouldBlock
4233                || cfg!(windows) && error.raw_os_error() == Some(33)
4234        })
4235    };
4236    match crate::pr_head::owner_lock(home, id) {
4237        Ok(lock) => return Ok(lock),
4238        Err(error) if busy(&error) => {}
4239        Err(error) => return Err(error),
4240    }
4241    let wait = RunState::load_under(id, home)?
4242        .config
4243        .graph
4244        .timeout_resource_wait;
4245    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4246}
4247
4248/// Historical successors do not revoke a still-resumable public owner. Scan
4249/// under the same lock as publication/driver claims, and fail closed on unknown
4250/// history before spending another attempt.
4251async fn public_resume_owner(
4252    home: &Path,
4253    runs: &[String],
4254    repo: &Path,
4255) -> Result<Option<RunState>> {
4256    let mut owner = None;
4257    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4258        let _lock = resume_owner_lock(home, id).await?;
4259        let state = RunState::load_under(id, home)?;
4260        if state.released()
4261            || state.retired_to.is_some()
4262            || state.pr_taken_over_by.is_some()
4263            || !crate::handover::landing_checkpoint(&state)
4264        {
4265            continue;
4266        }
4267        anyhow::ensure!(
4268            crate::git::toplevel(&state.repo).await?.canonicalize()?
4269                == crate::git::toplevel(repo).await?.canonicalize()?,
4270            "public owner repository differs; inspect run lineage"
4271        );
4272        anyhow::ensure!(
4273            owner.is_none(),
4274            "multiple retained public owners; inspect run lineage"
4275        );
4276        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4277            anyhow::bail!(reason.diagnostic(&state));
4278        }
4279        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4280        anyhow::ensure!(
4281            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4282            "public owner's driver is live or unknown; wait before retrying"
4283        );
4284        owner = Some(state);
4285    }
4286    Ok(owner)
4287}
4288
4289/// Run one claimed task to a terminal status and record the outcome.
4290///
4291/// Every transition is flushed to the queue as it happens, so the state on disk
4292/// is what actually occurred rather than what this process still intends to
4293/// write.
4294async fn attempt(
4295    opts: &Opts,
4296    queue: &Queue,
4297    status: &Arc<Mutex<Status>>,
4298    stop: &Stop,
4299    interrupt_pause: crate::graph::Pause,
4300    task: &mut Task,
4301) -> Vec<QuotaLoss> {
4302    let repo = repo_for(task, &opts.repo);
4303    tracing::info!(
4304        "task {} — {} (repo {})",
4305        task.short(),
4306        task.title,
4307        repo.display()
4308    );
4309
4310    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4311        Ok(owner) => owner,
4312        Err(e) => {
4313            task.hold_machine(Some(format!(
4314                "Cannot verify existing public owner: {e:#}; no attempt started."
4315            )));
4316            record(queue, task);
4317            return Vec::new();
4318        }
4319    };
4320    let resume_runs = public_owner
4321        .as_ref()
4322        .map(|s| vec![s.id.clone()])
4323        .unwrap_or_else(|| task.execution_runs().to_vec());
4324
4325    // A stop spends no agent resources and uses the saved landing owner.
4326    // Current roster edits, missing attachments or a failed config fetch must
4327    // never turn it into a new implementation, or prevent a PR from closing.
4328    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4329        && previous
4330            .merge_decision
4331            .as_ref()
4332            .is_some_and(|decision| !decision.closed)
4333        && previous.status != RunStatus::Landing
4334        && !crate::merge_decision::resumable_hold(&previous)
4335    {
4336        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)));
4337        record(queue, task);
4338        return Vec::new();
4339    }
4340    let stop_owner = resume_runs
4341        .last()
4342        .and_then(|id| RunState::load(id).ok())
4343        .filter(|state| {
4344            crate::merge_decision::resumable_hold(state)
4345                || state.status == RunStatus::Landing
4346                    && state.land_approval.as_ref().is_some_and(|binding| {
4347                        Questions::open()
4348                            .get_for_effects(&binding.question)
4349                            .is_ok_and(|q| {
4350                                q.run == state.id
4351                                    && q.resolution()
4352                                        .as_deref()
4353                                        .is_some_and(crate::merge_decision::stops)
4354                            })
4355                    })
4356        });
4357    if let Some(owner) = stop_owner {
4358        let mut runner = match Runner::resume(&owner.id) {
4359            Ok(runner) => runner,
4360            Err(e) => {
4361                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4362                record(queue, task);
4363                return Vec::new();
4364            }
4365        };
4366        runner.on_pause(stop.pause());
4367        runner.watch_interrupt(interrupt_pause);
4368        let quota_before = runner.state.quota.clone();
4369        let before_start = task.clone();
4370        task.start(owner.id.clone());
4371        if let Err(error) = queue.put(task) {
4372            *task = before_start;
4373            let error = runner.fail_startup("task-start", error);
4374            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4375                task.record_startup_failure(failure.clone());
4376            }
4377            task.hold_manual(Some(format!(
4378                "Could not persist task start; no agents dispatched: {error:#}"
4379            )));
4380            record(queue, task);
4381            return Vec::new();
4382        }
4383        lock(status).current.push(Current {
4384            worker: None,
4385            task: task.id.clone(),
4386            run: owner.id,
4387        });
4388        runner.state.carry_dispatched_resumes(task);
4389        runner.state.next_pass_task_entry = true;
4390        let result = runner.execute().await;
4391        return finish_attempt(
4392            opts.max_attempts,
4393            queue,
4394            task,
4395            &runner.state,
4396            &quota_before,
4397            result,
4398        );
4399    }
4400
4401    if let Some(owner) = &public_owner
4402        && (task.fresh_start || !may_resume_run(owner, task))
4403    {
4404        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)));
4405        record(queue, task);
4406        return Vec::new();
4407    }
4408
4409    if let Some(state) = task
4410        .execution_runs()
4411        .last()
4412        .and_then(|id| RunState::load(id).ok())
4413        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4414    {
4415        task.hold_machine(Some(reason));
4416        record(queue, task);
4417        return Vec::new();
4418    }
4419
4420    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4421        && !task.fresh_start
4422        && task.pr_recovery.is_none()
4423    {
4424        // Authorization still takes the owner lock and execution lease and
4425        // rechecks liveness, retained HEAD and ownership before saving.
4426        let authorized = if crate::repair_budget::conflict_pending(task, &held) {
4427            true
4428        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4429            let home = queue.root().parent().expect("queue has a home");
4430            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4431                Ok(()) => true,
4432                Err(error) => {
4433                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4434                    false
4435                }
4436            }
4437        } else {
4438            false
4439        };
4440        if !authorized {
4441            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())));
4442            // Retain the existing stop identity when an old release reached the queue.
4443            task.base_sync_notice(&held);
4444            task.resume_override = None;
4445            record(queue, task);
4446            return Vec::new();
4447        }
4448    }
4449    let unfinished = (!task.fresh_start)
4450        .then(|| unfinished_run(&resume_runs, task.short()))
4451        .flatten()
4452        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4453    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4454    if !task.fresh_start
4455        && task.pr_recovery.is_none()
4456        && task.review_branch.is_none()
4457        && task.resume_override.is_none()
4458        && previous
4459            .as_ref()
4460            .is_some_and(|run| run.retired_to.is_some())
4461        && unfinished.is_none()
4462    {
4463        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()));
4464        record(queue, task);
4465        return Vec::new();
4466    }
4467
4468    let saved_recovery = previous.as_ref().filter(|run| {
4469        task.replacement.is_none()
4470            && task.pr_recovery.as_ref().is_some_and(|selected| {
4471                selected
4472                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4473                    .is_ok()
4474                    && selected_starter(selected, Some(run), unfinished.as_deref())
4475                        == Starter::Resume(run.id.clone())
4476            })
4477    });
4478
4479    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4480    // failure here is the network's or the operator's, not the task's: hold
4481    // without spending an attempt, never fall back to a possibly stale copy.
4482    let explicit = match &task.overrides {
4483        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4484        Some(_) => opts.config.as_deref(),
4485        None => opts.config.as_deref(),
4486    };
4487    let (mut config, layers) = if let Some(run) = saved_recovery {
4488        // A matching resume owns its resolved configuration and evidence;
4489        // current layers and inherited overrides only configure new work.
4490        let mut saved = run.clone();
4491        if let Err(e) = saved.configure_recovery_resume() {
4492            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4493            record(queue, task);
4494            return Vec::new();
4495        }
4496        (saved.config, Vec::new())
4497    } else {
4498        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4499            Ok(loaded) => loaded,
4500            Err(e) => {
4501                let reason = format!("[config] {e:#}");
4502                record_config_failure(task, &e);
4503                task.last_error = Some(reason.clone());
4504                task.hold_machine(Some(reason));
4505                record(queue, task);
4506                return Vec::new();
4507            }
4508        };
4509        if let Err(e) = apply_options(&mut config, opts, task) {
4510            task.hold_manual(Some(format!(
4511                "[config] {e:#}; correct the merge override before releasing the task"
4512            )));
4513            record(queue, task);
4514            return Vec::new();
4515        }
4516        if let Some(selected) = &task.pr_recovery
4517            && let Err(e) = selected.configure(&mut config)
4518        {
4519            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4520            record(queue, task);
4521            return Vec::new();
4522        }
4523        (config, layers)
4524    };
4525    let config_evidence = crate::pr_recovery::ConfigEvidence {
4526        layers,
4527        overrides: task.overrides.clone(),
4528        daemon_merge: task
4529            .overrides
4530            .as_ref()
4531            .is_none_or(|o| o.inherit_daemon_options)
4532            .then(|| opts.merge.clone())
4533            .flatten(),
4534    };
4535    apply_task_implementers(&mut config, task);
4536    if let Some(replacement) = &task.replacement {
4537        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4538            old.liveness(false) == Liveness::Dead
4539                && old.merge_decision.as_ref().is_some_and(|d| {
4540                    d.closed
4541                        && d.question == replacement.question
4542                        && d.replacement_run.as_ref().is_none_or(|run| {
4543                            task.execution_runs().last() == Some(run)
4544                                && RunState::load(run).is_ok_and(|current| {
4545                                    current.replaces.as_ref().is_some_and(|pin| {
4546                                        pin.question == replacement.question
4547                                            && pin.agent == replacement.agent
4548                                    })
4549                                })
4550                        })
4551                })
4552        });
4553        if !safe {
4554            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()));
4555            record(queue, task);
4556            return Vec::new();
4557        }
4558        match config.agent(&replacement.agent) {
4559            Ok(agent) if crate::agent::installed(agent) => {}
4560            _ => {
4561                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)));
4562                record(queue, task);
4563                return Vec::new();
4564            }
4565        }
4566        config.graph.implementers = 1;
4567        config.graph.land_approval = true;
4568        config.merge.mode = MergeMode::Pr;
4569        config.graph.selected_implementer = Some(replacement.agent.clone());
4570    }
4571    let p = phrases(&config.graph.language);
4572    let start_failed = p.could_not_start;
4573    // Resolve once for both admission and settlement. The inputs are the
4574    // task's explicit sources (never prose), plus an explicit review source's
4575    // current head; review-only runs may rebase later, and neither fact can
4576    // refund a failed automatic generation.
4577    if let Ok(base) =
4578        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4579            .await
4580        && let Ok(head) =
4581            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4582    {
4583        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4584        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4585            let source = crate::git::rev_parse(&repo, branch)
4586                .await
4587                .unwrap_or_default();
4588            inputs.push_str(&format!(";review:{branch}:{source}"));
4589        }
4590        if let Some(reason) = task
4591            .recovery_exhausted(
4592                &head,
4593                &inputs,
4594                task.attempt_limit
4595                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4596            )
4597            .filter(|_| {
4598                !task.repair_grants.last().is_some_and(|receipt| {
4599                    RunState::load(&receipt.request.run)
4600                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4601                })
4602            })
4603        {
4604            task.hold_unrequested_retry(Some(reason));
4605            record(queue, task);
4606            return Vec::new();
4607        }
4608        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4609    }
4610
4611    // The free-space gate, checked *before* anything is minted: a task that
4612    // waits out a full disk costs nothing yet, and must not spend an attempt
4613    // or start a run the machine cannot finish. Held tasks stay in the list
4614    // for the human to see, and `magi task release` re-queues them when space
4615    // comes back - the same recovery as any other hold. A volume whose free
4616    // space cannot be measured closes the gate too: starting a run blind on a
4617    // disk that may be full is how the machine ends up with 6.7 GB free.
4618    if let Some(reason) = disk_gate(&repo, &config) {
4619        task.notice_cause("disk-space", None, None);
4620        task.last_error = Some(reason.clone());
4621        task.hold_machine(Some(reason.clone()));
4622        record(queue, task);
4623        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4624        // Stable wording - the free-space figures live in the task's hold
4625        // reason, and changing numbers would relight the bell every poll.
4626        notices::raise(
4627            Notice::warn(
4628                &format!("disk:{}", repo.display()),
4629                format!("Task {} held for want of free disk space: {reason}. Free some, then release it from the queue.", task.id),
4630            )
4631            .link(Link::Task {
4632                id: task.id.clone(),
4633            }),
4634        );
4635        return Vec::new();
4636    }
4637
4638    // A resumable run of this task is carried on, never re-competed. The
4639    // candidates are built and paid for, and a fresh competition races a
4640    // second implementation against them.
4641    //
4642    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4643    // started 3cbf on the same task a moment later, duplicating two and a
4644    // half hours of agent work. Then b25f stalled on a judge that timed out
4645    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4646    // was to blame for - and 4043 started **one second** later, buying three
4647    // fresh implementations to reach the same panel. `RunStatus::resumable`
4648    // rather than `!done()` is what catches the second case: a stall is
4649    // terminal, and its cheap recovery re-asks only the absent seats.
4650    //
4651    // A load failure is warned about rather than silently read as "not
4652    // resumable": the alternative is exactly what let a schema mismatch on
4653    // run `eba2` fall through to a full re-competition with nobody told why.
4654    // `crate::conduct` is what actually offers a better answer than
4655    // `Runner::start` here (see `Recovery::Review`), once this task's next
4656    // failure shows it up as `held`/`failed` with the run state unreadable.
4657    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
4658    // branch survived, and this reopens exactly that branch as a
4659    // review-only pass rather than resuming or competing again. Consumed
4660    // (cleared) here whichever way this goes, so it never outlives this one
4661    // attempt - see `queue::Task::review_branch`.
4662    let review_branch = if previous
4663        .as_ref()
4664        .is_some_and(|state| crate::repair_budget::pending(task, state))
4665    {
4666        None
4667    } else {
4668        take_review_branch(task, previous.as_ref())
4669    };
4670    let branch_exists = match &review_branch {
4671        Some(branch) => crate::git::branch_exists(&repo, branch)
4672            .await
4673            .unwrap_or(false),
4674        None => false,
4675    };
4676    // An explicit `magi review <branch>` is reviewed whatever happens to the
4677    // branch unless an explicit implementer change requires fresh work. An
4678    // unfinished run of the same task still wins, so a retry resumes.
4679    let proposed = review_retry_starter(
4680        task,
4681        previous.as_ref(),
4682        review_branch.as_deref(),
4683        branch_exists,
4684        unfinished.as_deref(),
4685    );
4686    let retry_selected = task.replacement.is_some()
4687        && task.resumption.is_some()
4688        && !task.fresh_start
4689        && previous.as_ref().is_some_and(|run| {
4690            run.replaces.is_some()
4691                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4692                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4693        });
4694    let stop_pin = task
4695        .resume_override
4696        .as_ref()
4697        .filter(|pin| {
4698            Questions::open()
4699                .get_for_effects(&pin.question_id)
4700                .is_ok_and(|q| {
4701                    q.node == land::APPROVAL_NODE
4702                        && q.resolution()
4703                            .as_deref()
4704                            .is_some_and(crate::merge_decision::stops)
4705                })
4706        })
4707        .and_then(|pin| pin.pinned_run.clone());
4708    let granted_run = task.repair_grants.last().and_then(|receipt| {
4709        let state = RunState::load(&receipt.request.run).ok()?;
4710        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
4711    });
4712    let starter = if let Some(run) = granted_run {
4713        Starter::Resume(run)
4714    } else if let Some(owner) = &public_owner {
4715        Starter::Resume(owner.id.clone())
4716    } else if let Some(run) = stop_pin {
4717        // Stop actions resume their exact owner even after seat-count edits;
4718        // they must never fall through to implementation or a takeover.
4719        Starter::Resume(run)
4720    } else if retry_selected {
4721        Starter::Resume(previous.as_ref().unwrap().id.clone())
4722    } else if let Some(selected) = &task.pr_recovery {
4723        if selected
4724            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4725            .is_ok()
4726        {
4727            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4728        } else {
4729            Starter::Review(selected.branch.clone())
4730        }
4731    } else {
4732        starter_with_implementers(task, previous.as_ref(), proposed)
4733    };
4734    // An explicit resume pin must never degrade into a new competition or
4735    // takeover, including when its run stops being eligible after the answer.
4736    if let Some(pin) = &task.resume_override
4737        && let Some(run) = &pin.pinned_run
4738        && starter != Starter::Resume(run.clone())
4739    {
4740        let run = run.clone();
4741        task.notice_cause("resume-owner", Some(&run), None);
4742        task.hold_machine(Some(format!(
4743            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4744            task.id
4745        )));
4746        record(queue, task);
4747        return Vec::new();
4748    }
4749    if task.replacement.is_some()
4750        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4751        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4752    {
4753        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()));
4754        record(queue, task);
4755        return Vec::new();
4756    }
4757    if let Some(reason) = retained_attempt_hold(
4758        task,
4759        &starter,
4760        config.disk.retained_attempt_limit,
4761        RunState::load,
4762    ) {
4763        // The review choice was consumed above. Preserve it across this hold
4764        // so a later release cannot silently become a fresh implementation.
4765        if let Starter::Review(branch) = &starter {
4766            task.review_branch = Some(branch.clone());
4767        }
4768        task.hold_unrequested_retry(Some(reason));
4769        record(queue, task);
4770        return Vec::new();
4771    }
4772    // Absolute paths of the files the task was filed with, re-read from the
4773    // task now so a file attached while it was held reaches a resumed run
4774    // too. A stored name whose file has gone is an error before any agent is
4775    // paid for, never a silent omission the implementer cannot notice.
4776    let attachments = match task_attachments(queue, task) {
4777        Ok(a) => a,
4778        Err(e) => {
4779            task.attempts += 1;
4780            task.fail_startup_target(
4781                "startup-attachments",
4782                e.name.clone(),
4783                format!("{start_failed}{e:#}"),
4784                opts.max_attempts,
4785            );
4786            record(queue, task);
4787            return Vec::new();
4788        }
4789    };
4790    let startup_pause = stop.pause();
4791    let startup_interrupt = interrupt_pause.clone();
4792    let wait = crate::repo_lock::WaitPolicy::new(
4793        Duration::from_secs(config.graph.timeout_resource_wait),
4794        move || startup_pause.parked() || startup_interrupt.parked(),
4795    );
4796    // Startup includes review takeover and recovery. Do not embed its large
4797    // future in both the wait scope and the surrounding attempt stack frame.
4798    let started = wait.scope(Box::pin(async { match &starter {
4799        Starter::Review(_) if task.pr_recovery.is_some() => {
4800            let selected = task.pr_recovery.clone().expect("selected recovery");
4801            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
4802                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4803                    .await
4804                    .map(|mut r| {
4805                        r.state.attachments = attachments.clone();
4806                        r
4807                    }),
4808                Err(e) => Err(e),
4809            }
4810        }
4811        Starter::Review(branch) => {
4812            tracing::info!(
4813                "task {} reopens `{branch}` as a review-only pass",
4814                task.short()
4815            );
4816            // Every earlier attempt is superseded by the one being minted
4817            // now, so a branch one of them still holds may be taken over.
4818            let takeover = crate::handover::Takeover {
4819                earlier: task.earlier_attempts().to_vec(),
4820                home: crate::run::home(),
4821                choice: take_divergence_answer(branch, &config.merge.remote, task),
4822                task_instruction: Some(instruction_for(task)),
4823            };
4824            Runner::review_taking_over(
4825                &repo,
4826                branch,
4827                config,
4828                Some(takeover),
4829                crate::run::Origin::queue(&task.id),
4830            )
4831            .await
4832        }
4833        Starter::Resume(id) => {
4834            tracing::info!("resuming run {id} rather than competing again");
4835            Runner::resume(id).and_then(|mut r| {
4836                if retry_selected {
4837                    // The explicit queue release retries this same pinned
4838                    // implementation, preserving the attempt and worktrees.
4839                    for candidate in &mut r.state.candidates {
4840                        candidate.failed = None;
4841                        candidate.empty = false;
4842                        candidate.commits = 0;
4843                    }
4844                    r.state.status = RunStatus::Implementing;
4845                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4846                }
4847                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4848                    r.state.sources = task.sources.clone();
4849                }
4850                if r.state.prep_failure.is_some() {
4851                    let approval = task
4852                        .resumption
4853                        .as_ref()
4854                        .context("preparation retry requires an explicit task release")?;
4855                    r.retry_preparation(approval.at)?;
4856                }
4857                if let Some(instruction) =
4858                    prepare_instruction(&starter, Some(&r.state.instruction), task)
4859                {
4860                    r.state.instruction = instruction;
4861                }
4862                r.state.attachments = attachments.clone();
4863                if task.replacement.is_some() {
4864                    r.state.config.merge.mode = MergeMode::Pr;
4865                    r.state.config.graph.land_approval = true;
4866                }
4867                // Replacements publish a new PR and ask again. Selected PR
4868                // recoveries keep their saved disposition; ordinary runs can
4869                // retain the task's merge override.
4870                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4871                    .overrides
4872                    .as_ref()
4873                    .and_then(|o| o.merge.as_deref())
4874                    .and_then(|m| merge_mode(m).ok())
4875                {
4876                    r.state.config.merge.mode = mode;
4877                }
4878                Ok(r)
4879            })
4880        }
4881        Starter::Start => {
4882            if let Some(branch) = &review_branch {
4883                tracing::warn!(
4884                    "conductor chose review for task {} but branch `{branch}` no longer \
4885                     exists; requeuing as a fresh competition instead",
4886                    task.short()
4887                );
4888            }
4889            let instruction = prepare_instruction(&starter, None, task)
4890                .unwrap_or_else(|| task.instruction.clone());
4891            Runner::start_naming(
4892                &repo,
4893                instruction,
4894                &task.title,
4895                config,
4896                crate::run::Origin::queue(&task.id),
4897            )
4898            .await
4899            .map(|mut r| {
4900                r.state.attachments = attachments.clone();
4901                r.state.sources = task.sources.clone();
4902                r
4903            })
4904        }
4905    }})).await;
4906    if let Err(error) = &started
4907        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
4908    {
4909        task.record_startup_failure(failure.clone());
4910    }
4911    let mut runner = match started {
4912        Ok(r) => r,
4913        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4914            task.last_error = Some(e.to_string());
4915            if stop.parking() || interrupt_pause.parked() {
4916                let attempts = task.attempts;
4917                task.park(e.to_string());
4918                // Startup has not spent an attempt to refund.
4919                task.attempts = attempts;
4920            } else {
4921                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4922            }
4923            record(queue, task);
4924            return Vec::new();
4925        }
4926        // A branch an earlier attempt still holds and magi will not release
4927        // by itself is the operator's call, not a failed attempt: hold the
4928        // task with the reason, spend nothing, and say so on the bell.
4929        Err(e) if task.pr_recovery.is_some() => {
4930            task.startup_notice_cause("startup-public-head");
4931            task.attempts += 1;
4932            task.last_error = Some(format!("{start_failed}{e:#}"));
4933            task.hold_unrequested_retry(Some(format!(
4934                "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."
4935            )));
4936            record(queue, task);
4937            return Vec::new();
4938        }
4939        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4940            let detail = match e.downcast_ref::<crate::handover::Refused>() {
4941                Some(r) => (p.handover_refused)(r),
4942                None => format!("{e:#}"),
4943            };
4944            task.startup_notice_cause("startup-handover");
4945            let reason = format!("{start_failed}{detail}");
4946            task.last_error = Some(reason.clone());
4947            // Consumed above by `take`; keep it so the released task retries
4948            // as a review of this same branch.
4949            let branch = match &starter {
4950                Starter::Review(branch) => Some(branch.clone()),
4951                _ => None,
4952            };
4953            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
4954            // one page; the guidance rides in the reason, fixed per state so a
4955            // re-put never changes the wording and relights it.
4956            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4957            record(queue, task);
4958            tracing::warn!(
4959                "holding {} for a branch it cannot take over: {e:#}",
4960                task.short()
4961            );
4962            return Vec::new();
4963        }
4964        // A branch that differs between here and the remote in ways magi
4965        // cannot prove are the same change is a decision for the owner, not a
4966        // failed attempt: ask with both sides laid out, spend no attempt, and
4967        // let the answer requeue the task.
4968        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4969            let d = e
4970                .downcast_ref::<crate::reconcile::Diverged>()
4971                .expect("checked by the guard");
4972            let mut q = ask::Question::new(
4973                task.id.clone(),
4974                crate::reconcile::NODE.to_owned(),
4975                crate::reconcile::SEAT.to_owned(),
4976                d.summary(),
4977                d.detail(),
4978                d.choices(),
4979            );
4980            match Questions::open().put(&mut q) {
4981                Ok(()) => {
4982                    task.last_error = Some(format!("{e:#}"));
4983                    // Consumed above by `take`; the answer has to reach a review
4984                    // of this same branch, so keep pointing the task at it.
4985                    task.review_branch = Some(d.branch.clone());
4986                    task.review_instruction = Some(task.instruction.clone());
4987                    task.block(vec![q.id.clone()], Some(d.summary()));
4988                }
4989                Err(put) => {
4990                    tracing::warn!("could not file the divergence question: {put:#}");
4991                    task.attempts += 1;
4992                    task.fail_startup(
4993                        "startup-question-store",
4994                        format!("{start_failed}{e:#}"),
4995                        opts.max_attempts,
4996                    );
4997                }
4998            }
4999            record(queue, task);
5000            return Vec::new();
5001        }
5002        Err(e) => {
5003            // The answer was stale and nothing was applied: keep pointing at
5004            // the branch so the next attempt asks again against its new tips.
5005            // Nothing went wrong with the task, so no attempt is spent: a
5006            // budget one short of its limit must not hold it instead of
5007            // letting the question be asked again.
5008            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5009                && let Starter::Review(branch) = &starter
5010            {
5011                task.review_branch = Some(branch.clone());
5012                task.review_instruction = Some(task.instruction.clone());
5013                task.last_error = Some(format!("{start_failed}{e:#}"));
5014                task.status = crate::queue::TaskStatus::Failed;
5015                record(queue, task);
5016                return Vec::new();
5017            }
5018            task.attempts += 1;
5019            task.last_error = Some(format!("{start_failed}{e:#}"));
5020            task.startup_notice_cause("startup-source");
5021            task.hold_unrequested_retry(Some(format!(
5022                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5023            )));
5024            record(queue, task);
5025            return Vec::new();
5026        }
5027    };
5028    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5029        runner.state.recovery_config = Some(config_evidence);
5030    }
5031    if let Some(replacement) = &task.replacement {
5032        if matches!(starter, Starter::Start) {
5033            runner.state.instruction.push_str(&format!(
5034                "\n\n# Replacement review context\n{}",
5035                replacement.context
5036            ));
5037        }
5038        runner.state.replaces = Some(replacement.clone());
5039        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5040        if let Ok(mut old) = RunState::load(&replacement.run)
5041            && let Some(d) = &mut old.merge_decision
5042        {
5043            d.replacement_run = Some(runner.state.id.clone());
5044            old.event(
5045                "replacement",
5046                format!(
5047                    "replacement run {} owns the next attempt; old PR remains closed",
5048                    runner.state.id
5049                ),
5050            );
5051            if let Err(e) = old.save() {
5052                let error = runner.fail_startup("replacement-history", e);
5053                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5054                    task.record_startup_failure(failure.clone());
5055                }
5056                task.hold_manual(Some(format!(
5057                    "Could not link replacement history: {error:#}; no agents dispatched"
5058                )));
5059                record(queue, task);
5060                return Vec::new();
5061            }
5062        }
5063    }
5064    runner.state.task_instruction = Some(task.instruction.clone());
5065    // The follow-up depth is fixed now, while the task certainly exists:
5066    // deleting it later must not reset the cap (`crate::followup`).
5067    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5068    if runner.state.origin_chat.is_none() {
5069        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5070    }
5071    // A stop that means "park" reaches the graph through this handle.
5072    runner.on_pause(stop.pause());
5073    // `poll`'s interrupt scheduler reaches this one run - and no other -
5074    // through this handle. See `Pause`'s own doc for why these are never
5075    // the same one.
5076    runner.watch_interrupt(interrupt_pause);
5077
5078    // `start` has minted the run, so the task can now point at it. Persisting
5079    // `Running` before `execute` is what makes a crash mid-run legible.
5080    let run = runner.state.id.clone();
5081    let before_start = task.clone();
5082    task.start(run.clone());
5083    if let Err(error) = queue.put(task) {
5084        *task = before_start;
5085        let error = runner.fail_startup("task-start", error);
5086        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5087            task.record_startup_failure(failure.clone());
5088        }
5089        task.hold_manual(Some(format!(
5090            "Could not persist task start; no agents dispatched: {error:#}"
5091        )));
5092        record(queue, task);
5093        return Vec::new();
5094    }
5095    lock(status).current.push(Current {
5096        worker: None,
5097        task: task.id.clone(),
5098        run,
5099    });
5100
5101    // `RunState::quota` is the run's whole history across every resume, so
5102    // only what this execution added may arm the cooldown or earn a refund.
5103    let quota_before = runner.state.quota.clone();
5104    runner.state.carry_dispatched_resumes(task);
5105    runner.state.next_pass_task_entry = true;
5106    let result = runner.execute().await;
5107    finish_attempt(
5108        opts.max_attempts,
5109        queue,
5110        task,
5111        &runner.state,
5112        &quota_before,
5113        result,
5114    )
5115}
5116
5117/// Settle `task` after its run executed: the verdict, the diagnosis, the
5118/// supersession of earlier attempts and the save. Shared by the loop and by
5119/// `magi run --resume`, so an attempt is counted one way wherever it ran.
5120/// Returns the quota losses this execution added to the run.
5121pub fn finish_attempt(
5122    max_attempts: usize,
5123    queue: &Queue,
5124    task: &mut Task,
5125    state: &RunState,
5126    quota_before: &[QuotaLoss],
5127    result: Result<()>,
5128) -> Vec<QuotaLoss> {
5129    let detail = match result {
5130        Ok(()) => describe(state),
5131        Err(e) => format!("{e:#}"),
5132    };
5133    let fresh = losses_this_attempt(quota_before, &state.quota);
5134    let verdict = Verdict {
5135        status: state.status,
5136        // A run that opened a pull request handed its work over, whatever the
5137        // gate then decided about merging it.
5138        left_pr: state.pr.is_some(),
5139        // Only a rate limit earns the task its attempt back - and only one
5140        // suffered now: a refund justified by a previous session's loss is
5141        // the same mistake as re-arming the cooldown from it. A stalled run
5142        // resumed without hitting quota again therefore spends its attempt,
5143        // like any other failure of the task's own.
5144        quota_hit: !fresh.is_empty(),
5145        // A run that parked was asked to stop; that is not a failure and must
5146        // not spend an attempt, or replacing the binary a few times would
5147        // exhaust a task's budget without an agent ever misbehaving.
5148        parked: state.parked,
5149        // A quota loss that left nothing viable is the same machine fact as a
5150        // `Stalled` quota loss; see `settle`'s doc table.
5151        no_viable_candidates: state.viable().is_empty(),
5152    };
5153    if let Some(replacement) = &state.replaces
5154        && let Some(pr) = &state.pr
5155        && let Ok(mut old) = RunState::load(&replacement.run)
5156        && let Some(d) = &mut old.merge_decision
5157    {
5158        d.replacement_pr = Some(pr.url.clone());
5159        let _ = old.save();
5160    }
5161    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5162    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5163        task.hold_unrequested_retry(Some(format!(
5164            "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.",
5165            task.short()
5166        )));
5167    }
5168    if task.status == TaskStatus::Done {
5169        supersede_prior_runs(task, &crate::run::home());
5170    }
5171    record(queue, task);
5172    tracing::info!(
5173        "task {} is {} after run {} ({})",
5174        task.short(),
5175        task.status.as_str(),
5176        state.short(),
5177        label(state.status)
5178    );
5179    fresh
5180}
5181
5182/// A task a hand-started run leaves runnable (failed with attempts to spare,
5183/// or requeued) is **held**: nobody asked for a retry, and a loop starting
5184/// later must not spend agent calls on it. `magi task release` retries.
5185pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5186    // Parked work (including legacy Failed records with a parked run) is a
5187    // checkpoint or owner handoff, not an unrequested retry.
5188    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5189        && !awaiting_resume_with(task, RunState::load)
5190        // A run parked on the owner's word about a withheld PR title/body
5191        // resumes via `land_resume_state`, including review-only tasks that
5192        // `awaiting_resume_with` does not consider.
5193        && withheld_text_wait(task).is_none()
5194        && !(task.fresh_start && task.replacement.is_some())
5195    {
5196        let why = task.last_error.clone().map_or_else(
5197            || "the run did not finish".to_owned(),
5198            |e| format!("the run did not finish: {e}"),
5199        );
5200        task.hold_unrequested_retry(Some(format!(
5201            "{why}. It was started by hand, so it is not retried \
5202             automatically; `magi task release` retries it."
5203        )));
5204        record(queue, task);
5205    }
5206}
5207
5208/// Whether an attempt at a task whose newest run is `run` would resume that
5209/// run rather than start a fresh competition. `magi run --resume` hands a run
5210/// to a live loop only when this holds.
5211#[must_use]
5212pub fn loop_would_resume(run: &str) -> bool {
5213    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5214}
5215
5216/// A loop in another process that is alive right now: a fresh heartbeat in
5217/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
5218/// carries the pid it published (`None` inside when it published none - a
5219/// fresh heartbeat is still evidence of a live loop).
5220///
5221/// The one judgement of "is somebody else serving this queue", shared by the
5222/// web UI's refusal to start a second loop and by `magi run` / `magi review`
5223/// deciding whether to hand a task to the loop. A claim file proves nothing
5224/// here: whether a claim succeeds says nothing about whether its owner lives.
5225#[must_use]
5226pub fn foreign_loop(
5227    reading: Option<&Reading>,
5228    now: Timestamp,
5229    own_pid: u32,
5230) -> Option<Option<u32>> {
5231    let reading = reading.filter(|r| r.running(now))?;
5232    match reading.pid {
5233        Some(pid) if pid == own_pid => None,
5234        pid => Some(pid),
5235    }
5236}
5237
5238fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5239    reading.worker_protocol != Some(1)
5240        && (foreign_loop(Some(reading), now, own_pid).is_some()
5241            || reading
5242                .pid
5243                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5244}
5245
5246/// Low-level claimed-task execution shared by the detached standalone worker
5247/// and focused lifecycle fixtures. The caller must retain the queue claim for
5248/// this entire call. CLI callers transfer ownership through
5249/// [`run_detached_claimed`] instead of executing inside their own runtime.
5250///
5251/// The one deliberate difference from the loop: a task the attempt leaves
5252/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5253/// Nobody asked for a retry, and a daemon starting later must not spend agent
5254/// calls re-running a hand-started task behind the operator's back;
5255/// `magi task release` is the explicit retry.
5256pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5257    run_claimed_until(opts, queue, task, &Stop::new()).await;
5258}
5259
5260async fn run_claimed_until(
5261    opts: &Opts,
5262    queue: &Queue,
5263    task: &mut Task,
5264    stop: &Stop,
5265) -> Vec<QuotaLoss> {
5266    let status = Arc::new(Mutex::new(Status::new()));
5267    // An attempt embeds startup and graph futures. Keep it off the standalone
5268    // caller's stack, on both the initial execution and withheld-text resume.
5269    let mut quota = Box::pin(attempt(
5270        opts,
5271        queue,
5272        &status,
5273        stop,
5274        crate::graph::Pause::new(),
5275        task,
5276    ))
5277    .await;
5278    // A run parked on the owner's word about a withheld PR title/body has no
5279    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5280    // here with the claim still held, and resume once the question is settled
5281    // (answered, or abandoned at its deadline -> the neutral text).
5282    // A rejected reply files one more question (the gate asks at most twice),
5283    // so after a resume the run may be waiting again: keep going, with a fresh
5284    // limit for the new question. `resumes` bounds it even if a resume parks
5285    // without asking anything new.
5286    let mut resumes = 0;
5287    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5288        let Some(timeout) = withheld_text_wait(task) else {
5289            break;
5290        };
5291        eprintln!(
5292            "waiting for the owner's answer on a withheld pull request text \
5293             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5294        );
5295        // The deadline abandons the question itself; the extra margin only
5296        // covers an abandon that could not be saved.
5297        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5298        let ready = loop {
5299            match land_resume_state(task) {
5300                LandResume::StillWaiting
5301                    if !stop.parking() && std::time::Instant::now() < limit =>
5302                {
5303                    tokio::time::sleep(WITHHELD_POLL).await;
5304                }
5305                LandResume::Ready => break true,
5306                _ => break false,
5307            }
5308        };
5309        if !ready || stop.parking() {
5310            break;
5311        }
5312        resumes += 1;
5313        quota.extend(
5314            Box::pin(attempt(
5315                opts,
5316                queue,
5317                &status,
5318                stop,
5319                crate::graph::Pause::new(),
5320                task,
5321            ))
5322            .await,
5323        );
5324    }
5325    hold_if_runnable(queue, task);
5326    quota
5327}
5328
5329/// Resumes an in-process run makes for withheld-text questions: the gate asks
5330/// at most twice, plus one for a resume that asks nothing new.
5331const MAX_WITHHELD_RESUMES: u32 = 3;
5332
5333/// How often an in-process run rechecks its withheld-text question.
5334const WITHHELD_POLL: Duration = Duration::from_secs(15);
5335
5336/// The `answer_timeout` (seconds) of the task's last run when that run is
5337/// parked on an unresolved withheld-text question; `None` otherwise.
5338fn withheld_text_wait(task: &Task) -> Option<u64> {
5339    let id = task.execution_runs().last()?;
5340    let s = RunState::load(id).ok()?;
5341    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5342        .then_some(s.config.graph.answer_timeout)
5343}
5344
5345/// The quota losses `after` holds that `before` did not: what one execution
5346/// suffered, as opposed to the run's history.
5347///
5348/// Compared by value rather than by length or position because
5349/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5350/// the vector can shrink and shift under a resume. A retried seat that hits
5351/// quota again is a `push` with a new `at`, so it shows up as new here.
5352/// Crash recovery uses the recorded pass start as its boundary when available;
5353/// legacy records without passes retain their original history-based policy.
5354fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5355    after
5356        .iter()
5357        .filter(|q| !before.contains(q))
5358        .cloned()
5359        .collect()
5360}
5361
5362/// When the loop-wide quota cooldown should end, given this attempt's losses;
5363/// `None` when there were none. Reset-hint parsing and the cap live here.
5364fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5365    let quota: Vec<_> = quota
5366        .iter()
5367        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5368        .collect();
5369    if quota.is_empty() {
5370        return None;
5371    }
5372    let with_hint = quota.iter().find(|q| q.reset.is_some());
5373    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5374    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5375    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5376    Some(
5377        now.checked_add(jiff::SignedDuration::from_secs(secs))
5378            .unwrap_or(Timestamp::MAX),
5379    )
5380}
5381
5382/// An explicit task count must agree with a run before any resume.
5383fn implementers_match(task: &Task, state: &RunState) -> bool {
5384    task.replacement.as_ref().map_or_else(
5385        || {
5386            task.implementers()
5387                .is_none_or(|n| n == state.config.graph.implementers)
5388        },
5389        |replacement| {
5390            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5391                && state.config.graph.implementers == 1
5392        },
5393    )
5394}
5395
5396/// Never resume or take over candidate work built for a different seat count.
5397fn starter_with_implementers(
5398    task: &Task,
5399    previous: Option<&RunState>,
5400    proposed: Starter,
5401) -> Starter {
5402    if previous.is_some_and(|s| !implementers_match(task, s)) {
5403        task.review_of
5404            .as_ref()
5405            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5406    } else {
5407        proposed
5408    }
5409}
5410
5411/// Apply this task's explicit count to the new attempt, without changing defaults.
5412fn apply_task_implementers(config: &mut Config, task: &Task) {
5413    if let Some(n) = task.implementers() {
5414        config.graph.implementers = n;
5415    }
5416}
5417
5418/// [`prepare`] for one task: its own `--config` and command-line overrides
5419/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5420/// over the loop's, so handing a hand-started task to a daemon changes nothing
5421/// about what it does.
5422#[cfg(test)]
5423fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5424    let explicit = match &task.overrides {
5425        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5426        _ => opts.config.as_deref(),
5427    };
5428    let (mut config, _) = Config::discover(repo, explicit)?;
5429    apply_options(&mut config, opts, task)?;
5430    Ok(config)
5431}
5432
5433fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5434    if task
5435        .overrides
5436        .as_ref()
5437        .is_none_or(|o| o.inherit_daemon_options)
5438        && let Some(mode) = opts.merge.as_deref()
5439    {
5440        config.merge.mode = merge_mode(mode)?;
5441    }
5442    if let Some(o) = &task.overrides {
5443        o.apply(config);
5444    }
5445    Ok(())
5446}
5447
5448/// Load the config for a task's repository, with the merge override applied.
5449fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5450    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5451    if let Some(mode) = &opts.merge {
5452        config.merge.mode = merge_mode(mode)?;
5453    }
5454    Ok(config)
5455}
5456
5457/// Prune the shared build cache at a between-runs boundary. The detached cache
5458/// service checks authoritative task jobs first; dispatch waits for that finite
5459/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5460/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5461async fn maybe_prune_cache_between_runs(
5462    repo: &Path,
5463    opts: &Opts,
5464    home: &Path,
5465    stop: &Stop,
5466    last_checked: &mut Option<Timestamp>,
5467    now: Timestamp,
5468) {
5469    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5470        return;
5471    }
5472    *last_checked = Some(now);
5473    let cfg = match prepare(repo, opts) {
5474        Ok(cfg) => cfg,
5475        Err(e) => {
5476            tracing::warn!("cache check: no config: {e:#}");
5477            return;
5478        }
5479    };
5480    match clean::prune_cache_if_over_limit(&cfg, home) {
5481        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5482            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5483            pruned.files,
5484            pruned.freed
5485        ),
5486        Ok(_) => {}
5487        Err(e) => {
5488            tracing::warn!("housekeep: prune cache: {e:#}");
5489            notices::raise_in(
5490                home,
5491                Notice::warn(
5492                    "housekeep:cache",
5493                    format!(
5494                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5495                        e.to_string()
5496                            .lines()
5497                            .next()
5498                            .unwrap_or("unknown cleanup error")
5499                    ),
5500                ),
5501            );
5502        }
5503    }
5504}
5505
5506/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5507/// now, given when it last did (if ever). Pure, so the cadence is asserted
5508/// directly rather than by waiting out real minutes in a test.
5509fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5510    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5511}
5512
5513/// The disk janitor, with its housekeeping logged rather than fatal.
5514///
5515/// Called only at the loop's idle points, for the reason the caller documents:
5516/// a prune racing a live compile would delete files mid-build. The config is
5517/// re-read on every call because the repository that just ran may not be the
5518/// daemon's own default, and the cache directory is a repository fact.
5519///
5520/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5521/// and [`crate::run::default_worktree_root`] read here, for the same reason
5522/// [`drive`] takes its queue and status file rather than resolving them: a
5523/// test driving the loop must not reach through to the operator's real home
5524/// or worktree bay just because the janitor runs on every idle tick.
5525/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5526/// to get wrong silently - a test's `home` was already isolated, but nothing
5527/// exercised the parameter next to it, so a real worktree bay stayed wired in
5528/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5529/// it for real, every test in this file that drives the loop at all started
5530/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5531async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5532    let cfg = match prepare(repo, opts) {
5533        Ok(cfg) => cfg,
5534        Err(e) => {
5535            tracing::warn!("housekeep: no config: {e:#}");
5536            return;
5537        }
5538    };
5539    // A run's own worktree lives under `config.graph.worktree_root` when the
5540    // repository sets one - the same precedence `RunState::worktree_root`
5541    // uses - and `worktrees_root` only stands in for the *default* an
5542    // unconfigured repository resolves to (see this function's own
5543    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5544    // that always swept the default regardless of this override would never
5545    // see, and so never reclaim, a single worktree for a repository that
5546    // relocated them elsewhere.
5547    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5548    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5549    // Reported whenever there is anything to say, not only when `folded > 0`:
5550    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5551    // folded, on every single pass, for months - a report gated on `folded`
5552    // would have stayed silent through every one of them.
5553    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5554        let mut extra = Vec::new();
5555        if out.unreadable > 0 {
5556            extra.push(format!("{} unreadable", out.unreadable));
5557        }
5558        if out.orphaned_worktrees > 0 {
5559            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5560        }
5561        let detail = if extra.is_empty() {
5562            String::new()
5563        } else {
5564            format!(" ({})", extra.join(", "))
5565        };
5566        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5567    }
5568    if out.external_merges_recorded > 0 {
5569        tracing::info!(
5570            "housekeep: recorded {} run(s) as merged externally",
5571            out.external_merges_recorded
5572        );
5573    }
5574    if out.stale_pr_states_repaired > 0 {
5575        tracing::info!(
5576            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5577            out.stale_pr_states_repaired
5578        );
5579    }
5580    if out.cache_files > 0 {
5581        tracing::info!(
5582            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5583            out.cache_files,
5584            out.cache_freed
5585        );
5586    }
5587    if out.questions_abandoned > 0 {
5588        tracing::info!(
5589            "housekeep: abandoned {} question(s) left open by a finished run",
5590            out.questions_abandoned
5591        );
5592    }
5593}
5594
5595/// Run [`triage::run_once`] and log whatever it did, the same "only when
5596/// there is something to say" rule [`janitor`] follows for its own report.
5597///
5598/// Called at the same idle points as [`janitor`] - once per full poll
5599/// interval, never mid-attempt - for the same reason: it is not liveness
5600/// critical, and a task's own `hold_reason` string is the one thing this
5601/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5602/// tick for no benefit.
5603async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5604    let questions = Questions::at(home.join("questions"));
5605    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5606    if report.is_empty() {
5607        return;
5608    }
5609    if !report.quarantined.is_empty() {
5610        tracing::info!(
5611            "triage: held {} blocked task(s) whose blocked-on task or \
5612             question no longer exists: {}",
5613            report.quarantined.len(),
5614            report.quarantined.join(", ")
5615        );
5616    }
5617    if !report.resumed.is_empty() {
5618        tracing::info!(
5619            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5620            report.resumed.len(),
5621            report.resumed.join(", ")
5622        );
5623    }
5624    if !report.asked.is_empty() {
5625        tracing::info!(
5626            "triage: asked about {} held task(s): {}",
5627            report.asked.len(),
5628            report.asked.join(", ")
5629        );
5630    }
5631    if !report.answered.is_empty() {
5632        tracing::info!(
5633            "triage: applied {} operator answer(s): {}",
5634            report.answered.len(),
5635            report.answered.join(", ")
5636        );
5637    }
5638}
5639
5640/// The free-space gate: what stands between this task and a new run, if
5641/// anything. `Some(reason)` holds the task; `None` lets it start.
5642///
5643/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5644/// the operator opted out. A measurement failure is a gate, not a pass: both
5645/// sides of "cannot tell" are served by not starting.
5646pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5647    disk_gate_with(repo, config, crate::disk::free_bytes)
5648}
5649
5650/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
5651/// test can assert the exact wiring `attempt` runs - config's threshold in,
5652/// task-holding reason out - without asking the real machine's disk anything.
5653fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5654    repo: &Path,
5655    config: &Config,
5656    free_bytes: F,
5657) -> Option<String> {
5658    let min = config.disk.min_free_bytes;
5659    if min == 0 {
5660        return None;
5661    }
5662    let mut paths = vec![repo.to_owned()];
5663    if let Some(cache) = config.cache_dir() {
5664        paths.push(cache);
5665    }
5666    if let Some(root) = &config.graph.worktree_root {
5667        paths.push(root.clone());
5668    }
5669    for path in paths {
5670        let probe = if path == repo {
5671            path.as_path()
5672        } else {
5673            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5674        };
5675        let reason = match free_bytes(probe) {
5676            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5677            Err(e) => Some(crate::disk::unmeasured_in(
5678                probe,
5679                &e,
5680                &config.graph.language,
5681            )),
5682        };
5683        if reason.is_some() {
5684            return reason;
5685        }
5686    }
5687    None
5688}
5689
5690/// How long to wait before offering another task when a run lost a seat to a
5691/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
5692/// could read, or carried nothing at all. Long enough that a quota outage
5693/// cannot burn through a whole backlog in the few seconds each doomed attempt
5694/// takes to fail; short enough that a quota which clears early is not left
5695/// idle for the fallback's sake.
5696const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5697
5698/// Longest a parsed reset hint may push the wait out to. The hint comes from
5699/// the CLI's own words, not a contract, so a parsing slip that lands a day
5700/// away must not leave the loop asleep for a day.
5701const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5702
5703/// How long [`poll`] should wait before offering the next task, after a run
5704/// lost at least one seat to a rate limit.
5705///
5706/// Pure and separate from the loop so the policy can be exercised without a
5707/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
5708/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
5709/// nothing to parse, or the parsed time has already passed; `cap` bounds how
5710/// far a parsed hint is trusted to push the wait out.
5711fn quota_wait(
5712    reset_at: Option<Timestamp>,
5713    now: Timestamp,
5714    fallback: Duration,
5715    cap: Duration,
5716) -> Duration {
5717    match reset_at {
5718        Some(at) if at > now => {
5719            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5720            Duration::from_secs(secs).min(cap)
5721        }
5722        _ => fallback,
5723    }
5724}
5725
5726/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
5727///
5728/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
5729/// explains why parsing it exactly "would be a bug factory" — so this only
5730/// recognises the shapes actually observed in the wild, and returns `None`
5731/// for anything else rather than guess at a format nobody has seen.
5732///
5733/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
5734/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
5735/// said it, not from whenever this loop happens to read it: anchoring on `now`
5736/// would push the reset later on every read and would read an already-elapsed
5737/// reset as still in the future. (A long hint is still clamped by
5738/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
5739fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5740    parse_reset_hint_zoned(text, now)
5741        .or_else(|| parse_reset_hint_dated(text))
5742        .or_else(|| parse_reset_hint_relative(text, recorded))
5743}
5744
5745/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
5746/// optional but at least one required, in that order. A bare number or any
5747/// unknown unit is refused.
5748fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5749    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5750    let mut rest = rest.trim();
5751    if rest.is_empty() {
5752        return None;
5753    }
5754    let mut total: i64 = 0;
5755    let mut matched = false;
5756    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5757        if let Some((digits, tail)) = rest.split_once(unit)
5758            && !digits.is_empty()
5759            && digits.bytes().all(|b| b.is_ascii_digit())
5760        {
5761            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5762            rest = tail;
5763            matched = true;
5764        }
5765    }
5766    if !rest.is_empty() || !matched {
5767        return None;
5768    }
5769    recorded
5770        .checked_add(jiff::SignedDuration::from_secs(total))
5771        .ok()
5772}
5773
5774/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
5775/// case-insensitive) into a 24-hour hour and minute. Shared by every
5776/// reset-hint shape below.
5777fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5778    let clock = clock.trim().to_lowercase();
5779    let (digits, pm) = clock
5780        .strip_suffix("am")
5781        .map(|d| (d, false))
5782        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5783    let (h, m) = digits.trim().split_once(':')?;
5784    let mut hour: i8 = h.trim().parse().ok()?;
5785    let minute: i8 = m.trim().parse().ok()?;
5786    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5787        return None;
5788    }
5789    if pm && hour != 12 {
5790        hour += 12;
5791    } else if !pm && hour == 12 {
5792        hour = 0;
5793    }
5794    Some((hour, minute))
5795}
5796
5797/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
5798/// and a zone, never a date. A clock reading already past today is read as
5799/// tomorrow's: a CLI naming a same-day reset that has already gone by means
5800/// the window rolled over while nothing was watching.
5801fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5802    let open = text.find('(')?;
5803    let close = text.rfind(')')?;
5804    if close <= open {
5805        return None;
5806    }
5807    let zone = text[open + 1..close].trim();
5808    let (hour, minute) = parse_12h_clock(&text[..open])?;
5809    let tz = jiff::tz::TimeZone::get(zone).ok()?;
5810    let candidate = now
5811        .to_zoned(tz)
5812        .with()
5813        .hour(hour)
5814        .minute(minute)
5815        .second(0)
5816        .millisecond(0)
5817        .microsecond(0)
5818        .nanosecond(0)
5819        .build()
5820        .ok()?;
5821    let mut at = candidate.timestamp();
5822    if at <= now {
5823        at += jiff::SignedDuration::from_hours(24);
5824    }
5825    Some(at)
5826}
5827
5828/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
5829/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
5830/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
5831/// "already past today" correction to make: the year already disambiguates
5832/// it. Scanned as a five-word window so it can be pulled out of the middle
5833/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
5834/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
5835/// any other timestamp with no zone attached.
5836fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5837    let words: Vec<&str> = text.split_whitespace().collect();
5838    if words.len() < 5 {
5839        return None;
5840    }
5841    (0..=words.len() - 5)
5842        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5843}
5844
5845/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
5846/// parenthesis right after the window is refused rather than ignored — it
5847/// reads as an explicit zone annotation on a shape that otherwise carries
5848/// none, and guessing UTC anyway would be exactly the silent misread this
5849/// module's parsing otherwise avoids.
5850fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5851    if trailing.is_some_and(|next| next.starts_with('(')) {
5852        return None;
5853    }
5854    let month = month_number(window[0])?;
5855    let day_token = window[1].strip_suffix(',')?.to_lowercase();
5856    let day_digits = ["st", "nd", "rd", "th"]
5857        .iter()
5858        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5859    let day: i8 = day_digits.parse().ok()?;
5860    let year_token = window[2];
5861    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5862        return None;
5863    }
5864    let year: i16 = year_token.parse().ok()?;
5865    // The am/pm word carries the sentence's own trailing punctuation, e.g.
5866    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
5867    // reusing the same 12-hour clock reader the bracketed shape uses.
5868    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5869    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5870    let date = jiff::civil::Date::new(year, month, day).ok()?;
5871    let candidate = date
5872        .at(hour, minute, 0, 0)
5873        .to_zoned(jiff::tz::TimeZone::UTC)
5874        .ok()?;
5875    Some(candidate.timestamp())
5876}
5877
5878/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
5879/// case-insensitively, into a 1-based month number.
5880fn month_number(name: &str) -> Option<i8> {
5881    const NAMES: [&str; 12] = [
5882        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5883    ];
5884    let lower = name.to_lowercase();
5885    NAMES
5886        .iter()
5887        .position(|n| *n == lower.as_str())
5888        .map(|i| i as i8 + 1)
5889}
5890
5891/// Test probe for the shared resume policy's review-budget exclusion.
5892#[cfg(test)]
5893fn exhausted_review_budget(state: &RunState) -> bool {
5894    // A run whose task-head publication failed has nothing left to review:
5895    // resuming it only retries the publication, so it is never "exhausted".
5896    !crate::handover::can_resume(state)
5897        && state.status == RunStatus::Blocked
5898        && !state.released()
5899        && state.retired_to.is_none()
5900}
5901
5902/// This task's *most recent* run, if resuming it would actually make
5903/// progress. `short` is only for the warning's own message.
5904///
5905/// Only ever `runs.last()` — never a search back through older history.
5906/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
5907/// mint, oldest first, and every entry before the last one was already
5908/// superseded at the moment it was minted: the daemon only ever starts a new
5909/// run when the previous one was not worth resuming (unresumable, exhausted,
5910/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
5911/// opens a fresh review-only run alongside an older, already-failed
5912/// competition. Searching further back would let an old run that merely
5913/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
5914/// behind, say — get resumed instead of the fresh competition
5915/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
5916/// nothing asked to revisit.
5917///
5918/// Two runs paid for the "prefer resuming over restarting" half of this
5919/// lesson, which is why this still checks `runs.last()` rather than always
5920/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
5921/// task a moment later, duplicating two and a half hours of agent work. Then
5922/// b25f stalled on a judge that timed out and one that answered with no JSON
5923/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
5924/// **one second** later, buying three fresh implementations to reach the
5925/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
5926/// the second case: a stall is terminal, and its cheap recovery re-asks only
5927/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
5928/// that is technically `resumable()` but provably cannot progress must not
5929/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
5930/// no-op instead of the fresh competition it promises.
5931///
5932/// A load failure is warned about rather than silently read as "not
5933/// resumable": the alternative is exactly what let a schema mismatch on run
5934/// `eba2` fall through to a full re-competition with nobody told why.
5935/// `crate::conduct` is what actually offers a better answer than
5936/// `Runner::start` here (see `Recovery::Review`), once this task's next
5937/// failure shows it up as `held`/`failed` with the run state unreadable.
5938fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5939    unfinished_run_with(runs, short, RunState::load)
5940}
5941
5942/// [`unfinished_run`] with an injected state reader. Tests provide their
5943/// fixtures directly rather than touching the process-global run home.
5944pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5945where
5946    F: FnMut(&str) -> Result<RunState>,
5947{
5948    let mut id = runs.last()?.clone();
5949    let mut visited = std::collections::BTreeSet::new();
5950    let mut repo = None;
5951    loop {
5952        if !runs.contains(&id) || !visited.insert(id.clone()) {
5953            tracing::warn!("invalid or cyclic recovery authority for task {short}");
5954            return None;
5955        }
5956        let state = match load(&id) {
5957            Ok(state) if state.id == id => state,
5958            Ok(_) => return None,
5959            Err(e) => {
5960                tracing::warn!("could not read run {id} for task {short}: {e:#}");
5961                return None;
5962            }
5963        };
5964        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5965            return None;
5966        }
5967        repo = Some(state.repo.clone());
5968        if let Some(authority) = state.retired_to {
5969            id = authority;
5970            continue;
5971        }
5972        return (crate::handover::can_resume(&state)
5973            && state.liveness(false) != crate::run::Liveness::Live)
5974            .then_some(id);
5975    }
5976}
5977
5978/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
5979/// that [`attempt`] will resume it on its own?
5980///
5981/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
5982/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
5983/// injected reader like its sibling. An unreadable run is not awaiting
5984/// anything: it keeps going to the conductor as before.
5985fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5986where
5987    F: FnOnce(&str) -> Result<RunState>,
5988{
5989    // `Failed` stays: a record an older build wrote for a parked run.
5990    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5991        || task.fresh_start
5992        || task.review_branch.is_some()
5993    {
5994        return false;
5995    }
5996    let Some(id) = task.execution_runs().last() else {
5997        return false;
5998    };
5999    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6000}
6001
6002/// Which of the three ways [`attempt`] can mint or continue a run this task
6003/// should use.
6004#[derive(Debug, Clone, PartialEq, Eq)]
6005enum Starter {
6006    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
6007    /// and that still exists.
6008    Review(String),
6009    /// `crate::graph::Runner::resume` on an unfinished run of this task.
6010    Resume(String),
6011    /// `crate::graph::Runner::start`: a fresh competition.
6012    Start,
6013}
6014
6015/// A second bound independent of inputs and the resettable failure counter.
6016/// Count execution and failed-startup recovery records once per run. Startup
6017/// failures can retain unrecorded preparation assets without an execution pass.
6018/// Unknown history is not evidence that a new set of worktrees is affordable.
6019fn retained_attempt_hold(
6020    task: &Task,
6021    starter: &Starter,
6022    limit: usize,
6023    mut load: impl FnMut(&str) -> Result<RunState>,
6024) -> Option<String> {
6025    if limit == 0 || matches!(starter, Starter::Resume(_)) {
6026        return None;
6027    }
6028    let mut retained = 0;
6029    for id in task
6030        .runs
6031        .iter()
6032        .chain(task.startup_failures.iter().map(|failure| &failure.run))
6033        .collect::<std::collections::BTreeSet<_>>()
6034    {
6035        let state = match load(id) {
6036            Ok(state) if state.id == *id => state,
6037            _ => {
6038                return Some(format!(
6039                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6040                ));
6041            }
6042        };
6043        if state.retired_to.is_some() || state.released() {
6044            continue;
6045        }
6046        // Neither a completed status nor an empty candidate array proves that
6047        // all recovery sources (including unrecorded preparation) were retired.
6048        retained += 1;
6049    }
6050    (retained >= limit).then(|| format!(
6051        "[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."
6052    ))
6053}
6054
6055/// A selected public implementation overrides every historical candidate and pin.
6056fn selected_starter(
6057    selected: &crate::pr_recovery::Selection,
6058    previous: Option<&RunState>,
6059    unfinished: Option<&str>,
6060) -> Starter {
6061    if let Some(id) = unfinished
6062        && previous.is_some_and(|r| {
6063            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6064        })
6065    {
6066        Starter::Resume(id.to_owned())
6067    } else {
6068        Starter::Review(selected.branch.clone())
6069    }
6070}
6071
6072/// The owner's answer to this branch's divergence question, consumed from the
6073/// task so a later, different divergence asks again. The runner applies it
6074/// (see `Runner::review_taking_over`), after the earlier worktree is released.
6075fn take_divergence_answer(
6076    branch: &str,
6077    remote: &str,
6078    task: &mut Task,
6079) -> Option<crate::reconcile::Choice> {
6080    let summary = crate::reconcile::summary_for(branch, remote);
6081    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6082        (a.question == summary)
6083            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6084            .flatten()
6085            .map(|c| (i, c))
6086    })?;
6087    task.answers.remove(idx);
6088    Some(choice)
6089}
6090
6091/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
6092/// this attempt should use. Pure, and separate from [`attempt`], so the
6093/// routing itself is assertable without spawning a real graph or a git
6094/// process: `attempt`'s own `crate::git::branch_exists` call has already
6095/// happened by the time this is called.
6096///
6097/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
6098/// whose branch is gone falls all the way through to [`Starter::Start`], not
6099/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
6100/// old (likely `Blocked`) run in the first place, and a branch that vanished
6101/// out from under that choice is not evidence resuming it would fare better.
6102fn choose_starter(
6103    review_branch: Option<&str>,
6104    branch_exists: bool,
6105    unfinished: Option<&str>,
6106) -> Starter {
6107    match review_branch {
6108        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6109        Some(_) => Starter::Start,
6110        None => match unfinished {
6111            Some(id) => Starter::Resume(id.to_owned()),
6112            None => Starter::Start,
6113        },
6114    }
6115}
6116
6117/// Reuse a compatible latest review owner instead of taking its checked-out
6118/// branch into a new run. Different branches and changed criteria still use
6119/// the ordinary review/takeover policy.
6120fn review_retry_starter(
6121    task: &Task,
6122    previous: Option<&RunState>,
6123    branch: Option<&str>,
6124    exists: bool,
6125    unfinished: Option<&str>,
6126) -> Starter {
6127    if let Some(run) = previous
6128        && unfinished == Some(run.id.as_str())
6129        && run.reviewed_commits.is_some()
6130        && branch.is_some_and(|branch| {
6131            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6132        })
6133        && may_resume_run(run, task)
6134    {
6135        return Starter::Resume(run.id.clone());
6136    }
6137    match (branch, unfinished, &task.review_of) {
6138        (None, None, Some(branch)) => Starter::Review(branch.clone()),
6139        _ => choose_starter(branch, exists, unfinished),
6140    }
6141}
6142
6143/// Consume a retained review only while its authored criteria still match.
6144fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
6145    let branch = task.review_branch.take();
6146    let instruction = task.review_instruction.take();
6147    branch.filter(|branch| match &instruction {
6148        Some(authored) => *authored == task.instruction,
6149        // Legacy retained branches must agree with their prior run; only an
6150        // explicitly pinned review can proceed without recoverable provenance.
6151        None => previous.map_or_else(
6152            || task.review_of.as_ref() == Some(branch),
6153            |run| compatible_run_instruction(run, task),
6154        ),
6155    })
6156}
6157
6158/// A current explicit pin can select an otherwise incompatible run. Edits
6159/// and subsequent approvals invalidate pins selected for earlier criteria.
6160fn may_resume_run(run: &RunState, task: &Task) -> bool {
6161    if !task.assignment_accepts(run) {
6162        return false;
6163    }
6164    task.resume_override
6165        .as_ref()
6166        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6167        || compatible_run_instruction(run, task)
6168}
6169
6170/// Review scaffolding is execution context, not evidence of an operator edit.
6171pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6172    if let Some(authored) = &run.task_instruction {
6173        return compatible_instruction(authored, task);
6174    }
6175    if compatible_instruction(&run.instruction, task) {
6176        return true;
6177    }
6178    // Recognize only the existing generated review shapes on legacy runs.
6179    // Ordinary authored text with a similar heading is left intact.
6180    if run.reviewed_commits.is_some() {
6181        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6182            return strip_answers_block(authored, task).trim() == task.instruction.trim();
6183        }
6184        if let Some(branch) = &task.review_of {
6185            let canonical = format!(
6186                "Review the branch `{branch}` (review-only: no implementation, no judging)."
6187            );
6188            let generated = format!(
6189                "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"
6190            );
6191            return task.instruction == canonical && run.instruction.starts_with(&generated);
6192        }
6193    }
6194    false
6195}
6196
6197/// Compare authored instructions, excluding answer blocks appended by the daemon.
6198pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6199    strip_answers_block(old, task) == task.instruction
6200}
6201
6202/// Which repository a task runs in. A task that names none — the normal case
6203/// for one filed from a phone — runs in the daemon's own default.
6204fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6205    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6206        return fallback.to_path_buf();
6207    }
6208    task.repo.clone()
6209}
6210
6211/// The header [`append_answers`] appends operator answers under. Shared with
6212/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
6213/// rather than grown a new block on every resume.
6214const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6215
6216/// Render the first `count` answers in the block appended to an instruction.
6217fn answers_block(task: &Task, count: usize) -> String {
6218    let mut s = ANSWERS_HEADER.to_owned();
6219    for a in &task.answers[..count] {
6220        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6221    }
6222    s
6223}
6224
6225/// Render the approval independently of transient task state, so historical
6226/// suffixes remain recognizable after another explicit release.
6227fn resumption_block(r: &crate::queue::Resumption) -> String {
6228    format!(
6229        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6230         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6231        r.generation, r.at, r.instruction, r.answers_through,
6232    )
6233}
6234
6235/// Append audit answers and the latest explicit approval to the instruction.
6236fn append_answers(base: &str, task: &Task) -> String {
6237    let mut s = base.to_owned();
6238    if !task.answers.is_empty() {
6239        s.push_str(&answers_block(task, task.answers.len()));
6240    }
6241    if let Some(r) = &task.resumption {
6242        s.push_str(&resumption_block(r));
6243    }
6244    s
6245}
6246
6247/// Drop the prior answer block only when it is exactly the suffix this task
6248/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6249/// the task author is ordinary instruction text, not a block to remove.
6250fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6251    let mut instruction = instruction;
6252    for approval in task
6253        .resumption
6254        .iter()
6255        .chain(task.resumption_history.iter().rev())
6256    {
6257        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6258            instruction = base;
6259            break;
6260        }
6261    }
6262    for count in (1..=task.answers.len()).rev() {
6263        let block = answers_block(task, count);
6264        if let Some(base) = instruction.strip_suffix(&block) {
6265            return base;
6266        }
6267    }
6268    instruction
6269}
6270
6271/// The instruction handed to `Runner::start`: the task's own text, plus any
6272/// operator answers `crate::conduct` collected for it (see
6273/// [`Task::answers`]), so a decision the operator actually made reaches the
6274/// implementers rather than only clearing the block that was waiting on it.
6275///
6276/// Appended rather than merged into [`Task::instruction`] itself, so the
6277/// task's own record stays exactly what its author wrote.
6278fn instruction_for(task: &Task) -> String {
6279    append_answers(&task.instruction, task)
6280}
6281
6282/// The instruction a resumed run should carry on with: whatever it already
6283/// had, refreshed with the task's *current* operator answers.
6284///
6285/// A resumable run's own `RunState::instruction` predates any answer
6286/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6287/// the behaviour before this function existed — silently drops the very
6288/// decision the operator made to unblock it. Re-stripping any block this
6289/// function appended on an earlier resume before re-appending the current
6290/// list (rather than blindly appending again) is what keeps a task resumed
6291/// three times over three answered questions from carrying the same answer
6292/// three times.
6293fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6294    append_answers(strip_answers_block(old_instruction, task), task)
6295}
6296
6297/// Preserve the producer's verified boundary and target, independent of prose.
6298fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6299    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6300    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6301    if let Some(cause) = task.hold_notice_cause.as_mut() {
6302        cause.target = failure.map(|f| f.target.clone());
6303    }
6304}
6305
6306#[derive(Debug, thiserror::Error)]
6307#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6308struct MissingAttachment {
6309    name: String,
6310    path: PathBuf,
6311}
6312
6313/// The task's attachments as absolute paths, each checked to still exist.
6314fn task_attachments(
6315    queue: &Queue,
6316    task: &Task,
6317) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6318    let paths = queue.attachment_paths(task);
6319    for (name, path) in task.attachments.iter().zip(&paths) {
6320        if !path.is_file() {
6321            return Err(MissingAttachment {
6322                name: name.clone(),
6323                path: path.clone(),
6324            });
6325        }
6326    }
6327    Ok(paths)
6328}
6329
6330/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6331/// answers before handing it to `Runner` — the actual boundary between
6332/// [`choose_starter`]'s routing and the graph, factored out so it is
6333/// assertable without a real repository, git branch, or agent CLI.
6334///
6335/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6336/// instruction from the reviewed branch's own commit log because there is no
6337/// task statement to speak of for hand-written work, and splicing operator
6338/// answers into that text would contradict the very message it sends
6339/// reviewers ("there is no task statement").
6340fn prepare_instruction(
6341    starter: &Starter,
6342    old_instruction: Option<&str>,
6343    task: &Task,
6344) -> Option<String> {
6345    match starter {
6346        Starter::Start => Some(instruction_for(task)),
6347        Starter::Resume(_) => Some(resumed_instruction(
6348            old_instruction.expect("a resumed run always has a prior instruction"),
6349            task,
6350        )),
6351        Starter::Review(_) => None,
6352    }
6353}
6354
6355/// Persist a transition. A queue write failure is logged rather than fatal: the
6356/// run already happened, and taking the daemon down would only add a lost
6357/// backlog to a full disk.
6358fn record(queue: &Queue, task: &mut Task) {
6359    if let Err(e) = queue.put(task) {
6360        tracing::error!("could not record task {}: {e:#}", task.short());
6361        let notice = Notice::error(
6362            "loop:record",
6363            format!(
6364                "Task {} state could not be saved: {}. Check the disk.",
6365                task.id,
6366                e.to_string().lines().next().unwrap_or("unknown save error")
6367            ),
6368        )
6369        .link(Link::Task {
6370            id: task.id.clone(),
6371        });
6372        // The queue lives at `<home>/queue`, so its parent is the home.
6373        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6374            Some(home) => notices::raise_in(home, notice),
6375            None => notices::raise(notice),
6376        }
6377    }
6378}
6379
6380/// Every runnable task, in the order the loop should try them.
6381///
6382/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6383/// tail exists so that a claim somebody else holds costs the loop the next
6384/// candidate rather than a whole poll interval of idleness.
6385fn runnable(queue: &Queue) -> Vec<Task> {
6386    let mut tasks: Vec<Task> = queue
6387        .list()
6388        .into_iter()
6389        .filter(|t| t.status.runnable())
6390        .collect();
6391    tasks.sort_unstable_by(crate::queue::dispatch_order);
6392    tasks
6393}
6394
6395/// Why a run ended where it did, in one line, for [`Task::last_error`].
6396///
6397/// A stalled run names the seats the quota took out: "out of quota" is not
6398/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6399/// agent to replace or which plan to top up.
6400///
6401/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6402/// purpose: unlike `label`'s other callers (an internal log line, an
6403/// already-a-bug fallback message), this string becomes `Task::last_error`
6404/// verbatim, which the phone renders in the same alarm-styled box an
6405/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6406/// `.err` styling. A bare `verified_noop` there would read exactly like the
6407/// failure this whole feature exists to tell apart from one.
6408fn describe(state: &RunState) -> String {
6409    let p = phrases(&state.config.graph.language);
6410    let mut detail = if state.status == RunStatus::Stalled {
6411        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6412        seats.sort_unstable();
6413        seats.dedup();
6414        if seats.is_empty() {
6415            p.quorum_lost.to_owned()
6416        } else {
6417            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6418        }
6419    } else {
6420        format!("{}{}", p.run_ended, state.status.display_label())
6421    };
6422    if let Some(cause) = state.verification_blocking_cause() {
6423        detail.push_str(&format!(" ({cause})"));
6424    } else if let Some(last) = state.events.last() {
6425        // The review loop's "never answered" stop is the one event worth
6426        // translating; it is recognised from structured state, not by
6427        // matching the English event text (which stays as recorded).
6428        let unanswered = state
6429            .reviews
6430            .last()
6431            .filter(|r| {
6432                state.status == RunStatus::Blocked
6433                    && last.node == "review"
6434                    && r.incomplete()
6435                    && r.blocking == 0
6436                    && r.round == state.config.graph.review_rounds
6437                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6438            })
6439            .map(|r| (r.expected - r.answered, r.round));
6440        match unanswered {
6441            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6442                detail.push_str(&format!(
6443                    " ({}: {})",
6444                    last.node,
6445                    (p.reviewers_never_answered)(missing, rounds)
6446                ));
6447            }
6448            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6449        }
6450    }
6451    detail.push_str(&format!(" [run {}]", state.id));
6452    detail
6453}
6454
6455/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6456///
6457/// The task file lives in the backlog indefinitely; a diagnostic is an
6458/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6459/// stay small regardless of how much a gate command or a candidate printed.
6460const DIAGNOSTIC_MAX: usize = 4_000;
6461
6462/// Tail kept from a single failing command's output inside a diagnostic.
6463/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6464/// pointer for a human deciding whether to go read the full artifact by hand,
6465/// not a replacement for reading it.
6466const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6467
6468/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6469/// `magi task show` says more than the one-line reason in [`describe`].
6470///
6471/// The one-liner answers "where did the run stop"; this answers "what would a
6472/// human have found opening `artifacts/` by hand" — the point of the whole
6473/// feature is the case that one-liner actively misleads on: a run held as "no
6474/// candidate produced a change" can mean the implementer actually finished
6475/// the task (opened a PR, merged it, tagged a release) and only left a clean
6476/// local worktree behind, which reads as "nothing happened" unless someone
6477/// goes and reads what the agent actually said. `None` when the run carries
6478/// none of the three shapes this recognises — an ordinary run held for
6479/// something not diagnosable from `RunState` alone still explains itself
6480/// through `Task::last_error`.
6481fn diagnostic(state: &RunState) -> Option<String> {
6482    let mut parts: Vec<String> = Vec::new();
6483
6484    // Gate failure: which check(s), and the tail of what each printed.
6485    for o in state.gate.iter().filter(|o| !o.ok()) {
6486        parts.push(format!(
6487            "gate `{}` failed ({}):\n{}",
6488            o.command,
6489            notices::exit_status(o.code),
6490            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6491        ));
6492    }
6493
6494    // The land loop gave up because the fixer declined while checks were
6495    // still red: the message already names them (see `land::run`).
6496    if let Some(last) = state
6497        .events
6498        .iter()
6499        .rev()
6500        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6501    {
6502        parts.push(last.message.clone());
6503    }
6504
6505    // No viable candidate: every implementer's own final word, sanitized the
6506    // same way a judge would have read it, so a run that actually finished
6507    // the job does not read as an unexplained failure. A verified no-op is
6508    // called out ahead of its own summary and apart from an ordinary
6509    // failure's `why` — this is the one candidate shape whose diagnostic a
6510    // human is expected to actually judge, not just skim.
6511    if state.viable().is_empty() {
6512        for c in &state.candidates {
6513            if let Some(evidence) = &c.verified_noop {
6514                parts.push(format!(
6515                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6516                    c.label
6517                ));
6518            } else if !c.summary.trim().is_empty() {
6519                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6520            } else if let Some(why) = &c.failed {
6521                parts.push(format!("candidate {}: {why}", c.label));
6522            }
6523        }
6524    }
6525
6526    if parts.is_empty() {
6527        return None;
6528    }
6529    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6530    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6531    // back slightly over. Leave it enough room to always land under the
6532    // limit.
6533    Some(crate::run::tail(
6534        &parts.join("\n\n"),
6535        DIAGNOSTIC_MAX.saturating_sub(100),
6536    ))
6537}
6538
6539/// Stable lower-case name for a run status, for an internal log line and the
6540/// "graph stopped without reaching a terminal status" bug message in
6541/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6542/// doc for why that one reads [`RunStatus::display_label`] instead. One
6543/// definition of a status's name, on the type that owns it: this table used
6544/// to live here as a second copy, and a status renamed in one place would
6545/// have gone on reading correctly in the other.
6546fn label(status: RunStatus) -> &'static str {
6547    status.as_str()
6548}
6549
6550/// Parse a merge mode override.
6551pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6552    match mode {
6553        "none" => Ok(MergeMode::None),
6554        "local" => Ok(MergeMode::Local),
6555        "pr" => Ok(MergeMode::Pr),
6556        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6557    }
6558}
6559
6560/// Take the status lock, recovering from a poisoned one.
6561///
6562/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6563/// data, and the worst a poisoned lock can hold is a stale timestamp.
6564fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6565    mutex
6566        .lock()
6567        .unwrap_or_else(std::sync::PoisonError::into_inner)
6568}
6569
6570#[cfg(test)]
6571mod tests {
6572    use super::*;
6573    use crate::queue::{Source, TaskStatus};
6574    use crate::run::{Candidate, CommandOutcome};
6575    use pretty_assertions::assert_eq;
6576
6577    fn task() -> Task {
6578        Task::new(
6579            "add retries".to_owned(),
6580            "add retries".to_owned(),
6581            PathBuf::from("/repo"),
6582            Source::Human,
6583        )
6584    }
6585
6586    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6587        let job = crate::worker::Job {
6588            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6589            sequence: 1,
6590            kind: "task".into(),
6591            key: format!("task:{}", request.task),
6592            payload: serde_json::to_value(request).unwrap(),
6593            generation: "a".repeat(64),
6594            version: None,
6595            status: crate::worker::Status::Starting,
6596            result: None,
6597            pid: None,
6598            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6599            finished_at: None,
6600        };
6601        let dir = home.join("workers/jobs").join(&job.id);
6602        std::fs::create_dir_all(&dir).unwrap();
6603        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6604        job
6605    }
6606
6607    #[test]
6608    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6609        let home = tempfile::tempdir().unwrap();
6610        let request = TaskWorker {
6611            opts: Opts::default(),
6612            queue: home.path().join("queue"),
6613            task: "startup".into(),
6614            lane: PermitKind::Ordinary,
6615            standalone: false,
6616        };
6617        let job = starting_task_reservation(home.path(), &request);
6618        let error = task_worker_spawn_error(
6619            home.path(),
6620            &request,
6621            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6622        )
6623        .expect_err("our own reservation must not turn a failed spawn into a resync");
6624        let active = crate::worker::active(home.path()).unwrap();
6625        assert_eq!(active.len(), 1);
6626        assert_eq!(active[0].id, job.id);
6627        assert_eq!(active[0].status, crate::worker::Status::Starting);
6628        assert!(
6629            crate::worker::control(home.path(), &job.key)
6630                .unwrap()
6631                .is_none()
6632        );
6633        let notices = notices::Notices::at(home.path().join("notifications")).list();
6634        assert_eq!(notices.len(), 1);
6635        assert_eq!(notices[0].key, "loop:worker-startup");
6636        assert!(!notices[0].message.contains("private-error-detail"));
6637        assert!(notices[0].message.contains(&request.task));
6638        assert!(
6639            notices[0]
6640                .message
6641                .contains("could not be started or acknowledged")
6642        );
6643        assert!(notices[0].message.contains("worker.log"));
6644        assert_eq!(
6645            notices[0].link,
6646            Some(Link::Task {
6647                id: request.task.clone()
6648            })
6649        );
6650        assert!(format!("{error:#}").contains("private-error-detail"));
6651    }
6652
6653    #[test]
6654    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6655        let home = tempfile::tempdir().unwrap();
6656        let mut request = TaskWorker {
6657            opts: Opts::default(),
6658            queue: home.path().join("queue"),
6659            task: "handoff".into(),
6660            lane: PermitKind::Ordinary,
6661            standalone: true,
6662        };
6663        let job = starting_task_reservation(home.path(), &request);
6664        request.standalone = false;
6665        task_worker_spawn_error(
6666            home.path(),
6667            &request,
6668            anyhow::anyhow!("operation key is already reserved for a different request"),
6669        )
6670        .expect("a different standalone request is the handoff race, not our startup failure");
6671        let active = crate::worker::active(home.path()).unwrap();
6672        assert_eq!(active.len(), 1);
6673        assert_eq!(active[0].id, job.id);
6674        assert_eq!(active[0].payload, job.payload);
6675        assert!(
6676            notices::Notices::at(home.path().join("notifications"))
6677                .list()
6678                .is_empty()
6679        );
6680    }
6681
6682    #[test]
6683    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6684        let home = tempfile::tempdir().unwrap();
6685        let queue = Queue::at(home.path().join("queue"));
6686        let mut task = task();
6687        task.runs = vec!["previous".into()];
6688        queue.put(&mut task).unwrap();
6689        let request = TaskWorker {
6690            opts: Opts::default(),
6691            queue: home.path().join("queue"),
6692            task: task.id.clone(),
6693            lane: PermitKind::Ordinary,
6694            standalone: false,
6695        };
6696        let job = starting_task_reservation(home.path(), &request);
6697        let claims = current_work(home.path(), Timestamp::now());
6698        assert_eq!(claims.len(), 1);
6699        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6700        assert_eq!(claims[0].run, "previous");
6701        assert!(other_claims_run(&claims, "previous", None));
6702        // Only after confirming the executing caller may admission ignore
6703        // this exact projection. Cleanup continues to observe it as live.
6704        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6705        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6706    }
6707
6708    #[test]
6709    fn admission_excludes_only_the_callers_exact_reservation() {
6710        let own = Current {
6711            worker: Some("own".into()),
6712            task: "same-task".into(),
6713            run: "previous".into(),
6714        };
6715        assert!(!other_claims_run(
6716            std::slice::from_ref(&own),
6717            "previous",
6718            Some("own")
6719        ));
6720        assert!(other_claims_run(
6721            std::slice::from_ref(&own),
6722            "previous",
6723            None
6724        ));
6725        for worker in [None, Some("other".into())] {
6726            let other = Current {
6727                worker,
6728                ..own.clone()
6729            };
6730            assert!(other_claims_run(
6731                &[own.clone(), other],
6732                "previous",
6733                Some("own")
6734            ));
6735        }
6736        let legacy: Current =
6737            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6738        assert!(other_claims_run(&[legacy], "previous", Some("own")));
6739    }
6740
6741    #[test]
6742    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6743        let mut task = task();
6744        let mut run = run_state(RunStatus::Reviewing);
6745        run.task_instruction = Some(task.instruction.clone());
6746        run.reviewed_commits = Some(vec!["committed-fix".into()]);
6747        let branch = "magi/test/B";
6748        run.candidates.push(crate::run::Candidate {
6749            branch: branch.into(),
6750            ..candidate('B', "preserved work", false, None)
6751        });
6752        task.runs = vec![run.id.clone()];
6753        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6754        assert_eq!(
6755            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6756            Starter::Resume(run.id.clone())
6757        );
6758        assert!(matches!(
6759            review_retry_starter(
6760                &task,
6761                Some(&run),
6762                Some("different"),
6763                true,
6764                unfinished.as_deref()
6765            ),
6766            Starter::Review(_)
6767        ));
6768        assert_eq!(
6769            review_retry_starter(
6770                &task,
6771                Some(&run),
6772                Some(branch),
6773                false,
6774                unfinished.as_deref()
6775            ),
6776            Starter::Start
6777        );
6778        task.instruction.push_str(" changed criteria");
6779        assert!(matches!(
6780            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6781            Starter::Review(_)
6782        ));
6783        assert!(matches!(
6784            review_retry_starter(&task, Some(&run), Some(branch), true, None),
6785            Starter::Review(_)
6786        ));
6787    }
6788
6789    #[test]
6790    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6791        let dir = tempfile::tempdir().unwrap();
6792        let queue = Queue::at(dir.path().join("queue"));
6793        let mut task = task();
6794        task.status = TaskStatus::Running;
6795        task.attempts = 1;
6796        queue.put(&mut task).unwrap();
6797        let live = std::collections::BTreeSet::from([task.id.clone()]);
6798        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6799        drop(queue.claim(&task.id).unwrap());
6800        let saved = queue.get(&task.id).unwrap();
6801        assert_eq!(saved.status, TaskStatus::Running);
6802        assert_eq!(saved.attempts, 1);
6803        assert!(saved.last_error.is_none());
6804    }
6805
6806    #[test]
6807    fn standalone_workers_do_not_consume_scheduler_lanes() {
6808        let request = |task: &str, lane, standalone| TaskWorker {
6809            opts: Opts::default(),
6810            queue: PathBuf::from("/queue"),
6811            task: task.to_owned(),
6812            lane,
6813            standalone,
6814        };
6815        let mut jobs = vec![
6816            request("ordinary", PermitKind::Ordinary, false),
6817            request("standalone-urgent", PermitKind::Urgent, true),
6818            request("standalone-ordinary", PermitKind::Ordinary, true),
6819            request("decision", PermitKind::None, false),
6820        ];
6821        assert_eq!(available_slots(&jobs, 2), (1, 1));
6822        jobs.push(request("urgent", PermitKind::Urgent, false));
6823        assert_eq!(available_slots(&jobs, 2), (1, 0));
6824        assert_eq!(available_slots(&jobs, 0), (0, 0));
6825    }
6826
6827    #[test]
6828    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6829        let now = Timestamp::now();
6830        let mut reading = Reading {
6831            pid: Some(std::process::id()),
6832            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6833            ..Reading::default()
6834        };
6835        assert!(!reading.running(now));
6836        assert!(legacy_scheduler_running(&reading, now, 0));
6837        reading.worker_protocol = Some(1);
6838        assert!(!legacy_scheduler_running(&reading, now, 0));
6839    }
6840
6841    #[test]
6842    fn selected_public_head_overrides_historical_resume_and_pin() {
6843        let mut t = task();
6844        let mut old = run_state(RunStatus::Blocked);
6845        let selection = crate::pr_recovery::Selection {
6846            url: "url".into(),
6847            branch: format!("magi/task-{}", t.id),
6848            head: "a".repeat(40),
6849            source_head: None,
6850            source_run: None,
6851            source_proof: None,
6852            disposition: Some(crate::pr_recovery::Disposition::Review),
6853            instruction: t.instruction.clone(),
6854            approved_at: Timestamp::now(),
6855        };
6856        t.resume_override = Some(crate::queue::OperatorResume {
6857            pinned_run: Some(old.id.clone()),
6858            question_id: "choice".into(),
6859            at: Timestamp::now(),
6860            conductor_rehold: None,
6861            forced: false,
6862        });
6863        assert_eq!(
6864            selected_starter(&selection, Some(&old), Some(&old.id)),
6865            Starter::Review(selection.branch.clone())
6866        );
6867        old.pr_recovery = Some(selection.clone());
6868        assert_eq!(
6869            selected_starter(&selection, Some(&old), Some(&old.id)),
6870            Starter::Review(selection.branch.clone())
6871        );
6872        old.reviewed_commits = Some(vec!["implementation".into()]);
6873        assert_eq!(
6874            selected_starter(&selection, Some(&old), Some(&old.id)),
6875            Starter::Resume(old.id.clone())
6876        );
6877        let mut changed = selection.clone();
6878        changed.head = "b".repeat(40);
6879        assert_eq!(
6880            selected_starter(&changed, Some(&old), Some(&old.id)),
6881            Starter::Review(changed.branch)
6882        );
6883    }
6884
6885    #[test]
6886    fn candidate_transplant_failure_is_one_actionable_hold() {
6887        let dir = tempfile::tempdir().unwrap();
6888        let q = Queue::at(dir.path().join("queue"));
6889        let mut t = task();
6890        let mut state = run_state(RunStatus::Blocked);
6891        state.event("prep", "cannot apply referenced commit: conflict");
6892        state.prep_failure = Some("conflict".into());
6893        t.start(state.id.clone());
6894        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6895        assert_eq!(t.attempts, 1);
6896        assert_eq!(t.status, TaskStatus::Held);
6897        assert!(t.operator_held());
6898        assert!(!t.status.runnable());
6899        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6900        let first = t.chat_notice_key().unwrap();
6901        t.chat_notices.push(first.clone());
6902        t.release_operator("test", None);
6903        state.id = "another-unprepared-run".into();
6904        t.start(state.id.clone());
6905        finish_attempt(
6906            3,
6907            &q,
6908            &mut t,
6909            &state,
6910            &[],
6911            Err(anyhow::anyhow!("still conflicts")),
6912        );
6913        assert_eq!(
6914            t.chat_notice_key().as_ref(),
6915            Some(&first),
6916            "no work happened"
6917        );
6918        t.release_operator("test", None);
6919        state.prep_failure = None;
6920        state.status = RunStatus::Failed;
6921        state.begin_pass();
6922        t.start(state.id.clone());
6923        finish_attempt(
6924            1,
6925            &q,
6926            &mut t,
6927            &state,
6928            &[],
6929            Err(anyhow::anyhow!("new gate failure")),
6930        );
6931        let failure = t.chat_notice_key().unwrap();
6932        assert_ne!(failure, first, "approved recovery reached a real failure");
6933        t.release_operator("test", None);
6934        state.begin_pass();
6935        t.start(state.id.clone());
6936        finish_attempt(
6937            1,
6938            &q,
6939            &mut t,
6940            &state,
6941            &[],
6942            Err(anyhow::anyhow!("new failure on resume")),
6943        );
6944        assert_ne!(
6945            t.chat_notice_key().as_ref(),
6946            Some(&failure),
6947            "a new settled pass"
6948        );
6949    }
6950
6951    #[test]
6952    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6953        for source in ["cli", "web"] {
6954            let mut t = task();
6955            let mut run = run_state(RunStatus::Blocked);
6956            run.instruction = "Run A original criteria".into();
6957            run.task_instruction = Some(run.instruction.clone());
6958            t.start(run.id.clone());
6959            t.release_operator("choice", Some("resume-question"));
6960            t.resume_override = Some(crate::queue::OperatorResume {
6961                question_id: "resume-question".into(),
6962                at: Timestamp::now(),
6963                conductor_rehold: None,
6964                forced: true,
6965                pinned_run: Some(run.id.clone()),
6966            });
6967            t.hold_machine(Some("not enough free space to start a run".into()));
6968            let mut unchanged = t.clone();
6969            unchanged
6970                .edit("title changed".into(), unchanged.instruction.clone())
6971                .unwrap();
6972            unchanged.release_operator(source, None);
6973            assert_eq!(
6974                unchanged
6975                    .resume_override
6976                    .as_ref()
6977                    .unwrap()
6978                    .pinned_run
6979                    .as_deref(),
6980                Some(run.id.as_str())
6981            );
6982            assert!(!compatible_run_instruction(&run, &unchanged));
6983            assert!(may_resume_run(&run, &unchanged));
6984
6985            t.edit(
6986                "approved recovery".into(),
6987                "Reuse measured PR head B; fix Clippy; review".into(),
6988            )
6989            .unwrap();
6990            assert!(t.resume_override.is_none());
6991            t.release_operator(source, None);
6992            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6993            assert!(reloaded.resume_override.is_none());
6994            assert!(!may_resume_run(&run, &reloaded));
6995            let unfinished =
6996                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6997                    .filter(|_| may_resume_run(&run, &reloaded));
6998            assert_eq!(
6999                choose_starter(None, false, unfinished.as_deref()),
7000                Starter::Start
7001            );
7002            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7003            assert_eq!(
7004                reloaded.resumption_history[0].question_id.as_deref(),
7005                Some("resume-question")
7006            );
7007
7008            // A revision already persisted with the old approval/pin is also
7009            // invalidated when the new operator release is recorded.
7010            unchanged.instruction = "Reuse measured PR head B".into();
7011            unchanged.hold_machine(Some("disk hold".into()));
7012            unchanged.release_operator(source, None);
7013            assert!(unchanged.resume_override.is_none());
7014            assert!(!may_resume_run(&run, &unchanged));
7015        }
7016    }
7017
7018    #[test]
7019    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7020        let mut t = task();
7021        let mut run = run_state(RunStatus::Blocked);
7022        t.review_of = Some("approved-head".into());
7023        t.instruction =
7024            "Review the branch `approved-head` (review-only: no implementation, no judging)."
7025                .into();
7026        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();
7027        run.reviewed_commits = Some(vec!["Commit log".into()]);
7028        t.start(run.id.clone());
7029        t.hold_machine(Some("interrupted review".into()));
7030        t.release_operator("cli", None);
7031        assert!(
7032            compatible_run_instruction(&run, &t),
7033            "legacy explicit review remains resumable"
7034        );
7035        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7036            .filter(|_| compatible_run_instruction(&run, &t));
7037        assert_eq!(
7038            choose_starter(None, false, unfinished.as_deref()),
7039            Starter::Resume(run.id.clone())
7040        );
7041        run.task_instruction = Some(t.instruction.clone());
7042        assert!(compatible_run_instruction(&run, &t));
7043        let reloaded: RunState =
7044            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7045        assert!(compatible_run_instruction(&reloaded, &t));
7046        t.edit(
7047            "new approved head".into(),
7048            "Reuse measured PR head B".into(),
7049        )
7050        .unwrap();
7051        assert!(!compatible_run_instruction(&run, &t));
7052
7053        // Legacy recovery reviews retain the task criteria ahead of the log.
7054        t.review_of = None;
7055        t.instruction = "Fix Clippy on approved head".into();
7056        run.task_instruction = None;
7057        run.instruction = format!(
7058            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7059            t.instruction
7060        );
7061        assert!(compatible_run_instruction(&run, &t));
7062        t.instruction.push('\n');
7063        assert!(
7064            compatible_run_instruction(&run, &t),
7065            "legacy generated review trimmed the original criteria"
7066        );
7067        t.hold_for_handover(Some("approved-head".into()), "refused".into());
7068        let mut unchanged = t.clone();
7069        assert_eq!(
7070            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
7071            Some("approved-head")
7072        );
7073        t.edit("new plan".into(), "Reuse measured PR head B".into())
7074            .unwrap();
7075        assert!(take_review_branch(&mut t, Some(&run)).is_none());
7076        assert!(!compatible_run_instruction(&run, &t));
7077        t.review_branch = Some("approved-head".into());
7078        t.review_instruction = None;
7079        assert!(
7080            take_review_branch(&mut t, Some(&run)).is_none(),
7081            "legacy retained candidate cannot replace a revised approved head"
7082        );
7083    }
7084
7085    #[test]
7086    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7087        let home = crate::run::test_home();
7088        crate::run::pin_test_home();
7089        let dir = tempfile::tempdir().unwrap();
7090        let queue = Queue::at(dir.path().join("queue"));
7091        for resume in [true, false] {
7092            let state = run_state(RunStatus::Blocked);
7093            let mut t = task();
7094            t.start(state.id.clone());
7095            let action = if resume {
7096                ask::ChoiceAction::Resume {
7097                    run: state.id.clone(),
7098                }
7099            } else {
7100                ask::ChoiceAction::Requeue
7101            };
7102            let mut q = action_question(&state.id, action);
7103            q.status = ask::QuestionStatus::Open;
7104            q.answer = None;
7105            q.answered_at = None;
7106            t.fail("run stopped with a question", 3);
7107            hold_if_runnable(&queue, &mut t);
7108            assert!(t.operator_decided_at.is_none());
7109            assert!(t.operator_held());
7110            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7111            let expected = if resume {
7112                ActionDecision::Resume(state.id.clone())
7113            } else {
7114                ActionDecision::Requeue
7115            };
7116            assert_eq!(
7117                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7118                expected
7119            );
7120            t.hold_manual(Some("later explicit hold".into()));
7121            assert_eq!(
7122                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7123                ActionDecision::Stale
7124            );
7125        }
7126    }
7127
7128    #[test]
7129    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7130        let mut t = task();
7131        t.answers.push(crate::queue::AnsweredQuestion {
7132            question: "Inspect the remote?".into(),
7133            answer: "Inspect then wait".into(),
7134        });
7135        let old = instruction_for(&t);
7136        assert!(compatible_instruction(&old, &t));
7137        t.instruction = "Reuse approved PR head and review".into();
7138        t.release_operator("cli", None);
7139        assert!(!compatible_instruction(&old, &t));
7140        let approved = instruction_for(&t);
7141        assert!(approved.contains("waiting premises are superseded"));
7142        assert!(compatible_instruction(&approved, &t));
7143        assert_eq!(resumed_instruction(&approved, &t), approved);
7144        t.release_operator("web", None);
7145        assert!(compatible_instruction(&approved, &t));
7146        assert_eq!(t.resumption_history.len(), 1);
7147        t.start("run".into());
7148        assert!(instruction_for(&t).contains("Explicit operator resumption"));
7149    }
7150
7151    /// A run that stopped on an infrastructure wait asked no agent anything:
7152    /// the task is held by the machine under a `[resource]` reason (resumable,
7153    /// re-checked by triage), and the attempt it started is given back.
7154    #[test]
7155    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7156        let mut state = RunState::new(
7157            PathBuf::from("/repo"),
7158            "main".into(),
7159            "base".into(),
7160            "task".into(),
7161            Config::default(),
7162        );
7163        state.status = RunStatus::Landing;
7164        state.parked = true;
7165        state.pr_pushed_head = Some("head".into());
7166        state.land_unrelated = Some(
7167            serde_json::from_value(serde_json::json!({
7168                "head": "head", "question": "ci-question",
7169                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7170            }))
7171            .unwrap(),
7172        );
7173        let mut t = task();
7174        t.start(state.id.clone());
7175        let verdict = Verdict {
7176            status: RunStatus::Landing,
7177            left_pr: true,
7178            quota_hit: false,
7179            parked: true,
7180            no_viable_candidates: false,
7181        };
7182        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7183        assert_eq!(t.attempts, 0);
7184        assert_eq!(t.status, TaskStatus::Held);
7185        assert!(!t.operator_held());
7186        assert!(
7187            t.hold_reason
7188                .as_deref()
7189                .unwrap()
7190                .starts_with("[ci-unrelated]")
7191        );
7192        // A second settlement must not refund an earlier task attempt.
7193        t.attempts = 1;
7194        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7195        assert_eq!(t.attempts, 1);
7196        assert_eq!(t.passes.len(), 1);
7197        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7198        state.pr_pushed_head = Some("new-head".into());
7199        state.parked = false;
7200        state.status = RunStatus::Blocked;
7201        let stale = Verdict {
7202            status: RunStatus::Blocked,
7203            parked: false,
7204            ..verdict
7205        };
7206        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7207        assert_eq!(t.attempts, 1);
7208        // A new execution pass can refund its own newly charged attempt.
7209        state.begin_pass();
7210        state.begin_pass();
7211        state.status = RunStatus::Landing;
7212        state.parked = true;
7213        state.pr_pushed_head = Some("head".into());
7214        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7215        assert_eq!(t.attempts, 0);
7216        assert_eq!(t.passes.len(), 2);
7217    }
7218
7219    #[test]
7220    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7221        let mut state = run_state(RunStatus::Failed);
7222        state
7223            .quota
7224            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7225        state.begin_pass();
7226        let mut t = task();
7227        t.start(state.id.clone());
7228        reclaim(&mut t, Some(state), 2, "en");
7229        assert_eq!(t.attempts, 1);
7230    }
7231
7232    #[test]
7233    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7234        let mut state = run_state(RunStatus::Blocked);
7235        let losses: Vec<_> = ["alpha", "beta"]
7236            .into_iter()
7237            .enumerate()
7238            .map(|(i, agent)| {
7239                QuotaLoss::from_report(
7240                    format!("advisor-{i}"),
7241                    "advise",
7242                    Some(&crate::agent::Quota {
7243                        cause: crate::agent::QuotaCause::Authentication,
7244                        agent: agent.to_owned(),
7245                        reset: None,
7246                    }),
7247                )
7248            })
7249            .collect();
7250        crate::graph::block_machine_outage(&mut state, "advise", &losses);
7251        state.quota = losses;
7252        let mut t = task();
7253        t.start(state.id.clone());
7254        let verdict = Verdict {
7255            status: state.status,
7256            left_pr: false,
7257            quota_hit: true,
7258            parked: false,
7259            no_viable_candidates: true,
7260        };
7261        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7262        assert_eq!(t.attempts, 0);
7263        assert_eq!(t.status, TaskStatus::Held);
7264        assert!(!t.operator_held());
7265        let reason = t.hold_reason.as_deref().unwrap();
7266        assert!(reason.starts_with("[authentication]"));
7267        assert!(
7268            reason.contains("alpha")
7269                && reason.contains("beta")
7270                && reason.contains("re-authenticate")
7271        );
7272        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7273        // Orphan recovery uses the same settlement and cannot spend an attempt.
7274        let mut orphan = task();
7275        orphan.start(state.id.clone());
7276        reclaim(&mut orphan, Some(state), 2, "en");
7277        assert_eq!(orphan.attempts, 0);
7278        assert_eq!(orphan.status, TaskStatus::Held);
7279    }
7280
7281    #[test]
7282    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7283        let mut state = RunState::new(
7284            PathBuf::from("/repo"),
7285            "main".to_owned(),
7286            "abc1234".to_owned(),
7287            "task".to_owned(),
7288            Config::default(),
7289        );
7290        state.status = RunStatus::Blocked;
7291        state.resource_block = Some(crate::run::ResourceBlock {
7292            cause: crate::run::ResourceBlockCause::Other,
7293            node: "graft".to_owned(),
7294            kind: "shared build cache".to_owned(),
7295            detail: "timed out".to_owned(),
7296            at: jiff::Timestamp::now(),
7297        });
7298        let mut t = task();
7299        t.start("20260902-000000-aaaa".to_owned());
7300        assert_eq!(t.attempts, 1);
7301        let verdict = Verdict {
7302            status: RunStatus::Blocked,
7303            left_pr: false,
7304            quota_hit: false,
7305            parked: false,
7306            no_viable_candidates: false,
7307        };
7308        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7309        assert_eq!(t.status, TaskStatus::Held);
7310        assert_eq!(t.attempts, 0, "the attempt is refunded");
7311        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7312        assert!(
7313            !t.operator_held(),
7314            "a machine hold, released without a human"
7315        );
7316
7317        let mut selected = task();
7318        selected.start("20260902-000000-cccc".into());
7319        selected.replacement = Some(crate::merge_decision::Replacement {
7320            question: "fixture".into(),
7321            run: "earlier".into(),
7322            pr: "https://example.invalid/pr/1".into(),
7323            agent: "selected".into(),
7324            context: "fixture".into(),
7325        });
7326        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7327        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7328        assert_eq!(selected.attempts, 0);
7329        assert!(
7330            !selected.operator_held(),
7331            "a selected agent also retains a machine resource hold"
7332        );
7333        assert!(
7334            selected
7335                .hold_reason
7336                .as_deref()
7337                .unwrap()
7338                .starts_with("[resource] ")
7339        );
7340
7341        // A park request outranks it: still the operator's doing.
7342        let mut p = task();
7343        p.start("20260902-000000-bbbb".to_owned());
7344        settle_and_diagnose(
7345            &mut p,
7346            Verdict {
7347                parked: true,
7348                ..verdict
7349            },
7350            "parked",
7351            2,
7352            &state,
7353        );
7354        assert_eq!(p.status, TaskStatus::Parked);
7355        assert_eq!(
7356            p.attempts, 0,
7357            "parking refunds once rather than also settling the resource hold"
7358        );
7359    }
7360
7361    #[test]
7362    fn record_failure_notice_links_the_task() {
7363        let dir = tempfile::tempdir().unwrap();
7364        // A regular file where the queue directory should be makes every
7365        // `put` fail, on every platform and whoever runs the test.
7366        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7367        let queue = Queue::at(dir.path().join("queue"));
7368        let mut t = interrupt_task("rec-fail-1");
7369        record(&queue, &mut t);
7370
7371        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7372        assert_eq!(found.len(), 1);
7373        assert_eq!(found[0].key, "loop:record");
7374        assert_eq!(
7375            found[0].link,
7376            Some(Link::Task {
7377                id: "rec-fail-1".to_owned()
7378            })
7379        );
7380    }
7381
7382    /// A runnable task marked to interrupt, with an id fixed for assertions
7383    /// rather than the random one [`Task::new`] mints.
7384    fn interrupt_task(id: &str) -> Task {
7385        let mut t = task();
7386        t.id = id.to_owned();
7387        t.interrupt = true;
7388        t
7389    }
7390
7391    /// An ordinary runnable task with an id fixed for assertions.
7392    fn task_with_id(id: &str) -> Task {
7393        let mut t = task();
7394        t.id = id.to_owned();
7395        t
7396    }
7397
7398    /// A runnable task marked `--urgent`, with an id fixed for assertions.
7399    fn urgent_task(id: &str) -> Task {
7400        let mut t = task();
7401        t.id = id.to_owned();
7402        t.urgent = true;
7403        t
7404    }
7405
7406    #[test]
7407    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7408        let dir = tempfile::tempdir().unwrap();
7409        let queue = Queue::at(dir.path().join("queue"));
7410        let mut parked = task_with_id("parked");
7411        parked.start("run".into());
7412        parked.park("upgrade");
7413        parked.record_pass_at(
7414            "run",
7415            0,
7416            Some(Timestamp::now()),
7417            1,
7418            Some(crate::run::ParkCause::Upgrade {
7419                from: "old".into(),
7420                to: None,
7421            }),
7422        );
7423        let mut fresh = task_with_id("fresh");
7424        fresh.priority = 100;
7425        let mut urgent_task = urgent_task("urgent");
7426        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7427            queue.put(t).unwrap();
7428        }
7429        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7430        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7431        let candidates = runnable(&queue);
7432        assert_eq!(candidates[0].id, parked.id);
7433        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7434        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7435        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7436        drop(first);
7437        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7438        let next = runnable(&queue)
7439            .into_iter()
7440            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7441            .unwrap();
7442        assert_eq!(next.task.id, fresh.id);
7443        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7444        drop(claimed_elsewhere);
7445        drop(next);
7446        assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7447    }
7448
7449    #[test]
7450    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7451        let dir = tempfile::tempdir().unwrap();
7452        let queue = Queue::at(dir.path().join("queue"));
7453        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7454        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7455        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7456        let mut first = task();
7457        queue.put(&mut first).unwrap();
7458        let stale_plain = queue.get(&first.id).unwrap();
7459        first.set_urgent(true).unwrap();
7460        queue.put(&mut first).unwrap();
7461        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7462        let mut second = urgent_task("second");
7463        queue.put(&mut second).unwrap();
7464        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7465        drop(queue.claim(&second.id).unwrap());
7466        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7467        drop(dispatched);
7468        let stale_urgent = queue.get(&first.id).unwrap();
7469        first.set_urgent(false).unwrap();
7470        queue.put(&mut first).unwrap();
7471        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7472        assert_eq!(urgent.available_permits(), 1);
7473        drop(queue.claim(&first.id).unwrap());
7474        drop(occupied);
7475    }
7476
7477    #[test]
7478    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7479        let dir = tempfile::tempdir().unwrap();
7480        let queue = Queue::at(dir.path().join("queue"));
7481        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7482        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7483        let mut t = task();
7484        queue.put(&mut t).unwrap();
7485        for enabled in [true, false] {
7486            let stale = queue.get(&t.id).unwrap();
7487            t.set_urgent(enabled).unwrap();
7488            queue.put(&mut t).unwrap();
7489            assert_ne!(stale.urgent, enabled);
7490            let DispatchClaim {
7491                task: fresh,
7492                claim,
7493                permit,
7494            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7495            assert_eq!(fresh.urgent, enabled);
7496            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7497            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7498            assert!(queue.claim(&t.id).is_err());
7499            assert_eq!(fresh.attempts, stale.attempts);
7500            drop((claim, permit));
7501            assert_eq!(ordinary.available_permits(), 1);
7502            assert_eq!(urgent.available_permits(), 1);
7503        }
7504        t.set_urgent(true).unwrap();
7505        queue.put(&mut t).unwrap();
7506        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7507        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7508        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7509        drop(queue.claim(&t.id).unwrap());
7510        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7511        drop(occupied);
7512        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7513        drop(queue.claim(&t.id).unwrap());
7514        let held = queue.claim(&t.id).unwrap();
7515        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7516        drop(held);
7517        t.status = TaskStatus::Held;
7518        queue.put(&mut t).unwrap();
7519        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7520        drop(queue.claim(&t.id).unwrap());
7521        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7522        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7523        drop(queue.claim(&t.id).unwrap());
7524        assert_eq!(urgent.available_permits(), 1);
7525    }
7526
7527    /// The land-resume exemption wins outright, whether or not the candidate
7528    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7529    /// queue behind anything" guarantee cannot be weaker just because the
7530    /// same task was also filed with `--urgent`.
7531    #[test]
7532    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7533        assert_eq!(permit_kind(true, false), PermitKind::None);
7534        assert_eq!(permit_kind(true, true), PermitKind::None);
7535    }
7536
7537    /// The one property this whole feature exists for: `--urgent` draws from
7538    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7539    /// ordinary candidate draws from the ordinary pool exactly as before,
7540    /// untouched by the urgent slot's existence.
7541    #[test]
7542    fn permit_kind_separates_urgent_from_ordinary() {
7543        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7544        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7545    }
7546
7547    /// The exact wiring `attempt` runs before minting anything: a config's
7548    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7549    /// Free space is injected rather than asked of the real disk - the point
7550    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7551    /// is deterministic on every machine this test runs on, never dependent
7552    /// on how full the CI runner's own disk happens to be.
7553    #[test]
7554    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7555        let cfg = Config::default();
7556        let repo = Path::new("/any/repo/path");
7557
7558        let reason =
7559            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7560        assert!(reason.contains("1024"), "{reason}");
7561        assert!(
7562            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7563            "{reason}"
7564        );
7565
7566        assert_eq!(
7567            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7568            None,
7569            "exactly at the floor is open"
7570        );
7571        assert_eq!(
7572            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7573            None,
7574            "comfortably above the floor is open"
7575        );
7576    }
7577
7578    #[test]
7579    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7580        let mut cfg = Config::default();
7581        cfg.disk.min_free_bytes = 0;
7582        let repo = Path::new("/any/repo/path");
7583        assert_eq!(
7584            disk_gate_with(repo, &cfg, |_| Ok(0)),
7585            None,
7586            "a zero floor never measures at all"
7587        );
7588    }
7589
7590    #[test]
7591    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7592        let cfg = Config::default();
7593        let repo = Path::new("/any/repo/path");
7594        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7595            .expect("a measurement failure must close the gate, not open it");
7596        assert!(reason.contains("could not measure"), "{reason}");
7597    }
7598
7599    #[test]
7600    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7601        let ordinary = task();
7602        let next = advance_interrupt(
7603            Interrupt::Idle,
7604            std::slice::from_ref(&ordinary.id),
7605            std::slice::from_ref(&ordinary),
7606        );
7607        assert_eq!(next, Interrupt::Idle);
7608    }
7609
7610    #[test]
7611    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7612        // Nothing to interrupt - this is just an ordinary candidate, and the
7613        // loop's normal dispatch will pick it up like any other.
7614        let marked = interrupt_task("marked");
7615        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7616        assert_eq!(next, Interrupt::Idle);
7617    }
7618
7619    #[test]
7620    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7621        let marked = interrupt_task("marked");
7622        let next = advance_interrupt(
7623            Interrupt::Idle,
7624            &["running".to_owned()],
7625            std::slice::from_ref(&marked),
7626        );
7627        assert_eq!(
7628            next,
7629            Interrupt::Parking {
7630                parked: vec!["running".to_owned()],
7631                interrupt_task: "marked".to_owned(),
7632            }
7633        );
7634    }
7635
7636    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
7637    /// one run can be in flight when a task becomes runnable and marked.
7638    /// Parking all of them would mean `Resuming` later has more than one id
7639    /// to release back to ordinary dispatch, which cannot be made safe
7640    /// against that same setting's own extra concurrency slots letting two
7641    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
7642    /// The simplification the task's own constraints ask for: do not begin
7643    /// a sequence at all until the herd settles back to exactly one.
7644    #[test]
7645    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7646        let marked = interrupt_task("marked");
7647
7648        let two = advance_interrupt(
7649            Interrupt::Idle,
7650            &["a".to_owned(), "b".to_owned()],
7651            std::slice::from_ref(&marked),
7652        );
7653        assert_eq!(two, Interrupt::Idle);
7654
7655        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7656        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7657    }
7658
7659    #[test]
7660    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7661        let state = Interrupt::Parking {
7662            parked: vec!["running".to_owned()],
7663            interrupt_task: "marked".to_owned(),
7664        };
7665        // Still in flight: no change.
7666        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7667        assert_eq!(still_going, state);
7668
7669        // Left flight, but the interrupt task has not been dispatched yet on
7670        // this tick - stays `Parking` so `interrupt_gate` can let it through,
7671        // as long as it is still runnable.
7672        let stopped_but_not_yet_dispatched =
7673            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7674        assert_eq!(stopped_but_not_yet_dispatched, state);
7675
7676        // Left flight, and the interrupt task is now in flight itself.
7677        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7678        assert_eq!(
7679            dispatched,
7680            Interrupt::Running {
7681                parked: vec!["running".to_owned()],
7682                interrupt_task: "marked".to_owned(),
7683            }
7684        );
7685    }
7686
7687    #[test]
7688    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7689        let state = Interrupt::Running {
7690            parked: vec!["running".to_owned()],
7691            interrupt_task: "marked".to_owned(),
7692        };
7693        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7694        assert_eq!(still_running, state);
7695
7696        // Whatever it ended as - merged, failed, held - is not this
7697        // function's concern: leaving flight is the only trigger, driven
7698        // straight off the same in-flight list `poll` already reaps. It does
7699        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
7700        // why that would let an unrelated task start ahead of, or alongside,
7701        // the guaranteed resume.
7702        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7703        assert_eq!(
7704            ended,
7705            Interrupt::Resuming {
7706                parked: vec!["running".to_owned()]
7707            }
7708        );
7709    }
7710
7711    #[test]
7712    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7713        let state = Interrupt::Resuming {
7714            parked: vec!["running".to_owned()],
7715        };
7716        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7717        assert_eq!(still_waiting, state);
7718
7719        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7720        assert_eq!(dispatched, Interrupt::Idle);
7721    }
7722
7723    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
7724    /// or otherwise moved on by an operator with no claim standing in the
7725    /// way - must not wedge the sequence (and so the whole loop's dispatch,
7726    /// via `interrupt_gate`) waiting forever for a dispatch that can never
7727    /// come. The parked run still gets its resume.
7728    #[test]
7729    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7730    {
7731        let state = Interrupt::Parking {
7732            parked: vec!["running".to_owned()],
7733            interrupt_task: "marked".to_owned(),
7734        };
7735        // `marked` has been held/blocked/deleted since the sequence began:
7736        // it no longer appears in `runnable` at all.
7737        let next = advance_interrupt(state, &[], &[]);
7738        assert_eq!(
7739            next,
7740            Interrupt::Resuming {
7741                parked: vec!["running".to_owned()]
7742            },
7743            "abandoning the interrupt must not abandon the resume it owes"
7744        );
7745    }
7746
7747    /// The same abandonment, one step later: `Resuming` itself must not wait
7748    /// forever for a parked task that has since become unrunnable.
7749    #[test]
7750    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7751        let state = Interrupt::Resuming {
7752            parked: vec!["running".to_owned()],
7753        };
7754        let next = advance_interrupt(state, &[], &[]);
7755        assert_eq!(
7756            next,
7757            Interrupt::Idle,
7758            "nothing is left to wait for; the loop must not stay wedged"
7759        );
7760    }
7761
7762    #[test]
7763    fn disabled_by_config_the_sequence_can_never_leave_idle() {
7764        let marked = interrupt_task("marked");
7765        let next = advance_interrupt_tick(
7766            false,
7767            Interrupt::Idle,
7768            &["running".to_owned()],
7769            std::slice::from_ref(&marked),
7770        );
7771        assert_eq!(
7772            next,
7773            Interrupt::Idle,
7774            "an unmarked, unconfigured daemon must behave exactly as before"
7775        );
7776    }
7777
7778    #[test]
7779    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7780        let state = Interrupt::Parking {
7781            parked: vec!["running".to_owned()],
7782            interrupt_task: "marked".to_owned(),
7783        };
7784        let candidates = vec![interrupt_task("marked"), task()];
7785        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7786        assert!(
7787            allowed.is_empty(),
7788            "nothing may dispatch - not even the interrupt task itself - \
7789             until the parked run has actually stopped"
7790        );
7791    }
7792
7793    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
7794    /// grow a special case for it: an urgent candidate that is not the
7795    /// interrupt task withholds exactly like an ordinary one for as long as
7796    /// the parked run it is racing has not actually left flight. A version
7797    /// of this feature once bypassed the gate for urgent candidates, on the
7798    /// theory that a genuinely separate concurrency lane could not collide
7799    /// with 75dd's own; it could, and did - the bypassed task dispatched
7800    /// alongside a run 75dd's own state machine had only *asked* to park,
7801    /// not yet confirmed gone, which is exactly the second run
7802    /// `Interrupt::Parking`'s own doc says must never happen. There is no
7803    /// tick during Parking/Running/Resuming where letting an extra
7804    /// candidate through is safe, urgent or not - the parked run may still
7805    /// be genuinely mid-call.
7806    #[test]
7807    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7808        for state in [
7809            Interrupt::Parking {
7810                parked: vec!["running".to_owned()],
7811                interrupt_task: "marked".to_owned(),
7812            },
7813            Interrupt::Running {
7814                parked: vec!["running".to_owned()],
7815                interrupt_task: "marked".to_owned(),
7816            },
7817            Interrupt::Resuming {
7818                parked: vec!["running".to_owned()],
7819            },
7820        ] {
7821            let candidates = vec![
7822                interrupt_task("marked"),
7823                urgent_task("hot"),
7824                task_with_id("ordinary"),
7825            ];
7826            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7827            assert!(
7828                !allowed.iter().any(|t| t.id == "hot"),
7829                "an urgent candidate must wait out the same gate as anything \
7830                 else while the run it would run alongside has not actually \
7831                 left flight, for state {state:?}: {allowed:?}"
7832            );
7833        }
7834    }
7835
7836    /// The one case where marking a task `--urgent` and `interrupt` at once
7837    /// is not redundant: once the interrupt sequence's own guaranteed
7838    /// resume/dispatch actually admits the task, it is unaffected by also
7839    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
7840    /// never on the urgent flag.
7841    #[test]
7842    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7843        let state = Interrupt::Resuming {
7844            parked: vec!["hot".to_owned()],
7845        };
7846        let candidates = vec![urgent_task("hot"), task()];
7847        let allowed = interrupt_gate(&state, &[], candidates);
7848        assert_eq!(
7849            allowed.iter().filter(|t| t.id == "hot").count(),
7850            1,
7851            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7852        );
7853    }
7854
7855    #[test]
7856    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7857        let state = Interrupt::Parking {
7858            parked: vec!["running".to_owned()],
7859            interrupt_task: "marked".to_owned(),
7860        };
7861        let other = task();
7862        let candidates = vec![interrupt_task("marked"), other.clone()];
7863        let allowed = interrupt_gate(&state, &[], candidates);
7864        assert_eq!(allowed.len(), 1);
7865        assert_eq!(allowed[0].id, "marked");
7866    }
7867
7868    #[test]
7869    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7870        let state = Interrupt::Running {
7871            parked: vec!["running".to_owned()],
7872            interrupt_task: "marked".to_owned(),
7873        };
7874        let candidates = vec![task(), task()];
7875        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7876        assert!(allowed.is_empty());
7877    }
7878
7879    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
7880    /// sequence began (only reachable above the default
7881    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
7882    /// never both in the same tick, which is what "exactly one resume, no
7883    /// simultaneous run" actually requires structurally rather than by
7884    /// coincidence of how many ordinary slots happen to be free.
7885    #[test]
7886    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7887        let state = Interrupt::Resuming {
7888            parked: vec!["a".to_owned(), "c".to_owned()],
7889        };
7890        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7891        let allowed = interrupt_gate(&state, &[], candidates);
7892        assert_eq!(
7893            allowed.len(),
7894            1,
7895            "at most one candidate may be offered while resuming: {allowed:?}"
7896        );
7897        assert_eq!(allowed[0].id, "a");
7898    }
7899
7900    #[test]
7901    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7902        let state = Interrupt::Resuming {
7903            parked: vec!["a".to_owned()],
7904        };
7905        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7906        assert!(allowed.is_empty());
7907    }
7908
7909    /// The invariant the completion criteria ask for by name: across a whole
7910    /// simulated sequence, there is never a tick where the gate would let
7911    /// through both the parked run's resume and the interrupt task, and
7912    /// exactly one candidate resumes the instant the interrupt task's run
7913    /// ends - never zero, never more than one.
7914    #[test]
7915    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7916        let running = task(); // id: whatever `Task::new` minted
7917        let marked = interrupt_task("marked");
7918
7919        let mut state = Interrupt::Idle;
7920        // Tick 1: `running` is in flight, `marked` becomes runnable.
7921        let in_flight = vec![running.id.clone()];
7922        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7923        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7924        assert!(gated.is_empty(), "still waiting on `running` to park");
7925
7926        // Tick 2: `running` parked and left flight; nothing dispatched yet.
7927        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7928        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7929        assert_eq!(
7930            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7931            vec!["marked"],
7932            "only the interrupt task may be offered to the dispatcher now"
7933        );
7934
7935        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
7936        state = advance_interrupt_tick(
7937            true,
7938            state,
7939            &["marked".to_owned()],
7940            std::slice::from_ref(&running),
7941        );
7942        let gated = interrupt_gate(
7943            &state,
7944            &["marked".to_owned()],
7945            vec![marked.clone(), running.clone()],
7946        );
7947        assert!(
7948            gated.is_empty(),
7949            "the parked run must not be offered back while the interrupt \
7950             task is still running"
7951        );
7952
7953        // Tick 4: `marked`'s run reached a terminal status and left flight.
7954        // A higher-priority ordinary task `other` is also runnable now - it
7955        // must not be let through instead of, or alongside, `running`.
7956        let other = task_with_id("other");
7957        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7958        assert_eq!(
7959            state,
7960            Interrupt::Resuming {
7961                parked: vec![running.id.clone()]
7962            }
7963        );
7964        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7965        assert_eq!(
7966            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7967            vec![running.id.as_str()],
7968            "exactly the parked run resumes - not the unrelated task, even \
7969             though it was offered first"
7970        );
7971
7972        // Tick 5: `running` is now in flight (dispatched from tick 4's
7973        // gate). Only now does the sequence end and ordinary dispatch fully
7974        // resume.
7975        state = advance_interrupt_tick(
7976            true,
7977            state,
7978            std::slice::from_ref(&running.id),
7979            std::slice::from_ref(&other),
7980        );
7981        assert_eq!(state, Interrupt::Idle);
7982        let gated = interrupt_gate(
7983            &state,
7984            std::slice::from_ref(&running.id),
7985            vec![other.clone()],
7986        );
7987        assert_eq!(
7988            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7989            vec![other.id.as_str()],
7990            "ordinary dispatch is unrestricted again"
7991        );
7992    }
7993
7994    #[test]
7995    fn every_run_status_settles_the_task_it_came_from() {
7996        // run status, resulting task status, attempts still standing after one
7997        let table = [
7998            (RunStatus::Merged, TaskStatus::Done, 1),
7999            (RunStatus::Ready, TaskStatus::Done, 1),
8000            (RunStatus::Stalled, TaskStatus::Failed, 0),
8001            (RunStatus::Blocked, TaskStatus::Failed, 1),
8002            (RunStatus::Failed, TaskStatus::Failed, 1),
8003            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8004            (RunStatus::Prep, TaskStatus::Failed, 1),
8005            (RunStatus::Implementing, TaskStatus::Failed, 1),
8006            (RunStatus::Judging, TaskStatus::Failed, 1),
8007            (RunStatus::Deliberating, TaskStatus::Failed, 1),
8008            (RunStatus::Voting, TaskStatus::Failed, 1),
8009            (RunStatus::Reviewing, TaskStatus::Failed, 1),
8010            (RunStatus::Gating, TaskStatus::Failed, 1),
8011        ];
8012        for (run, want, attempts) in table {
8013            let mut t = task();
8014            t.start("20260902-000000-aaaa".to_owned());
8015            settle(
8016                &mut t,
8017                Verdict {
8018                    status: run,
8019                    left_pr: false,
8020                    parked: false,
8021                    quota_hit: matches!(run, RunStatus::Stalled),
8022                    no_viable_candidates: false,
8023                },
8024                "why",
8025                2,
8026            );
8027            assert_eq!(t.status, want, "task status after {}", label(run));
8028            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8029        }
8030    }
8031
8032    #[test]
8033    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8034        let mut stalled = task();
8035        stalled.start("20260902-000000-aaaa".to_owned());
8036        settle(
8037            &mut stalled,
8038            Verdict {
8039                status: RunStatus::Stalled,
8040                left_pr: false,
8041                parked: false,
8042                quota_hit: true,
8043                no_viable_candidates: false,
8044            },
8045            "quota",
8046            1,
8047        );
8048        assert_eq!(stalled.attempts, 0);
8049        assert!(
8050            stalled.status.runnable(),
8051            "a machine problem must leave the task in line"
8052        );
8053
8054        let mut blocked = task();
8055        blocked.start("20260902-000000-aaaa".to_owned());
8056        settle(
8057            &mut blocked,
8058            Verdict {
8059                status: RunStatus::Blocked,
8060                left_pr: false,
8061                parked: false,
8062                quota_hit: false,
8063                no_viable_candidates: false,
8064            },
8065            "findings open",
8066            1,
8067        );
8068        assert_eq!(blocked.attempts, 1);
8069        assert_eq!(
8070            blocked.status,
8071            TaskStatus::Held,
8072            "the last attempt hands the task to a human"
8073        );
8074    }
8075
8076    #[test]
8077    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8078        // Attempts to spare: without the pull request this task would go
8079        // straight back in line and run the whole competition again.
8080        let mut delivered = task();
8081        delivered.start("20260903-080619-01c2".to_owned());
8082        settle(
8083            &mut delivered,
8084            Verdict {
8085                status: RunStatus::Blocked,
8086                left_pr: true,
8087                parked: false,
8088                quota_hit: false,
8089                no_viable_candidates: false,
8090            },
8091            "no check status",
8092            4,
8093        );
8094        assert_eq!(
8095            delivered.status,
8096            TaskStatus::Held,
8097            "a pull request waiting on CI or a person is not a retryable failure"
8098        );
8099        assert!(
8100            !delivered.status.runnable(),
8101            "the loop must not pick this task up again"
8102        );
8103        assert_eq!(
8104            delivered.last_error.as_deref(),
8105            Some("no check status"),
8106            "the operator needs to be told what the gate was waiting for"
8107        );
8108
8109        // The same status without a pull request is a plain failure, and with
8110        // attempts left it is retried.
8111        let mut empty_handed = task();
8112        empty_handed.start("20260903-080619-01c2".to_owned());
8113        settle(
8114            &mut empty_handed,
8115            Verdict {
8116                status: RunStatus::Blocked,
8117                left_pr: false,
8118                parked: false,
8119                quota_hit: false,
8120                no_viable_candidates: false,
8121            },
8122            "findings open",
8123            4,
8124        );
8125        assert_eq!(empty_handed.status, TaskStatus::Failed);
8126        assert!(empty_handed.status.runnable());
8127    }
8128
8129    #[test]
8130    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8131        // Every candidate agreed, with evidence, that nothing belonged in the
8132        // worktree. That is not a confirmed success to close automatically -
8133        // a human still has to check the claim - and it is not an ordinary
8134        // failure either, so this settles exactly like a pull request nobody
8135        // merged yet: `Held`, same as `Blocked` with a PR.
8136        let mut noop = task();
8137        noop.start("20260912-131304-391f".to_owned());
8138        settle(
8139            &mut noop,
8140            Verdict {
8141                status: RunStatus::VerifiedNoop,
8142                left_pr: false,
8143                parked: false,
8144                quota_hit: false,
8145                no_viable_candidates: true,
8146            },
8147            "candidate A: already fixed by b32cfc4, on main",
8148            4,
8149        );
8150        assert_eq!(
8151            noop.status,
8152            TaskStatus::Held,
8153            "an unverified claim is a request for a human, not a failure"
8154        );
8155        assert!(
8156            !noop.status.runnable(),
8157            "the loop must not requeue this on the same unverified claim"
8158        );
8159        // `Task::release` resets attempts to zero the moment a human looks at
8160        // the evidence and lets it run again, so it does not matter here
8161        // whether the one attempt already spent stays spent - what matters is
8162        // that nothing retries this task unattended in the meantime.
8163        assert_eq!(noop.attempts, 1);
8164    }
8165
8166    #[test]
8167    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8168        // Parking is the operator asking for the process back - to replace the
8169        // binary, most of all. The run's work is intact on disk, so this is
8170        // not a failed attempt, and charging for it would mean a few upgrades
8171        // could exhaust a budget meant for agents that misbehaved.
8172        let mut parked = task();
8173        parked.start("20260903-183634-2d98".to_owned());
8174        settle(
8175            &mut parked,
8176            Verdict {
8177                status: RunStatus::Implementing,
8178                left_pr: false,
8179                quota_hit: false,
8180                parked: true,
8181                no_viable_candidates: false,
8182            },
8183            "parked after `implementing`",
8184            2,
8185        );
8186        assert_eq!(parked.attempts, 0, "a park is refunded");
8187        assert!(
8188            parked.status.runnable(),
8189            "and the task stays in line so the next loop resumes its run"
8190        );
8191        assert_eq!(parked.status, TaskStatus::Parked);
8192        assert_eq!(
8193            parked.park_reason.as_deref(),
8194            Some("parked after `implementing`"),
8195            "the card says where it stopped"
8196        );
8197        assert_eq!(parked.last_error, None, "nothing failed");
8198
8199        // Without the park flag the same non-terminal status is what it always
8200        // was: `execute` returning mid-flight, which is a bug and spends an
8201        // attempt so a task cannot loop on it forever.
8202        let mut broken = task();
8203        broken.start("20260903-183634-2d98".to_owned());
8204        settle(
8205            &mut broken,
8206            Verdict {
8207                status: RunStatus::Implementing,
8208                left_pr: false,
8209                quota_hit: false,
8210                parked: false,
8211                no_viable_candidates: false,
8212            },
8213            "returned mid-flight",
8214            2,
8215        );
8216        assert_eq!(broken.attempts, 1);
8217    }
8218
8219    #[test]
8220    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
8221        // Run e633: quorum lost because two judges answered with the wrong
8222        // JSON shape, `quota: []`. Refunding that takes the bound off the
8223        // retry loop, and each retry pays for a fresh hour-long implement
8224        // wave before it can fail the same way.
8225        let mut flaky = task();
8226        flaky.start("20260903-123023-e633".to_owned());
8227        settle(
8228            &mut flaky,
8229            Verdict {
8230                status: RunStatus::Stalled,
8231                left_pr: false,
8232                parked: false,
8233                quota_hit: false,
8234                no_viable_candidates: false,
8235            },
8236            "verdict rests on 1 of 3 judges",
8237            2,
8238        );
8239        assert_eq!(
8240            flaky.attempts, 1,
8241            "flakiness spends an attempt, so `max_attempts` still bounds it"
8242        );
8243        assert!(flaky.status.runnable(), "and it is still worth retrying");
8244
8245        // The same status, lost to a rate limit, is the machine's fault.
8246        let mut limited = task();
8247        limited.start("20260903-123023-e633".to_owned());
8248        settle(
8249            &mut limited,
8250            Verdict {
8251                status: RunStatus::Stalled,
8252                left_pr: false,
8253                parked: false,
8254                quota_hit: true,
8255                no_viable_candidates: false,
8256            },
8257            "judge-2, judge-3 out of quota",
8258            2,
8259        );
8260        assert_eq!(limited.attempts, 0, "a quota window is refunded");
8261        assert!(limited.status.runnable());
8262
8263        // And the bound really binds: a task that keeps stalling on flakiness
8264        // reaches a human instead of running the roster forever.
8265        let mut worn = task();
8266        for _ in 0..2 {
8267            worn.release();
8268        }
8269        worn.start("20260903-123023-e633".to_owned());
8270        worn.attempts = 2;
8271        settle(
8272            &mut worn,
8273            Verdict {
8274                status: RunStatus::Stalled,
8275                left_pr: false,
8276                parked: false,
8277                quota_hit: false,
8278                no_viable_candidates: false,
8279            },
8280            "no quorum again",
8281            2,
8282        );
8283        assert_eq!(worn.status, TaskStatus::Held);
8284        assert!(!worn.status.runnable());
8285    }
8286
8287    #[test]
8288    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8289        // The implement wave loses every seat to the same rate limit and
8290        // `after_implement` bails with nothing viable, which surfaces as
8291        // `Failed` rather than `Stalled`. That is the same machine fact the
8292        // `Stalled`-quota row already refunds, and must be refunded the same
8293        // way, or a quota outage quietly holds every task it touches instead
8294        // of leaving them in line for the reset.
8295        let mut wiped_out = task();
8296        wiped_out.start("20260907-025000-a1b2".to_owned());
8297        settle(
8298            &mut wiped_out,
8299            Verdict {
8300                status: RunStatus::Failed,
8301                left_pr: false,
8302                parked: false,
8303                quota_hit: true,
8304                no_viable_candidates: true,
8305            },
8306            "no candidate produced a change; nothing to judge",
8307            2,
8308        );
8309        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8310        assert!(
8311            wiped_out.status.runnable(),
8312            "a machine problem must leave the task in line"
8313        );
8314
8315        // This is the exemption that must stay narrow: a candidate that did
8316        // produce a change, and then failed for some other reason, still
8317        // spends the attempt even though a seat elsewhere hit its quota.
8318        // Otherwise every ordinary failure that happens to share a run with
8319        // an unrelated rate limit would be refunded for free.
8320        let mut partial_progress = task();
8321        partial_progress.start("20260907-025500-c3d4".to_owned());
8322        settle(
8323            &mut partial_progress,
8324            Verdict {
8325                status: RunStatus::Failed,
8326                left_pr: false,
8327                parked: false,
8328                quota_hit: true,
8329                no_viable_candidates: false,
8330            },
8331            "gate failed on the winning candidate",
8332            2,
8333        );
8334        assert_eq!(
8335            partial_progress.attempts, 1,
8336            "a candidate that actually produced a change spends the attempt \
8337             even though some other seat hit its quota"
8338        );
8339        assert!(partial_progress.status.runnable());
8340    }
8341
8342    #[test]
8343    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8344        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
8345        // disk, and that construction must reach the same conclusion as the
8346        // one `attempt` builds from a live run, or a crash at exactly the
8347        // wrong moment gives a recovered task a different policy than one a
8348        // daemon finished settling itself.
8349        let mut t = task();
8350        t.start("20260907-025000-a1b2".to_owned());
8351        let mut state = run_state(RunStatus::Failed);
8352        state.quota.push(QuotaLoss {
8353            cause: crate::agent::QuotaCause::UsageLimit,
8354            agent: String::new(),
8355            seat: "cand-a".to_owned(),
8356            node: "implement".to_owned(),
8357            at: Timestamp::now(),
8358            reset: None,
8359        });
8360        assert!(
8361            state.viable().is_empty(),
8362            "no candidate was added, so nothing is viable"
8363        );
8364        reclaim(&mut t, Some(state), 2, "en");
8365        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8366        assert!(t.status.runnable());
8367    }
8368
8369    #[test]
8370    fn a_held_task_is_never_offered_to_the_loop() {
8371        let dir = tempfile::tempdir().unwrap();
8372        let queue = Queue::at(dir.path().to_path_buf());
8373        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8374            let mut t = task();
8375            t.id = format!("2026090{n}-000000-000{n}");
8376            t.priority = priority;
8377            queue.put(&mut t).unwrap();
8378        }
8379        let mut held = task();
8380        held.id = "20260909-000000-9999".to_owned();
8381        held.priority = 99;
8382        held.hold_machine(None);
8383        queue.put(&mut held).unwrap();
8384
8385        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8386        assert_eq!(order.len(), 3);
8387        assert!(!order.contains(&held.id));
8388        assert_eq!(
8389            order.first().cloned(),
8390            queue.next_runnable().map(|t| t.id),
8391            "the loop's first candidate is exactly what the queue offers"
8392        );
8393        assert_eq!(
8394            order,
8395            vec![
8396                "20260902-000000-0002".to_owned(),
8397                "20260903-000000-0003".to_owned(),
8398                "20260901-000000-0001".to_owned(),
8399            ],
8400            "priority first, then oldest, so nothing starves"
8401        );
8402    }
8403
8404    #[test]
8405    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8406        let dir = tempfile::tempdir().unwrap();
8407        let queue = Queue::at(dir.path().to_path_buf());
8408        let mut old = task();
8409        old.id = "20260101-000000-old0".to_owned();
8410        queue.put(&mut old).unwrap();
8411        let mut fresh = task();
8412        fresh.id = "20260101-000000-new0".to_owned();
8413        queue.put(&mut fresh).unwrap();
8414
8415        // No parseable pid at all, so age is the only signal there is to
8416        // check - unlike a real `Queue::claim`, which always names a real,
8417        // and therefore alive, pid this test cannot fake as dead.
8418        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8419        std::thread::sleep(Duration::from_millis(60));
8420        let live = queue.claim(&fresh.id).unwrap();
8421
8422        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8423        assert_eq!(swept, vec![old.id.clone()]);
8424        assert!(
8425            queue.claim(&old.id).is_ok(),
8426            "an unparseable lock older than the threshold is swept"
8427        );
8428        assert!(
8429            queue.claim(&fresh.id).is_err(),
8430            "a live pid protects its lock regardless of age"
8431        );
8432        drop(live);
8433    }
8434
8435    #[test]
8436    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8437        // A live worker's claim remains authoritative even beyond the sweep's
8438        // age limit. Sweeping it would permit a second competing attempt.
8439        let dir = tempfile::tempdir().unwrap();
8440        let queue = Queue::at(dir.path().to_path_buf());
8441        let mut t = task();
8442        t.id = "20260101-000000-live".to_owned();
8443        queue.put(&mut t).unwrap();
8444
8445        let claim = queue.claim(&t.id).unwrap();
8446        std::thread::sleep(Duration::from_millis(60));
8447
8448        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8449        assert!(
8450            swept.is_empty(),
8451            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8452        );
8453        assert!(
8454            queue.claim(&t.id).is_err(),
8455            "the lock still protects its task"
8456        );
8457        drop(claim);
8458    }
8459
8460    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8461    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8462    fn injected_dead_pid() -> u32 {
8463        std::process::id().checked_add(1).unwrap_or(1)
8464    }
8465
8466    #[test]
8467    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8468        let dir = tempfile::tempdir().unwrap();
8469        let queue = Queue::at(dir.path().to_path_buf());
8470        let mut t = task();
8471        t.id = "20260101-000000-dead".to_owned();
8472        queue.put(&mut t).unwrap();
8473        let dead_pid = injected_dead_pid();
8474
8475        // Written directly rather than through `Queue::claim`, which would
8476        // stamp this test process's own very much alive pid and defeat the
8477        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8478        // like moments after it died, not six hours later.
8479        std::fs::write(
8480            dir.path().join(format!("{}.lock", t.id)),
8481            dead_pid.to_string(),
8482        )
8483        .unwrap();
8484
8485        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8486            pid != dead_pid
8487        });
8488        assert_eq!(
8489            swept,
8490            vec![t.id.clone()],
8491            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8492        );
8493        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8494    }
8495
8496    #[test]
8497    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8498        let dir = tempfile::tempdir().unwrap();
8499        let queue = Queue::at(dir.path().to_path_buf());
8500        let mut t = task();
8501        t.id = "20260101-000000-late".to_owned();
8502        queue.put(&mut t).unwrap();
8503        let dead_pid = injected_dead_pid();
8504
8505        // Tick one, standing in for the sweep `poll` already runs at
8506        // startup: nothing to find yet.
8507        assert!(
8508            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8509            "nothing has claimed the task yet"
8510        );
8511
8512        // A second daemon claims the task and dies before it ever writes
8513        // `running`, well after this loop's own startup sweep already ran.
8514        std::fs::write(
8515            dir.path().join(format!("{}.lock", t.id)),
8516            dead_pid.to_string(),
8517        )
8518        .unwrap();
8519
8520        // Tick two, standing in for a poll long into this daemon's uptime:
8521        // the same function, called again, notices what only just appeared -
8522        // proving the sweep is not a one-shot startup check.
8523        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8524            pid != dead_pid
8525        });
8526        assert_eq!(swept, vec![t.id.clone()]);
8527    }
8528
8529    #[test]
8530    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8531        // `reclaim_orphaned_running` looks up the task's last run, which
8532        // touches `run::home()`; the first call anywhere in this binary wins,
8533        // so this is a no-op if another test already pinned one, and either
8534        // way the run id below is never written under it.
8535        crate::run::pin_test_home();
8536        let dir = tempfile::tempdir().unwrap();
8537        let queue = Queue::at(dir.path().to_path_buf());
8538        let mut t = task();
8539        t.id = "20260101-000000-crsh".to_owned();
8540        t.status = TaskStatus::Running;
8541        t.attempts = 1;
8542        // No `run.json` behind this id: standing in for a run this test does
8543        // not need to make readable, since the point is the lock, not the
8544        // recovery table `reclaim` already has its own tests for.
8545        t.runs.push("20260904-000000-4043".to_owned());
8546        queue.put(&mut t).unwrap();
8547        let dead_pid = injected_dead_pid();
8548
8549        // The crashed daemon's own claim, naming a pid nothing on the
8550        // machine holds anymore.
8551        std::fs::write(
8552            dir.path().join(format!("{}.lock", t.id)),
8553            dead_pid.to_string(),
8554        )
8555        .unwrap();
8556
8557        // Before the lock is swept the task looks claimed, and
8558        // `reclaim_orphaned_running` must leave it alone - this is exactly
8559        // the bug: a `running` task stranded behind a dead daemon's lock,
8560        // invisible to the claim-as-proof check because the lock outlived
8561        // the process that wrote it.
8562        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8563        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8564
8565        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8566            pid != dead_pid
8567        });
8568        assert_eq!(swept, vec![t.id.clone()]);
8569
8570        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8571        assert_eq!(reclaimed, vec![t.id.clone()]);
8572        let after = queue.get(&t.id).unwrap();
8573        assert_eq!(
8574            after.status,
8575            TaskStatus::Held,
8576            "no run.json to recover from, so a human is asked"
8577        );
8578        assert_eq!(
8579            after.runs,
8580            vec!["20260904-000000-4043".to_owned()],
8581            "the crashed run's id is kept as evidence, not discarded"
8582        );
8583    }
8584
8585    #[test]
8586    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8587        let dir = tempfile::tempdir().unwrap();
8588        let queue = Queue::at(dir.path().to_path_buf());
8589        let mut t = task();
8590        t.id = "20260101-000000-unknown".to_owned();
8591        queue.put(&mut t).unwrap();
8592        let dead_pid = injected_dead_pid();
8593        std::fs::write(
8594            dir.path().join(format!("{}.lock", t.id)),
8595            dead_pid.to_string(),
8596        )
8597        .unwrap();
8598
8599        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8600        assert!(swept.is_empty(), "an unknown pid must keep its lock");
8601        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8602    }
8603
8604    fn run_state_in(status: RunStatus, language: &str) -> RunState {
8605        let mut s = run_state(status);
8606        s.config.graph.language = language.to_owned();
8607        s
8608    }
8609
8610    fn unstarted_verdict(status: RunStatus) -> Verdict {
8611        Verdict {
8612            status,
8613            left_pr: false,
8614            quota_hit: false,
8615            parked: false,
8616            no_viable_candidates: false,
8617        }
8618    }
8619
8620    #[test]
8621    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8622        let mut t = task();
8623        t.attempts = 1;
8624        settle_in(
8625            &mut t,
8626            unstarted_verdict(RunStatus::AlreadyInBase),
8627            "already in main",
8628            1,
8629            phrases("en"),
8630        );
8631        assert_eq!(t.status, TaskStatus::Done);
8632        assert_eq!(t.attempts, 0);
8633    }
8634
8635    #[test]
8636    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8637        let reason = |language: &str| {
8638            let mut t = task();
8639            settle_in(
8640                &mut t,
8641                unstarted_verdict(RunStatus::Judging),
8642                "boom",
8643                1,
8644                phrases(language),
8645            );
8646            t.last_error.or(t.hold_reason).unwrap_or_default()
8647        };
8648        assert!(
8649            reason("en").starts_with("the graph stopped at `"),
8650            "{}",
8651            reason("en")
8652        );
8653        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8654        assert!(reason("日本語").contains("boom"));
8655        assert_eq!(reason("fr"), reason("en"));
8656    }
8657
8658    #[test]
8659    fn describe_follows_the_run_language_and_keeps_the_run_id() {
8660        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8661        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8662        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8663        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8664        assert!(ja.contains("[run "), "{ja}");
8665        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8666        assert!(ended.starts_with("run 終了: "), "{ended}");
8667        let mut de = run_state_in(RunStatus::Failed, "de");
8668        let mut en = run_state_in(RunStatus::Failed, "en");
8669        de.id = "same".to_owned();
8670        en.id = "same".to_owned();
8671        assert_eq!(describe(&de), describe(&en));
8672    }
8673
8674    #[test]
8675    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8676        use crate::handover::Refused;
8677        let cases = [
8678            Refused::Foreign {
8679                branch: "b".into(),
8680                path: "/w/x".into(),
8681                why: "made by hand".into(),
8682            },
8683            Refused::Unsafe {
8684                branch: "b".into(),
8685                path: "/w/x".into(),
8686                why: "its worktree has uncommitted changes (a.rs)".into(),
8687            },
8688            Refused::ReleaseFailed {
8689                branch: "b".into(),
8690                path: "/w/x".into(),
8691                run: "ab12".into(),
8692            },
8693        ];
8694        for r in &cases {
8695            let en = (phrases("en").handover_refused)(r);
8696            assert_eq!(en, r.to_string());
8697            let ja = (phrases("ja").handover_refused)(r);
8698            assert!(
8699                !ja.contains("is checked out") && !ja.contains("try again"),
8700                "{ja}"
8701            );
8702            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8703            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8704                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8705            }
8706        }
8707        assert!(phrases("en").handover_hint.contains("release the task"));
8708        assert!(phrases("ja").handover_hint.contains("解放"));
8709    }
8710
8711    #[test]
8712    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8713        let build = |lang: &str| {
8714            let mut s = run_state_in(RunStatus::Blocked, lang);
8715            s.id = "same".to_owned();
8716            s.config.graph.review_rounds = 3;
8717            let mut r = review_round(3);
8718            r.expected = 3;
8719            r.answered = 1;
8720            s.reviews.push(r);
8721            s.event(
8722                "review",
8723                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8724            );
8725            s
8726        };
8727        let en = describe(&build("en"));
8728        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8729        let ja = describe(&build("ja"));
8730        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8731        assert!(!ja.contains("never answered"), "{ja}");
8732        assert!(ja.contains("[run "), "{ja}");
8733
8734        // An incomplete panel whose verification failed is a different stop:
8735        // the real event must survive in ja too.
8736        let mut failed = build("ja");
8737        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8738            command: "cargo test".to_owned(),
8739            code: Some(1),
8740            output_tail: String::new(),
8741            duration_ms: 0,
8742            resource_blocked: false,
8743        });
8744        failed.event("review", "stopped; e2e failed: cargo test");
8745        let ja = describe(&failed);
8746        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8747        assert!(!ja.contains("席のレビュアー"), "{ja}");
8748    }
8749
8750    #[test]
8751    fn refusals_and_recovery_prose_follow_the_language() {
8752        let home = crate::run::test_home();
8753        let t = held_task_with("r1");
8754        let q = action_question(
8755            "r1",
8756            ask::ChoiceAction::Resume {
8757                run: "r1".to_owned(),
8758            },
8759        );
8760        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
8761            ActionDecision::Refuse(s) => s,
8762            other => panic!("{other:?}"),
8763        };
8764        assert!(refuse(phrases("en")).contains("could not be read: gone"));
8765        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8766        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8767
8768        let mut held = task();
8769        reclaim(&mut held, None, 2, "ja");
8770        assert!(held.hold_reason.unwrap().contains("保留にしました"));
8771        let mut held = task();
8772        reclaim(&mut held, None, 2, "xx");
8773        assert!(held.hold_reason.unwrap().contains("held for a human"));
8774    }
8775
8776    fn run_state(status: RunStatus) -> RunState {
8777        let mut state = RunState::new(
8778            PathBuf::from("/repo"),
8779            "main".to_owned(),
8780            "abc1234def".to_owned(),
8781            "add retries".to_owned(),
8782            Config::default(),
8783        );
8784        state.status = status;
8785        state
8786    }
8787
8788    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8789        Candidate {
8790            index: 0,
8791            label,
8792            agent: "claude".to_owned(),
8793            branch: format!("magi/x/{label}"),
8794            worktree: PathBuf::from("/repo"),
8795            summary: summary.to_owned(),
8796            stat: String::new(),
8797            files: 0,
8798            commits: usize::from(!empty),
8799            empty,
8800            failed: failed.map(str::to_owned),
8801            verified_noop: None,
8802            duration_ms: 0,
8803            folded: false,
8804        }
8805    }
8806
8807    #[test]
8808    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8809        let mut state = run_state(RunStatus::Blocked);
8810        state.gate = vec![
8811            CommandOutcome {
8812                command: "cargo make check".to_owned(),
8813                code: Some(0),
8814                output_tail: "ok".to_owned(),
8815                duration_ms: 0,
8816                resource_blocked: false,
8817            },
8818            CommandOutcome {
8819                command: "cargo test".to_owned(),
8820                code: Some(101),
8821                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8822                duration_ms: 0,
8823                resource_blocked: false,
8824            },
8825        ];
8826        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8827        assert!(d.contains("cargo test"), "{d}");
8828        assert!(
8829            !d.contains("cargo make check"),
8830            "a passing check is not a diagnostic: {d}"
8831        );
8832        assert!(d.contains("assertion failed"), "{d}");
8833    }
8834
8835    #[test]
8836    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8837        let mut state = run_state(RunStatus::Blocked);
8838        state.event(
8839            "land",
8840            "stopped: the fixer produced no commit while 2 check(s) were failing \
8841             (build, lint); stopping instead of looping on an unchanged tree",
8842        );
8843        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8844        assert!(d.contains("build"), "{d}");
8845        assert!(d.contains("lint"), "{d}");
8846        assert!(d.contains("fixer produced no commit"), "{d}");
8847    }
8848
8849    #[test]
8850    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8851        // `describe`'s output becomes `Task::last_error` verbatim, and the
8852        // phone renders that in the same alarm-styled box an ordinary
8853        // failure gets. A bare `verified_noop` there would read exactly like
8854        // the failure this status exists to be told apart from.
8855        let state = run_state(RunStatus::VerifiedNoop);
8856        let d = describe(&state);
8857        assert!(
8858            d.contains("agent-verified no-op"),
8859            "expected the display label, not the wire spelling: {d}"
8860        );
8861        assert!(!d.contains("verified_noop"), "{d}");
8862    }
8863
8864    #[test]
8865    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
8866        let mut state = run_state(RunStatus::Failed);
8867        state.gate.push(crate::run::CommandOutcome {
8868            command: "cargo test".into(),
8869            code: Some(101),
8870            output_tail: format!(
8871                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8872                "  41: 0x1234 - backtrace frame\n".repeat(10000)
8873            ),
8874            duration_ms: 1,
8875            resource_blocked: false,
8876        });
8877        let d = diagnostic(&state).unwrap();
8878        assert!(d.contains("panicked at widget.rs:12"), "{d}");
8879        assert!(d.contains("assertion failed: widget missing"));
8880        assert!(d.contains("widget log"));
8881    }
8882
8883    #[test]
8884    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8885        // The whole point of the feature: a run held as "no candidate produced
8886        // a change" can mean the implementer actually finished the task and
8887        // only left a clean local tree behind - see AGENTS.md on this exact
8888        // failure mode. The diagnostic has to carry what the agent actually
8889        // said, not just the fact that nothing was there to judge.
8890        let mut state = run_state(RunStatus::Failed);
8891        state.candidates = vec![candidate(
8892            'A',
8893            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8894            true,
8895            None,
8896        )];
8897        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8898        assert!(d.contains("candidate A"), "{d}");
8899        assert!(d.contains("tagged v1.2.3"), "{d}");
8900    }
8901
8902    #[test]
8903    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8904        let mut state = run_state(RunStatus::Failed);
8905        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8906        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8907        assert!(d.contains("candidate A"), "{d}");
8908        assert!(d.contains("agent timed out"), "{d}");
8909    }
8910
8911    #[test]
8912    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8913        // A viable candidate existed, the gate never ran, and nothing land
8914        // said matches - `Task::last_error` is left to explain this one alone.
8915        let mut state = run_state(RunStatus::Failed);
8916        state.candidates = vec![candidate('A', "did the work", false, None)];
8917        assert!(diagnostic(&state).is_none());
8918    }
8919
8920    #[test]
8921    fn diagnostic_is_bounded_however_much_a_run_printed() {
8922        let mut state = run_state(RunStatus::Blocked);
8923        state.gate = vec![
8924            CommandOutcome {
8925                command: "cargo test".to_owned(),
8926                code: Some(101),
8927                output_tail: "x".repeat(50_000),
8928                duration_ms: 0,
8929                resource_blocked: false,
8930            },
8931            CommandOutcome {
8932                command: "cargo clippy".to_owned(),
8933                code: Some(1),
8934                output_tail: "y".repeat(50_000),
8935                duration_ms: 0,
8936                resource_blocked: false,
8937            },
8938        ];
8939        state.candidates = vec![
8940            candidate('A', &"z".repeat(50_000), true, None),
8941            candidate('B', &"w".repeat(50_000), true, None),
8942        ];
8943        let d = diagnostic(&state).expect("plenty here to diagnose");
8944        assert!(
8945            d.len() <= DIAGNOSTIC_MAX,
8946            "diagnostic grew to {} bytes, unbounded",
8947            d.len()
8948        );
8949    }
8950
8951    #[test]
8952    fn selected_delivery_guards_survive_recovery_failure_accounting() {
8953        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8954            let mut t = task();
8955            let mut state = run_state(status);
8956            t.pr_recovery = Some(crate::pr_recovery::Selection {
8957                url: "url".into(),
8958                branch: format!("magi/task-{}", t.id),
8959                head: "a".repeat(40),
8960                source_head: None,
8961                source_run: None,
8962                source_proof: None,
8963                disposition: Some(crate::pr_recovery::Disposition::Land),
8964                instruction: t.instruction.clone(),
8965                approved_at: Timestamp::now(),
8966            });
8967            state.pr_recovery = t.pr_recovery.clone();
8968            t.start(state.id.clone());
8969            settle_and_diagnose(
8970                &mut t,
8971                Verdict {
8972                    status,
8973                    left_pr: false,
8974                    quota_hit: false,
8975                    parked: false,
8976                    no_viable_candidates: false,
8977                },
8978                "delivery stopped",
8979                5,
8980                &state,
8981            );
8982            assert_eq!(t.status, TaskStatus::Held);
8983            let reason = t.hold_reason.as_deref().unwrap();
8984            if status == RunStatus::Ready {
8985                assert!(reason.contains("Selected PR delivery is incomplete"));
8986                assert!(t.recovery_budget.is_none());
8987            } else {
8988                assert!(reason.contains("Selected recovery stopped"));
8989                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8990            }
8991            assert!(t.pr_recovery.is_some());
8992        }
8993    }
8994
8995    #[test]
8996    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
8997        let mut state = run_state(RunStatus::Voting);
8998        state.base_sync = Some(crate::run::BaseSync {
8999            tip: "base-tip".into(),
9000            behind: 3,
9001            attempts: 4,
9002            conflict: Some("base stopped".into()),
9003            already_in: None,
9004        });
9005        state.record_base_sync_stop("candidate-head");
9006        let mut t = task();
9007        t.start(state.id.clone());
9008        let verdict = Verdict {
9009            status: RunStatus::Blocked,
9010            left_pr: false,
9011            quota_hit: false,
9012            parked: false,
9013            no_viable_candidates: false,
9014        };
9015        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9016        assert_eq!(
9017            t.status,
9018            TaskStatus::Held,
9019            "unspent task attempts cannot start another competition"
9020        );
9021        let at = t.held_at;
9022        let cause = t.hold_notice_cause.clone();
9023        state.begin_pass();
9024        t.release_operator("test-resume", None);
9025        t.start(state.id.clone());
9026        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9027        assert_eq!(t.status, TaskStatus::Held);
9028        assert_eq!(t.held_at, at);
9029        assert_eq!(t.hold_notice_cause, cause);
9030    }
9031
9032    #[test]
9033    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9034        let mut state = run_state(RunStatus::Blocked);
9035        state.gate = vec![CommandOutcome {
9036            command: "cargo test".to_owned(),
9037            code: Some(101),
9038            output_tail: "assertion failed".to_owned(),
9039            duration_ms: 0,
9040            resource_blocked: false,
9041        }];
9042        let verdict = Verdict {
9043            status: RunStatus::Blocked,
9044            left_pr: false,
9045            quota_hit: false,
9046            parked: false,
9047            no_viable_candidates: false,
9048        };
9049
9050        // Attempt one of two still has a retry coming: no diagnostic yet, the
9051        // task is going to run again and this run's evidence would go stale.
9052        let mut t = task();
9053        t.start("run-1".to_owned());
9054        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9055        assert_eq!(t.status, TaskStatus::Failed);
9056        assert!(t.diagnostic.is_none());
9057
9058        // Attempt two exhausts the budget: now it is held, and the
9059        // diagnostic is what `magi task show` has to say more than one line.
9060        t.start("run-2".to_owned());
9061        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9062        assert_eq!(t.status, TaskStatus::Held);
9063        let d = t.diagnostic.expect("a held task must carry its diagnostic");
9064        assert!(d.contains("cargo test"), "{d}");
9065    }
9066
9067    #[test]
9068    fn a_held_task_names_the_open_question_it_is_waiting_on() {
9069        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
9070        // `magi ask` question settled Held with `hold_reason: null`, so the
9071        // notification said nothing actionable. `note_open_question` should
9072        // append the question id to whatever `handed_off` already wrote.
9073        crate::run::pin_test_home();
9074        let home = crate::run::home();
9075        let state = run_state(RunStatus::VerifiedNoop);
9076        let mut q = ask::Question::new(
9077            state.id.clone(),
9078            "implement".to_owned(),
9079            "impl-A".to_owned(),
9080            "is this really a no-op?".to_owned(),
9081            String::new(),
9082            Vec::new(),
9083        );
9084        Questions::at(home.join("questions")).put(&mut q).unwrap();
9085
9086        let verdict = Verdict {
9087            status: RunStatus::VerifiedNoop,
9088            left_pr: false,
9089            quota_hit: false,
9090            parked: false,
9091            no_viable_candidates: false,
9092        };
9093        let mut t = task();
9094        t.start(state.id.clone());
9095        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9096
9097        assert_eq!(t.status, TaskStatus::Held);
9098        let reason = t.hold_reason.expect("a held task must record why");
9099        assert!(
9100            reason.starts_with("run ended agent-verified no-op"),
9101            "the original settle reason must survive unchanged: {reason}"
9102        );
9103        assert!(
9104            reason.contains(q.short()),
9105            "the open question's id must be named so the notice is actionable: {reason}"
9106        );
9107    }
9108
9109    #[test]
9110    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9111        crate::run::pin_test_home();
9112        let state = run_state(RunStatus::VerifiedNoop);
9113
9114        let verdict = Verdict {
9115            status: RunStatus::VerifiedNoop,
9116            left_pr: false,
9117            quota_hit: false,
9118            parked: false,
9119            no_viable_candidates: false,
9120        };
9121        let mut t = task();
9122        t.start(state.id.clone());
9123        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9124
9125        assert_eq!(t.status, TaskStatus::Held);
9126        assert_eq!(
9127            t.hold_reason.as_deref(),
9128            Some("run ended agent-verified no-op"),
9129            "nothing to append when the question was already answered or never asked"
9130        );
9131    }
9132
9133    #[test]
9134    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
9135        crate::run::pin_test_home();
9136        let mut first = run_state(RunStatus::Blocked);
9137        first.id = "20260101-000000-sup1".to_owned();
9138        first.save().unwrap();
9139        let mut second = run_state(RunStatus::Merged);
9140        second.id = "20260101-000000-sup2".to_owned();
9141        second.save().unwrap();
9142
9143        let mut t = task();
9144        t.runs = vec![first.id.clone(), second.id.clone()];
9145        t.status = TaskStatus::Done;
9146
9147        supersede_prior_runs(&t, &crate::run::home());
9148
9149        assert_eq!(
9150            RunState::load(&first.id).unwrap().status,
9151            RunStatus::Superseded,
9152            "the first attempt's Blocked no longer needs anyone's attention"
9153        );
9154        assert_eq!(
9155            RunState::load(&second.id).unwrap().status,
9156            RunStatus::Merged,
9157            "the run that actually succeeded is left exactly as it was"
9158        );
9159    }
9160
9161    #[test]
9162    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
9163        // `is_working_on` alone only proves a *daemon* claim; a `magi run
9164        // --resume` invoked by hand outside the daemon never touches
9165        // `daemon.json` at all, so it would look identical to a genuinely
9166        // idle run without also consulting `RunState::liveness`, which reads
9167        // this run's own recorded `driver_pid` instead.
9168        crate::run::pin_test_home();
9169        let mut first = run_state(RunStatus::Blocked);
9170        first.id = "20260101-000000-sup9".to_owned();
9171        // This test process's own pid: guaranteed alive without needing a
9172        // real second process or daemon.
9173        first.driver_pid = Some(std::process::id());
9174        first.driver_started_at = Some(
9175            crate::proc::process_started_at(std::process::id())
9176                .expect("this test process's own start time must be queryable"),
9177        );
9178        first.save().unwrap();
9179        let mut second = run_state(RunStatus::Merged);
9180        second.id = "20260101-000000-supa".to_owned();
9181        second.save().unwrap();
9182
9183        let mut t = task();
9184        t.runs = vec![first.id.clone(), second.id.clone()];
9185        t.status = TaskStatus::Done;
9186
9187        supersede_prior_runs(&t, &crate::run::home());
9188
9189        assert_eq!(
9190            RunState::load(&first.id).unwrap().status,
9191            RunStatus::Blocked,
9192            "a live driver_pid means something is still actually working this run, \
9193             even though no daemon claims it - rewriting under it would just be \
9194             undone the next time that process saves"
9195        );
9196    }
9197
9198    #[test]
9199    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
9200        // The first resweep must skip a still-live attempt exactly like
9201        // `supersede_prior_runs` itself does; a later resweep, once that
9202        // process is no longer actually driving it, is what closes the gap
9203        // `supersede_prior_runs` alone leaves - a task only ever reaches
9204        // `Done` once, so nothing else would ever look at this run again.
9205        let dir = tempfile::tempdir().unwrap();
9206        let home = dir.path().to_path_buf();
9207        let queue = Queue::at(dir.path().join("queue"));
9208
9209        let mut first = run_state(RunStatus::Blocked);
9210        first.id = "20260101-000000-supd".to_owned();
9211        first.driver_pid = Some(std::process::id());
9212        first.driver_started_at = Some(
9213            crate::proc::process_started_at(std::process::id())
9214                .expect("this test process's own start time must be queryable"),
9215        );
9216        first.save_under(&home).unwrap();
9217        let mut second = run_state(RunStatus::Merged);
9218        second.id = "20260101-000000-supe".to_owned();
9219        second.save_under(&home).unwrap();
9220
9221        let mut t = task();
9222        t.runs = vec![first.id.clone(), second.id.clone()];
9223        t.status = TaskStatus::Done;
9224        queue.put(&mut t).unwrap();
9225
9226        resweep_superseded_attempts(&queue, &home);
9227        assert_eq!(
9228            RunState::load_under(&first.id, &home).unwrap().status,
9229            RunStatus::Blocked,
9230            "still live on the first pass, so still untouched"
9231        );
9232
9233        // Stand in for the manual process no longer being the one driving
9234        // this run: same pid (this test process really is still alive), but
9235        // an identity marker that no longer matches it - see
9236        // `RunState::liveness`'s own doc for why a mismatched
9237        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
9238        let mut stale = RunState::load_under(&first.id, &home).unwrap();
9239        stale.driver_started_at = Some("1".to_owned());
9240        stale.save_under(&home).unwrap();
9241
9242        resweep_superseded_attempts(&queue, &home);
9243        assert_eq!(
9244            RunState::load_under(&first.id, &home).unwrap().status,
9245            RunStatus::Superseded,
9246            "the second pass catches up what the first one correctly skipped"
9247        );
9248    }
9249
9250    #[test]
9251    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
9252        crate::run::pin_test_home();
9253        let mut first = run_state(RunStatus::Blocked);
9254        first.id = "20260101-000000-sup3".to_owned();
9255        first.save().unwrap();
9256        let mut second = run_state(RunStatus::Blocked);
9257        second.id = "20260101-000000-sup4".to_owned();
9258        second.save().unwrap();
9259
9260        let mut t = task();
9261        t.runs = vec![first.id.clone(), second.id.clone()];
9262        // Still retrying: nothing about this task's story is settled yet, so
9263        // neither Blocked run may be relabelled, even though a later attempt
9264        // already exists.
9265        t.status = TaskStatus::Failed;
9266
9267        supersede_prior_runs(&t, &crate::run::home());
9268
9269        assert_eq!(
9270            RunState::load(&first.id).unwrap().status,
9271            RunStatus::Blocked
9272        );
9273        assert_eq!(
9274            RunState::load(&second.id).unwrap().status,
9275            RunStatus::Blocked
9276        );
9277    }
9278
9279    #[test]
9280    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9281        // `magi task done` (or the API's equivalent) can close a task with no
9282        // run of its own ever having succeeded - there is nothing here that
9283        // counts as "the attempt that finished it", so nothing is rewritten.
9284        crate::run::pin_test_home();
9285        let mut first = run_state(RunStatus::Blocked);
9286        first.id = "20260101-000000-sup5".to_owned();
9287        first.save().unwrap();
9288
9289        let mut t = task();
9290        t.runs = vec![first.id.clone()];
9291        t.status = TaskStatus::Done;
9292
9293        supersede_prior_runs(&t, &crate::run::home());
9294
9295        assert_eq!(
9296            RunState::load(&first.id).unwrap().status,
9297            RunStatus::Blocked,
9298            "a single-attempt task has no earlier run to supersede"
9299        );
9300    }
9301
9302    #[test]
9303    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9304        // `magi task done` (or the web/conductor equivalents) can close a
9305        // task in any status, including one whose *last* recorded attempt is
9306        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
9307        // never watched, say. `runs.last()` being `Done`-adjacent is not
9308        // proof it actually succeeded, so nothing earlier may be relabelled
9309        // on its say-so alone.
9310        crate::run::pin_test_home();
9311        let mut first = run_state(RunStatus::Blocked);
9312        first.id = "20260101-000000-supb".to_owned();
9313        first.save().unwrap();
9314        let mut second = run_state(RunStatus::Failed);
9315        second.id = "20260101-000000-supc".to_owned();
9316        second.save().unwrap();
9317
9318        let mut t = task();
9319        t.runs = vec![first.id.clone(), second.id.clone()];
9320        t.status = TaskStatus::Done;
9321
9322        supersede_prior_runs(&t, &crate::run::home());
9323
9324        assert_eq!(
9325            RunState::load(&first.id).unwrap().status,
9326            RunStatus::Blocked,
9327            "the task's last attempt never landed, so there is nothing here \
9328             actually superseding it"
9329        );
9330    }
9331
9332    #[test]
9333    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9334        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
9335        // to look" - `Failed` and `VerifiedNoop` are already their own
9336        // terminal answers and must not be relabelled into a third one.
9337        crate::run::pin_test_home();
9338        let mut failed = run_state(RunStatus::Failed);
9339        failed.id = "20260101-000000-sup6".to_owned();
9340        failed.save().unwrap();
9341        let mut noop = run_state(RunStatus::VerifiedNoop);
9342        noop.id = "20260101-000000-sup7".to_owned();
9343        noop.save().unwrap();
9344        let mut winner = run_state(RunStatus::Ready);
9345        winner.id = "20260101-000000-sup8".to_owned();
9346        winner.save().unwrap();
9347
9348        let mut t = task();
9349        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9350        t.status = TaskStatus::Done;
9351
9352        supersede_prior_runs(&t, &crate::run::home());
9353
9354        assert_eq!(
9355            RunState::load(&failed.id).unwrap().status,
9356            RunStatus::Failed
9357        );
9358        assert_eq!(
9359            RunState::load(&noop.id).unwrap().status,
9360            RunStatus::VerifiedNoop
9361        );
9362    }
9363
9364    fn approval_question(run: &str) -> ask::Question {
9365        ask::Question::new(
9366            run.to_owned(),
9367            land::APPROVAL_NODE.to_owned(),
9368            "land".to_owned(),
9369            "merge?".to_owned(),
9370            String::new(),
9371            vec!["merge".to_owned(), "hold".to_owned()],
9372        )
9373    }
9374
9375    #[test]
9376    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9377        crate::run::pin_test_home();
9378        let mut state = run_state(RunStatus::Landing);
9379        state.id = "20260101-000000-fre1".to_owned();
9380        state.parked = true;
9381        state.save().unwrap();
9382        ask::Questions::open()
9383            .put(&mut approval_question(&state.id))
9384            .unwrap();
9385
9386        let mut t = task();
9387        t.runs.push(state.id.clone());
9388        assert_eq!(
9389            land_resume_state(&t),
9390            LandResume::StillWaiting,
9391            "nobody has answered and the timeout has not passed"
9392        );
9393    }
9394
9395    #[test]
9396    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9397        crate::run::pin_test_home();
9398        let mut state = run_state(RunStatus::Gating);
9399        state.id = "20260101-000000-gt01".to_owned();
9400        state.parked = true;
9401        state.config.graph.answer_timeout = 60;
9402        state.github_text = Some(crate::run::GithubTextAsk {
9403            rewrite: None,
9404            fingerprint: "f".into(),
9405            title: true,
9406            body: false,
9407            categories: vec!["title-language".into()],
9408            question: None,
9409            asks: 1,
9410            resolved: false,
9411            chosen_title: None,
9412            choice: None,
9413            publication: None,
9414        });
9415        state.save().unwrap();
9416        let store = ask::Questions::open();
9417        let mut q = ask::Question::new(
9418            state.id.clone(),
9419            crate::github_text::ASK_NODE.to_owned(),
9420            crate::github_text::ASK_SEAT.to_owned(),
9421            "s".into(),
9422            String::new(),
9423            vec!["use fallback".into()],
9424        );
9425        store.put(&mut q).unwrap();
9426        let mut t = task();
9427        t.runs.push(state.id.clone());
9428        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9429        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9430        store.put(&mut q).unwrap();
9431        assert_eq!(land_resume_state(&t), LandResume::Ready);
9432        assert!(!store.get(&q.id).unwrap().status.open());
9433        // Once decided, a parked run is an ordinary candidate again.
9434        state.github_text.as_mut().unwrap().resolved = true;
9435        state.save().unwrap();
9436        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9437    }
9438
9439    #[test]
9440    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9441        // `ask::ask_and_wait`'s own deadline used to retire a question
9442        // nobody answered; land's approval bypasses that wait (see
9443        // `land::approval_gate`), so this is now the only place
9444        // `graph.answer_timeout` is enforced for a land approval at all.
9445        crate::run::pin_test_home();
9446        let mut state = run_state(RunStatus::Landing);
9447        state.id = "20260101-000000-exp1".to_owned();
9448        state.parked = true;
9449        state.config.graph.answer_timeout = 60;
9450        state.save().unwrap();
9451
9452        let store = ask::Questions::open();
9453        let mut q = approval_question(&state.id);
9454        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9455        store.put(&mut q).unwrap();
9456
9457        let mut t = task();
9458        t.runs.push(state.id.clone());
9459        assert_eq!(
9460            land_resume_state(&t),
9461            LandResume::Ready,
9462            "an expired question must not be waited on forever"
9463        );
9464
9465        let after = store.get(&q.id).unwrap();
9466        assert!(
9467            !after.status.open(),
9468            "the question is abandoned, not silently ignored"
9469        );
9470        assert!(
9471            after.resolution().is_none(),
9472            "an abandoned question is not read as a decision"
9473        );
9474    }
9475
9476    #[test]
9477    fn reclaim_settles_a_running_task_against_its_last_run() {
9478        let mut t = task();
9479        t.start("20260904-000000-4043".to_owned());
9480        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9481        assert_eq!(
9482            t.status,
9483            TaskStatus::Done,
9484            "a run that actually finished must not stay `running` forever"
9485        );
9486    }
9487
9488    #[test]
9489    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
9490        let dir = tempfile::tempdir().unwrap();
9491        let queue = Queue::at(dir.path().join("queue"));
9492        let mut task = task();
9493        let mut run = run_state(RunStatus::Blocked);
9494        run.reserve_under(dir.path()).unwrap();
9495        run.driver_exited = true;
9496        run.save_under(dir.path()).unwrap();
9497        queue.put(&mut task).unwrap();
9498        let stale = task.clone();
9499        task.resume_override = Some(crate::queue::OperatorResume {
9500            question_id: "pending-resume".into(),
9501            at: Timestamp::now(),
9502            conductor_rehold: None,
9503            forced: true,
9504            pinned_run: Some(run.id.clone()),
9505        });
9506        task.start(run.id.clone());
9507        queue.put(&mut task).unwrap();
9508        // Discard every in-memory handoff, as a worker death before execute does.
9509        let mut recovered = queue.get(&task.id).unwrap();
9510        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
9511        reclaim(&mut recovered, Some(disk), 2, "en");
9512        queue.put(&mut recovered).unwrap();
9513        assert!(recovered.resume_override.is_none());
9514        assert_eq!(
9515            recovered.dispatched_resumes.get("pending-resume"),
9516            Some(&run.id)
9517        );
9518        let mut stale = stale;
9519        queue.put(&mut stale).unwrap();
9520        assert_eq!(
9521            stale.dispatched_resumes, recovered.dispatched_resumes,
9522            "a stale task writer cannot erase dispatch ownership"
9523        );
9524        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
9525        assert!(resumed.decision_starts.is_empty());
9526        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
9527        assert!(
9528            resumed.decision_starts.is_empty(),
9529            "handoff is not execution proof"
9530        );
9531        resumed.begin_pass();
9532        resumed.save_under(dir.path()).unwrap();
9533        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
9534        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
9535        disk.carry_dispatched_resumes(&recovered);
9536        disk.begin_pass();
9537        assert_eq!(
9538            disk.decision_starts.get("pending-resume"),
9539            Some(&0),
9540            "later execution must preserve the original pass receipt"
9541        );
9542    }
9543
9544    #[test]
9545    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9546        let mut t = task();
9547        t.start("20260904-000000-4043".to_owned());
9548        t.last_error = Some("earlier trouble".to_owned());
9549        let mut state = run_state(RunStatus::Judging);
9550        state.parked = true;
9551        reclaim(&mut t, Some(state), 1, "en");
9552        assert_eq!(t.status, TaskStatus::Parked);
9553        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9554        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9555        assert!(t.park_reason.is_some());
9556        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9557        assert!(!t.fresh_start);
9558        assert!(t.status.runnable());
9559    }
9560
9561    #[test]
9562    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9563        let mut t = task();
9564        t.start("20260904-000000-4043".to_owned());
9565        t.last_error = Some("earlier trouble".to_owned());
9566        settle(
9567            &mut t,
9568            Verdict {
9569                status: RunStatus::Judging,
9570                left_pr: false,
9571                quota_hit: false,
9572                parked: true,
9573                no_viable_candidates: false,
9574            },
9575            "parked after `judging`",
9576            1,
9577        );
9578        assert_eq!(t.status, TaskStatus::Parked);
9579        assert_eq!(t.attempts, 0);
9580        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9581        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9582        assert_eq!(t.schema, crate::queue::SCHEMA);
9583        assert!(
9584            crate::notices::task_held(&t).is_none(),
9585            "a park is not news"
9586        );
9587        t.start("20260904-000000-4043".to_owned());
9588        assert_eq!(t.park_reason, None);
9589    }
9590
9591    #[test]
9592    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9593        // A blocked run with attempts left goes back to `Failed`, exactly as
9594        // it would from `attempt` itself - `reclaim` must not invent a second
9595        // policy for a task a daemon merely stopped without reporting.
9596        let mut t = task();
9597        t.start("20260904-000000-4043".to_owned());
9598        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9599        assert_eq!(t.status, TaskStatus::Failed);
9600        assert!(t.status.runnable());
9601    }
9602
9603    #[test]
9604    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9605        let mut t = task();
9606        t.start("20260904-000000-4043".to_owned());
9607        assert_eq!(t.attempts, 1);
9608        let mut run = run_state(RunStatus::Implementing);
9609        run.id = "20260904-000000-4043".to_owned();
9610        run.begin_pass();
9611        let cause = crate::run::ParkCause::Upgrade {
9612            from: "0.121.0".to_owned(),
9613            to: Some("0.121.1".to_owned()),
9614        };
9615        run.end_pass_parked(cause.clone());
9616        run.parked = true;
9617        let verdict = Verdict {
9618            status: run.status,
9619            left_pr: false,
9620            quota_hit: false,
9621            parked: true,
9622            no_viable_candidates: false,
9623        };
9624        // A crash after the checkpoint but before queue settlement must
9625        // recover exactly the same scheduling evidence and refund.
9626        let mut orphan = t.clone();
9627        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9628        assert_eq!(orphan.status, TaskStatus::Parked);
9629        assert_eq!(orphan.attempts, 0);
9630        assert_eq!(
9631            orphan.upgrade_resume_key(),
9632            Some((run.passes[0].started_at, orphan.id.as_str()))
9633        );
9634        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9635        assert_eq!(t.attempts, 0);
9636        assert_eq!(t.passes.len(), 1);
9637        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9638        assert_eq!(t.passes[0].parked, Some(cause));
9639        assert_eq!(t.passes[0].pass_index, 0);
9640        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9641        assert!(t.upgrade_resume_key().is_some());
9642
9643        // A resumed pass that then fails spends its attempt, and the earlier
9644        // pass's entry is untouched.
9645        t.start("20260904-000000-4043".to_owned());
9646        run.begin_pass();
9647        run.status = RunStatus::Failed;
9648        let verdict = Verdict {
9649            status: RunStatus::Failed,
9650            left_pr: false,
9651            quota_hit: false,
9652            parked: false,
9653            no_viable_candidates: false,
9654        };
9655        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9656        assert_eq!(t.passes.len(), 2);
9657        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9658        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9659        assert_eq!(t.passes[1].pass_index, 1);
9660        assert_eq!(t.attempts, 1);
9661    }
9662
9663    #[test]
9664    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9665        let mut t = task();
9666        t.start("20260904-000000-4043".to_owned());
9667        reclaim(&mut t, None, 2, "en");
9668        assert_eq!(t.status, TaskStatus::Held);
9669        assert!(
9670            t.last_error
9671                .as_deref()
9672                .is_some_and(|e| e.contains("running")),
9673            "the operator needs to know why this task was held"
9674        );
9675    }
9676
9677    #[test]
9678    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9679        let dir = tempfile::tempdir().unwrap();
9680        let queue = Queue::at(dir.path().to_path_buf());
9681
9682        // No run recorded, so this never has to touch `RunState::load`.
9683        let mut orphaned = task();
9684        orphaned.id = "20260904-000000-orph".to_owned();
9685        orphaned.status = TaskStatus::Running;
9686        orphaned.attempts = 1;
9687        queue.put(&mut orphaned).unwrap();
9688
9689        let mut alive = task();
9690        alive.id = "20260904-000000-live".to_owned();
9691        alive.status = TaskStatus::Running;
9692        alive.attempts = 1;
9693        queue.put(&mut alive).unwrap();
9694        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9695
9696        let mut queued = task();
9697        queued.id = "20260904-000000-wait".to_owned();
9698        queue.put(&mut queued).unwrap();
9699
9700        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9701        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9702
9703        assert_eq!(
9704            queue.get(&orphaned.id).unwrap().status,
9705            TaskStatus::Held,
9706            "nothing was driving it and there was no run to recover"
9707        );
9708        assert_eq!(
9709            queue.get(&alive.id).unwrap().status,
9710            TaskStatus::Running,
9711            "a live claim must protect the task it belongs to"
9712        );
9713        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9714    }
9715
9716    /// Read a run.json back from an explicit `home`, the same way
9717    /// `reclaim_abandoned_runs` itself does - never through the
9718    /// process-global `RunState::load`, which this test's own `home` (an
9719    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
9720    /// use at all.
9721    fn read_run_under(home: &Path, id: &str) -> RunState {
9722        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9723        serde_json::from_str(&body).unwrap()
9724    }
9725
9726    #[test]
9727    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9728        let dir = tempfile::tempdir().unwrap();
9729        let home = dir.path().to_path_buf();
9730        let now = Timestamp::now();
9731        let overrun_seat = || crate::run::ActiveSeat {
9732            node: "implement".to_owned(),
9733            started_at: now - jiff::SignedDuration::new(21_000, 0),
9734            timeout_secs: 3_600,
9735            attempt: 0,
9736            task: None,
9737            command: None,
9738            index: None,
9739            total: None,
9740        };
9741
9742        let mut dead = run_state(RunStatus::Implementing);
9743        dead.id = "20260101-000000-dead".to_owned();
9744        dead.active.insert("impl-A".to_owned(), overrun_seat());
9745        // A `driver_pid` the injected query below confirms gone outright —
9746        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
9747        dead.driver_pid = Some(4242);
9748        dead.save_under(&home).unwrap();
9749
9750        // Same shape, but a live daemon's heartbeat names it: must be left
9751        // exactly alone, however far past its own timeout the seat sits.
9752        let mut alive = run_state(RunStatus::Implementing);
9753        alive.id = "20260101-000000-aliv".to_owned();
9754        alive.active.insert("impl-A".to_owned(), overrun_seat());
9755        alive.save_under(&home).unwrap();
9756        let mut status = Status::new();
9757        status.current = vec![Current {
9758            worker: None,
9759            task: "20260101-000000-task".to_owned(),
9760            run: alive.id.clone(),
9761        }];
9762        write_status_to(&home.join("daemon.json"), &status).unwrap();
9763
9764        // The abandoned seat left an open question behind: nobody is left to
9765        // read an answer once the run is failed, and this must not wait for
9766        // some later daemon startup's own sweep to notice that.
9767        let questions = Questions::at(home.join("questions"));
9768        let mut q = ask::Question::new(
9769            dead.id.clone(),
9770            "implement".to_owned(),
9771            "impl-A".to_owned(),
9772            "Which storage backend?".to_owned(),
9773            String::new(),
9774            vec!["SQLite".to_owned(), "Redis".to_owned()],
9775        );
9776        questions.put(&mut q).unwrap();
9777
9778        let abandoned = reclaim_abandoned_runs_with(
9779            &home,
9780            now,
9781            |pid| if pid == 4242 { Some(false) } else { None },
9782            |_| panic!("a query answering Dead outright needs no identity corroboration"),
9783        );
9784        assert_eq!(abandoned, vec![dead.id.clone()]);
9785
9786        let reloaded = read_run_under(&home, &dead.id);
9787        assert_eq!(reloaded.status, RunStatus::Failed);
9788        assert!(reloaded.active.is_empty());
9789        assert!(
9790            !questions.get(&q.id).unwrap().status.open(),
9791            "the failed run's own open question must be settled in the same pass"
9792        );
9793
9794        let still_alive = read_run_under(&home, &alive.id);
9795        assert_eq!(
9796            still_alive.status,
9797            RunStatus::Implementing,
9798            "a live daemon's claim protects it"
9799        );
9800        assert!(!still_alive.active.is_empty());
9801    }
9802
9803    /// The exact shape a review round flagged as broken: `magi serve` running
9804    /// in this same `home` scans *every* run on disk, including a manual
9805    /// `magi review` / `magi run` this daemon never started and that
9806    /// therefore claims no heartbeat of its own. Before this scan asked
9807    /// `liveness` rather than just `is_working_on`, a manual run whose active
9808    /// seat merely ran a little past its own timeout — the CLI finishing up,
9809    /// its result still being collected — got wiped and failed by a daemon
9810    /// that had nothing to do with it, out from under a process that was
9811    /// still very much running.
9812    #[test]
9813    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9814        let dir = tempfile::tempdir().unwrap();
9815        let home = dir.path().to_path_buf();
9816        let now = Timestamp::now();
9817
9818        let mut manual = run_state(RunStatus::Reviewing);
9819        manual.id = "20260101-000000-manl".to_owned();
9820        manual.active.insert(
9821            "review-1".to_owned(),
9822            crate::run::ActiveSeat {
9823                node: "review".to_owned(),
9824                started_at: now - jiff::SignedDuration::new(21_000, 0),
9825                timeout_secs: 3_600,
9826                attempt: 0,
9827                task: None,
9828                command: None,
9829                index: None,
9830                total: None,
9831            },
9832        );
9833        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
9834        // but a real, still-running process: `liveness` must corroborate this
9835        // as `Live`, not read the missing daemon claim as death.
9836        manual.driver_pid = Some(4242);
9837        manual.driver_started_at = Some("1790000000".to_owned());
9838        manual.save_under(&home).unwrap();
9839
9840        let abandoned = reclaim_abandoned_runs_with(
9841            &home,
9842            now,
9843            |pid| if pid == 4242 { Some(true) } else { None },
9844            |pid| {
9845                if pid == 4242 {
9846                    Some("1790000000".to_owned())
9847                } else {
9848                    None
9849                }
9850            },
9851        );
9852        assert!(
9853            abandoned.is_empty(),
9854            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9855        );
9856
9857        let reloaded = read_run_under(&home, &manual.id);
9858        assert_eq!(reloaded.status, RunStatus::Reviewing);
9859        assert!(!reloaded.active.is_empty());
9860    }
9861
9862    #[test]
9863    fn an_already_claimed_task_is_skipped_rather_than_failed() {
9864        let dir = tempfile::tempdir().unwrap();
9865        let queue = Queue::at(dir.path().to_path_buf());
9866        let mut only = task();
9867        queue.put(&mut only).unwrap();
9868
9869        let _elsewhere = queue.claim(&only.id).unwrap();
9870        let candidates = runnable(&queue);
9871        assert_eq!(candidates.len(), 1, "the task is still runnable");
9872        assert!(
9873            queue.claim(&candidates[0].id).is_err(),
9874            "the loop cannot take a claim somebody else holds"
9875        );
9876
9877        let after = queue.get(&only.id).unwrap();
9878        assert_eq!(after.status, TaskStatus::Queued);
9879        assert_eq!(
9880            after.attempts, 0,
9881            "losing the race is not an attempt at the task"
9882        );
9883        assert_eq!(after.last_error, None);
9884    }
9885
9886    #[test]
9887    fn the_status_file_round_trips_and_its_heartbeat_advances() {
9888        let dir = tempfile::tempdir().unwrap();
9889        let path = dir.path().join("daemon.json");
9890
9891        let mut status = Status::new();
9892        status.idle = false;
9893        status.completed = 7;
9894        status.current = vec![Current {
9895            worker: None,
9896            task: "20260902-000000-t111".to_owned(),
9897            run: "20260902-000001-r111".to_owned(),
9898        }];
9899        write_status_to(&path, &status).unwrap();
9900        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9901        assert_eq!(first.schema, SCHEMA);
9902        assert_eq!(first.pid, std::process::id());
9903        assert!(!first.idle);
9904        assert_eq!(first.completed, 7);
9905        assert_eq!(first.current, status.current);
9906        assert!(
9907            !path.with_extension("json.tmp").exists(),
9908            "the temp file is renamed, not left behind"
9909        );
9910
9911        std::thread::sleep(Duration::from_millis(5));
9912        status.updated_at = Timestamp::now();
9913        status.polls = 3;
9914        write_status_to(&path, &status).unwrap();
9915        let second: Status =
9916            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9917        assert!(
9918            second.updated_at > first.updated_at,
9919            "a reader can only detect staleness if the heartbeat moves"
9920        );
9921        assert_eq!(
9922            second.started_at, first.started_at,
9923            "the start time is not a heartbeat"
9924        );
9925        assert_eq!(second.polls, 3);
9926    }
9927
9928    #[test]
9929    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9930        let dir = tempfile::tempdir().unwrap();
9931
9932        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9933
9934        let mut status = Status::new();
9935        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9936        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9937        let stale = read_status(dir.path()).unwrap();
9938        assert!(
9939            !stale.running(Timestamp::now()),
9940            "a minute without a heartbeat is a dead daemon, not a busy one"
9941        );
9942        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9943
9944        status.updated_at = Timestamp::now();
9945        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9946        let fresh = read_status(dir.path()).unwrap();
9947        assert!(fresh.running(Timestamp::now()));
9948    }
9949
9950    #[test]
9951    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9952        let dir = tempfile::tempdir().unwrap();
9953        let now = Timestamp::now();
9954        let mine = "20260903-080619-01c2";
9955
9956        assert!(
9957            !is_working_on(dir.path(), mine, now),
9958            "no status file means nobody is working on anything"
9959        );
9960
9961        let mut status = Status::new();
9962        status.current = vec![Current {
9963            worker: None,
9964            task: "20260903-080340-0167".to_owned(),
9965            run: mine.to_owned(),
9966        }];
9967        status.updated_at = now;
9968        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9969        assert!(is_working_on(dir.path(), mine, now));
9970        assert!(
9971            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9972            "a daemon busy with one run is not working on another"
9973        );
9974
9975        // A killed daemon stops writing heartbeats but leaves the file behind
9976        // naming the run it died in. That run must not be undeletable forever.
9977        status.updated_at = now - jiff::SignedDuration::from_secs(600);
9978        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9979        assert!(
9980            !is_working_on(dir.path(), mine, now),
9981            "a stale heartbeat is a dead daemon, so its run is a leftover"
9982        );
9983    }
9984
9985    #[test]
9986    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9987        let dir = tempfile::tempdir().unwrap();
9988        let now = Timestamp::now();
9989
9990        assert!(
9991            !is_working_on_short(dir.path(), "01c2", now),
9992            "no status file means nobody is working on anything"
9993        );
9994
9995        let mut status = Status::new();
9996        status.current = vec![Current {
9997            worker: None,
9998            task: "20260903-080340-0167".to_owned(),
9999            run: "20260903-080619-01c2".to_owned(),
10000        }];
10001        status.updated_at = now;
10002        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10003        assert!(
10004            is_working_on_short(dir.path(), "01c2", now),
10005            "the run's short id is the last block of its full id"
10006        );
10007        assert!(
10008            !is_working_on_short(dir.path(), "3cbf", now),
10009            "a daemon busy with one worktree bay is not working on another"
10010        );
10011    }
10012
10013    #[test]
10014    fn a_newer_status_file_still_yields_a_reading() {
10015        let dir = tempfile::tempdir().unwrap();
10016        // A field this build has never heard of must not turn the reading into
10017        // nothing at all; that is the whole reason the reader is permissive.
10018        std::fs::write(
10019            dir.path().join("daemon.json"),
10020            serde_json::json!({
10021                "schema": 2,
10022                "updated_at": Timestamp::now().to_string(),
10023                "idle": true,
10024                "surprise": { "nested": [1, 2, 3] },
10025            })
10026            .to_string(),
10027        )
10028        .unwrap();
10029
10030        let reading = read_status(dir.path()).expect("a forward-compatible read");
10031        assert!(reading.running(Timestamp::now()));
10032        assert!(reading.idle);
10033        assert!(reading.current.is_empty());
10034    }
10035
10036    #[test]
10037    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
10038        // A daemon started before `current` became a list keeps writing this
10039        // shape on every heartbeat until it is restarted. A rolling upgrade
10040        // - a newer `magi web` or `magi doctor` reading an older `magi
10041        // serve`'s heartbeat - must still see the run it is on, not "no
10042        // daemon" from a type mismatch failing the whole struct.
10043        let dir = tempfile::tempdir().unwrap();
10044        std::fs::write(
10045            dir.path().join("daemon.json"),
10046            serde_json::json!({
10047                "schema": 1,
10048                "pid": 4242,
10049                "updated_at": Timestamp::now().to_string(),
10050                "idle": false,
10051                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
10052                "completed": 3,
10053                "polls": 9,
10054            })
10055            .to_string(),
10056        )
10057        .unwrap();
10058
10059        let reading = read_status(dir.path()).expect("an older shape must still parse");
10060        assert!(reading.running(Timestamp::now()));
10061        assert_eq!(
10062            reading.current,
10063            vec![Current {
10064                worker: None,
10065                task: "20260902-140501-aaaa".to_owned(),
10066                run: "20260902-140502-bbbb".to_owned(),
10067            }]
10068        );
10069    }
10070
10071    #[test]
10072    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
10073        let dir = tempfile::tempdir().unwrap();
10074        std::fs::write(
10075            dir.path().join("daemon.json"),
10076            serde_json::json!({
10077                "schema": 1,
10078                "updated_at": Timestamp::now().to_string(),
10079                "idle": true,
10080                "current": null,
10081            })
10082            .to_string(),
10083        )
10084        .unwrap();
10085        let with_null = read_status(dir.path()).expect("null must still parse");
10086        assert!(with_null.current.is_empty());
10087
10088        std::fs::write(
10089            dir.path().join("daemon.json"),
10090            serde_json::json!({
10091                "schema": 1,
10092                "updated_at": Timestamp::now().to_string(),
10093                "idle": true,
10094            })
10095            .to_string(),
10096        )
10097        .unwrap();
10098        let absent = read_status(dir.path()).expect("a missing field must still parse");
10099        assert!(absent.current.is_empty());
10100    }
10101
10102    #[test]
10103    fn a_task_without_a_repository_runs_in_the_daemons_default() {
10104        let fallback = Path::new("/default");
10105        let mut blank = task();
10106        blank.repo = PathBuf::new();
10107        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
10108        let mut dot = task();
10109        dot.repo = PathBuf::from(".");
10110        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
10111        assert_eq!(
10112            repo_for(&task(), fallback),
10113            PathBuf::from("/repo"),
10114            "a task that names a repository keeps it"
10115        );
10116    }
10117
10118    #[test]
10119    fn task_implementers_edit_inherits_daemon_config_and_merge() {
10120        let dir = tempfile::tempdir().unwrap();
10121        let path = dir.path().join("explicit.toml");
10122        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
10123        let opts = Opts {
10124            config: Some(path),
10125            merge: Some("none".into()),
10126            ..Default::default()
10127        };
10128        let mut t = task();
10129        t.set_implementers(
10130            2,
10131            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10132                .unwrap(),
10133        )
10134        .unwrap();
10135        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10136        assert_eq!(cfg.graph.implementers, 2);
10137        assert_eq!(cfg.graph.judges, 1);
10138        assert_eq!(cfg.merge.mode, MergeMode::None);
10139        t.set_implementers(1, &cfg).unwrap();
10140        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10141        apply_task_implementers(&mut cfg, &t);
10142        assert_eq!(cfg.graph.implementers, 1);
10143        assert_eq!(cfg.graph.judges, 1);
10144        assert_eq!(cfg.merge.mode, MergeMode::None);
10145    }
10146
10147    #[test]
10148    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
10149        let dir = tempfile::tempdir().unwrap();
10150        let repo = dir.path().join("repo");
10151        std::fs::create_dir(&repo).unwrap();
10152        std::fs::write(
10153            repo.join("magi.toml"),
10154            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
10155        )
10156        .unwrap();
10157        let daemon_config = dir.path().join("daemon.toml");
10158        std::fs::write(
10159            &daemon_config,
10160            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
10161        )
10162        .unwrap();
10163        let opts = Opts {
10164            config: Some(daemon_config),
10165            merge: Some("pr".into()),
10166            ..Default::default()
10167        };
10168        let q = Queue::at(dir.path().join("queue"));
10169        let validation: Config =
10170            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10171                .unwrap();
10172        // No provenance field on legacy direct tasks: both shapes stay isolated.
10173        for record in ["{}", r#"{"candidates":2}"#] {
10174            let overrides = serde_json::from_str(record).unwrap();
10175            let filing = crate::direct::Filing {
10176                instruction: "work".into(),
10177                title: "direct".into(),
10178                repo: repo.clone(),
10179                source: crate::queue::Source::Human,
10180                solo: false,
10181                overrides,
10182                review_of: None,
10183                sources: Default::default(),
10184            };
10185            let filed =
10186                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
10187            let crate::direct::Filed::Standalone {
10188                mut task,
10189                claim: _claim,
10190            } = filed
10191            else {
10192                panic!("local filing")
10193            };
10194            let before = prepare_for(&repo, &opts, &task).unwrap();
10195            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
10196            assert_eq!(
10197                before.merge.mode,
10198                MergeMode::None,
10199                "daemon --merge must not leak"
10200            );
10201            for n in [2, 1, 2] {
10202                task.set_implementers(n, &validation).unwrap();
10203                q.put(&mut task).unwrap();
10204                task = q.get(&task.id).unwrap();
10205                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
10206                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
10207                apply_task_implementers(&mut cfg, &task);
10208                assert_eq!(cfg.graph.implementers, usize::from(n));
10209                assert_eq!(cfg.graph.judges, 2);
10210                assert_eq!(cfg.merge.mode, MergeMode::None);
10211            }
10212        }
10213    }
10214
10215    #[test]
10216    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
10217        let cfg: Config =
10218            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10219                .unwrap();
10220        let mut t = task();
10221        t.review_of = Some("review-target".into());
10222        t.hold_manual(Some("retry".into()));
10223        let mut previous = RunState::new(
10224            PathBuf::from("/repo"),
10225            "main".into(),
10226            "abc1234".into(),
10227            "review".into(),
10228            cfg.clone(),
10229        );
10230        previous.config.graph.implementers = 2;
10231        for count in [1, 3] {
10232            t.set_implementers(count, &cfg).unwrap();
10233            t.release();
10234            assert_eq!(t.review_of.as_deref(), Some("review-target"));
10235            for proposed in [
10236                Starter::Resume(previous.id.clone()),
10237                Starter::Review("recovery-target".into()),
10238            ] {
10239                assert_eq!(
10240                    starter_with_implementers(&t, Some(&previous), proposed),
10241                    Starter::Review("review-target".into())
10242                );
10243            }
10244            let mut configured = cfg.clone();
10245            apply_task_implementers(&mut configured, &t);
10246            assert_eq!(configured.graph.implementers, usize::from(count));
10247            assert_eq!(previous.config.graph.implementers, 2);
10248        }
10249    }
10250
10251    #[test]
10252    fn task_implementers_dispatch_and_resume_agree() {
10253        let mut t = task();
10254        let cfg: crate::config::Config =
10255            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10256                .unwrap();
10257        let mut run = RunState::new(
10258            PathBuf::from("/repo"),
10259            "main".into(),
10260            "abc1234".into(),
10261            "work".into(),
10262            cfg.clone(),
10263        );
10264        run.config.graph.implementers = 2;
10265        for n in [2, 1, 3, 2] {
10266            t.set_implementers(n, &cfg).unwrap();
10267            let mut dispatched = cfg.clone();
10268            apply_task_implementers(&mut dispatched, &t);
10269            assert_eq!(dispatched.graph.implementers, usize::from(n));
10270            assert_eq!(implementers_match(&t, &run), n == 2);
10271            for proposed in [
10272                Starter::Resume(run.id.clone()),
10273                Starter::Review("old-branch".into()),
10274            ] {
10275                let expected = if n == 2 {
10276                    proposed.clone()
10277                } else {
10278                    Starter::Start
10279                };
10280                assert_eq!(
10281                    starter_with_implementers(&t, Some(&run), proposed),
10282                    expected
10283                );
10284            }
10285            assert_eq!(
10286                run.config.graph.implementers, 2,
10287                "history must not be rewritten"
10288            );
10289        }
10290        t.solo = false;
10291        t.overrides = None;
10292        assert!(implementers_match(&t, &run));
10293    }
10294
10295    #[test]
10296    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
10297        // Three seats said out loud. What `solo` promises is one candidate
10298        // *whatever the config asks for*, so the contrast has to be a number
10299        // this test owns - it used to be `Config::default()`'s, which became
10300        // 1 when one implementation became the default and left the two
10301        // halves of this test asserting the same thing.
10302        let mut solo_cfg = Config::default();
10303        solo_cfg.graph.implementers = 3;
10304        let mut solo_task = task();
10305        solo_task.solo = true;
10306        apply_task_implementers(&mut solo_cfg, &solo_task);
10307        assert_eq!(solo_cfg.graph.implementers, 1);
10308
10309        let mut plain_cfg = Config::default();
10310        plain_cfg.graph.implementers = 3;
10311        let plain_task = task();
10312        assert!(!plain_task.solo);
10313        apply_task_implementers(&mut plain_cfg, &plain_task);
10314        assert_eq!(
10315            plain_cfg.graph.implementers, 3,
10316            "a task that did not ask to run alone keeps the config's candidates"
10317        );
10318    }
10319
10320    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
10321        QuotaLoss {
10322            cause: crate::agent::QuotaCause::UsageLimit,
10323            agent: String::new(),
10324            seat: seat.into(),
10325            node: "judge".into(),
10326            at: at.parse().unwrap(),
10327            reset: reset.map(str::to_string),
10328        }
10329    }
10330
10331    #[test]
10332    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
10333        let now = Timestamp::now();
10334        for reset in [None, Some("in 1h")] {
10335            let auth = crate::agent::Quota {
10336                cause: crate::agent::QuotaCause::Authentication,
10337                agent: "alpha".into(),
10338                reset: reset.map(str::to_owned),
10339            };
10340            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
10341            assert_eq!(cooldown_until(&[loss], now), None);
10342        }
10343    }
10344
10345    #[test]
10346    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
10347        let old: Vec<QuotaLoss> = (1..=4)
10348            .map(|i| {
10349                loss(
10350                    &format!("judge-{i}"),
10351                    "2026-09-23T05:23:00Z",
10352                    Some("2:40pm (Asia/Tokyo)"),
10353                )
10354            })
10355            .collect();
10356        let fresh = losses_this_attempt(&old, &old);
10357        assert!(fresh.is_empty());
10358        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
10359        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
10360    }
10361
10362    #[test]
10363    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
10364        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
10365        let now = Timestamp::now();
10366        let mut after = old.clone();
10367        after.push(loss("judge-2", &now.to_string(), None));
10368        let fresh = losses_this_attempt(&old, &after);
10369        assert_eq!(fresh, vec![after[1].clone()]);
10370        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
10371        assert_eq!(
10372            until,
10373            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
10374        );
10375    }
10376
10377    #[test]
10378    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
10379        // `recover_stall` removes judge-1's loss and the retry then hits quota
10380        // again: the vector is the same length, so an index diff sees nothing.
10381        let before = vec![
10382            loss("judge-1", "2026-09-23T05:23:00Z", None),
10383            loss("judge-2", "2026-09-23T05:24:00Z", None),
10384        ];
10385        let after = vec![
10386            loss("judge-2", "2026-09-23T05:24:00Z", None),
10387            loss("judge-1", "2026-09-24T01:00:00Z", None),
10388        ];
10389        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
10390    }
10391
10392    #[test]
10393    fn merge_overrides_are_parsed_or_refused() {
10394        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
10395        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
10396        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
10397        assert!(merge_mode("squash").is_err());
10398    }
10399
10400    #[test]
10401    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
10402        let now = Timestamp::now();
10403        let fallback = Duration::from_secs(300);
10404        let cap = Duration::from_secs(1800);
10405
10406        // No reset hint at all: the fallback.
10407        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
10408
10409        // A reset ten minutes out, well inside the cap: waited for exactly.
10410        let soon = now + jiff::SignedDuration::from_secs(600);
10411        assert_eq!(
10412            quota_wait(Some(soon), now, fallback, cap),
10413            Duration::from_secs(600)
10414        );
10415
10416        // A reset already in the past is not trusted: the fallback, not a
10417        // zero or negative wait that would spin the loop right back around.
10418        let past = now - jiff::SignedDuration::from_secs(60);
10419        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
10420
10421        // A reset further out than the cap is trusted for direction but not
10422        // for magnitude: a parsing slip must not sleep the loop for a day.
10423        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
10424        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
10425    }
10426
10427    #[test]
10428    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
10429        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10430
10431        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
10432        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
10433
10434        // Same clock reading, but it has already gone by today: read as
10435        // tomorrow's, since the CLI would not still be reporting a limit past
10436        // its own stated reset.
10437        let already_past =
10438            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
10439        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
10440
10441        assert!(
10442            parse_reset_hint("session limit reached", now, now).is_none(),
10443            "free text with no recognised shape is not guessed at"
10444        );
10445        assert!(
10446            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
10447            "an unresolvable zone name is not guessed at either"
10448        );
10449    }
10450
10451    #[test]
10452    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
10453        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10454
10455        let at = parse_reset_hint(
10456            "You've hit your usage limit. Visit \
10457             https://chatgpt.com/codex/settings/usage to purchase more \
10458             credits or try again at Sep 19th, 2026 5:10 PM.",
10459            now,
10460            now,
10461        )
10462        .expect("the codex reset wording is a recognised shape");
10463        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
10464
10465        // The month is explicit, so a date already earlier in the same
10466        // sentence-implied year than `now` is trusted as written rather than
10467        // rolled forward a year the way the bracketed shape rolls a
10468        // same-day clock reading to tomorrow.
10469        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
10470            .expect("an explicit year needs no rollover");
10471        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
10472
10473        assert!(
10474            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
10475            "a two-digit year is not the documented shape and is not guessed at"
10476        );
10477        assert!(
10478            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
10479            "a four-letter month name is not the documented three-letter abbreviation"
10480        );
10481        assert!(
10482            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10483            "an explicit zone on the dated shape is a format nobody has \
10484             documented, and is refused rather than guessed at as UTC"
10485        );
10486    }
10487
10488    #[test]
10489    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10490        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10491        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10492
10493        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10494        assert_eq!(at.as_second() - recorded.as_second(), 3769);
10495
10496        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10497        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10498
10499        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10500            assert!(
10501                parse_reset_hint(bad, now, recorded).is_none(),
10502                "{bad:?} must not be guessed at"
10503            );
10504        }
10505    }
10506
10507    /// A loop whose queue lives in a temp tree and whose poll interval is far
10508    /// longer than the test's patience, so anything that waits out a poll
10509    /// instead of noticing the stop fails rather than merely being slow.
10510    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10511        let config = dir.join("magi.toml");
10512        std::fs::write(
10513            &config,
10514            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10515        )
10516        .unwrap();
10517        let opts = Opts {
10518            poll: Duration::from_secs(30),
10519            config: Some(config),
10520            // The explicit fixture config keeps startup cleanup from reading
10521            // machine configuration. This fictional repository likewise
10522            // keeps any best-effort git cleanup away from this checkout.
10523            repo: dir.join("repo"),
10524            ..Opts::default()
10525        };
10526        // The status file goes in a directory that does not exist yet, so its
10527        // creation is itself evidence the loop published one. `worktrees`
10528        // must be just as fictional: the janitor reclaims worktrees under it
10529        // for real, and a test that let it fall through to
10530        // `crate::run::default_worktree_root()` would have it reclaim
10531        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
10532        // which is exactly what happened before this function took the
10533        // parameter at all.
10534        let home = dir.join("home");
10535        // These control-only fixtures do not launch native workers. Give the
10536        // independently tested maintenance services a fresh cadence receipt.
10537        let stamps = home.join("service-ticks");
10538        std::fs::create_dir_all(&stamps).unwrap();
10539        for service in ["waiter", "deputies", "release-watch"] {
10540            std::fs::write(
10541                stamps.join(service),
10542                Timestamp::now().as_second().to_string(),
10543            )
10544            .unwrap();
10545        }
10546        for operation in [
10547            "conductor",
10548            "maintenance",
10549            "housekeeping",
10550            "disk-pressure",
10551            "cache",
10552            "fetch",
10553        ] {
10554            std::fs::write(
10555                stamps.join(format!("daemon-{operation}")),
10556                serde_json::to_vec(&Timestamp::now()).unwrap(),
10557            )
10558            .unwrap();
10559        }
10560        let worktrees = dir.join("wt");
10561        (
10562            opts,
10563            Queue::at(dir.join("queue")),
10564            home.join("daemon.json"),
10565            home,
10566            worktrees,
10567        )
10568    }
10569
10570    #[tokio::test]
10571    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
10572        let dir = tempfile::tempdir().unwrap();
10573        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10574        let cfg = Config::default();
10575        start_service(
10576            &home,
10577            &opts,
10578            &queue,
10579            &worktrees,
10580            "housekeeping",
10581            Some(&cfg),
10582            true,
10583        )
10584        .await
10585        .unwrap();
10586        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
10587        let read = |path: &Path| -> serde_json::Value {
10588            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
10589        };
10590        assert_eq!(read(&receipt)["detail"], "cadence not due");
10591        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
10592        start_service(
10593            &home,
10594            &opts,
10595            &queue,
10596            &worktrees,
10597            "housekeeping",
10598            Some(&cfg),
10599            true,
10600        )
10601        .await
10602        .unwrap();
10603        assert_eq!(
10604            read(&receipt)["detail"],
10605            "active work or runnable task queue"
10606        );
10607        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
10608        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
10609        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
10610        start_service(
10611            &home,
10612            &opts,
10613            &queue,
10614            &worktrees,
10615            "disk-pressure",
10616            Some(&cfg),
10617            false,
10618        )
10619        .await
10620        .unwrap();
10621        assert_eq!(
10622            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
10623            "no active work; idle housekeeping owns scan"
10624        );
10625        assert!(crate::worker::active(&home).unwrap().is_empty());
10626    }
10627
10628    #[test]
10629    fn a_stop_is_idempotent_and_once_set_stays_set() {
10630        let stop = Stop::new();
10631        assert!(!stop.stopped());
10632
10633        stop.stop();
10634        assert!(stop.stopped());
10635        stop.stop();
10636        assert!(stop.stopped(), "a second stop is not a toggle");
10637
10638        let shared = stop.clone();
10639        assert!(
10640            shared.stopped(),
10641            "a clone is the same stop; that is how the loop and its caller share one"
10642        );
10643    }
10644
10645    #[tokio::test]
10646    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10647        for operation in ["conductor", "maintenance", "housekeeping"] {
10648            let dir = tempfile::tempdir().unwrap();
10649            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10650            opts.once = true;
10651            opts.poll = Duration::from_millis(1);
10652            let mut task = task();
10653            task.runs.push("fixture-run".into());
10654            queue.put(&mut task).unwrap();
10655            let claim = queue.claim(&task.id).unwrap();
10656
10657            // Model a live service holding the task's claim across the
10658            // scheduler's dispatch scan. No real subprocess or timed race.
10659            let directory = home.join("workers/jobs/abcdef");
10660            std::fs::create_dir_all(&directory).unwrap();
10661            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10662            crate::pr_head::try_lock_file(&lease).unwrap();
10663            let mut job = crate::worker::Job {
10664                id: "abcdef".into(),
10665                sequence: 1,
10666                kind: "daemon-service".into(),
10667                key: format!("service:daemon-{operation}"),
10668                payload: serde_json::Value::Null,
10669                generation: "fixture".into(),
10670                version: None,
10671                status: crate::worker::Status::Running,
10672                result: None,
10673                pid: Some(std::process::id()),
10674                created_at: Timestamp::now().as_second() as u64,
10675                finished_at: None,
10676            };
10677            let record = directory.join("job.json");
10678            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10679
10680            let status = Arc::new(Mutex::new(Status::new()));
10681            let stop = Stop::new();
10682            let mut drain = Box::pin(poll(
10683                &opts,
10684                &queue,
10685                &status,
10686                &home,
10687                &worktrees,
10688                &stop,
10689                DispatchLimits {
10690                    max_concurrent: 1,
10691                    pause_for_interrupts: false,
10692                    recovery_cfg: None,
10693                },
10694            ));
10695            std::future::poll_fn(|cx| {
10696                use std::future::Future;
10697                assert!(
10698                    drain.as_mut().poll(cx).is_pending(),
10699                    "--once must wait for {operation} to release its queue claim"
10700                );
10701                std::task::Poll::Ready(())
10702            })
10703            .await;
10704            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10705
10706            // An answer arrives while the service still owns the claim. A
10707            // fresh scheduling pass must apply it before declaring idle.
10708            let questions = Questions::at(home.join("questions"));
10709            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10710            questions.put(&mut q).unwrap();
10711            drop(claim);
10712            // Model services that took longer than their cadence, without a
10713            // wall-clock sleep. The final scans must not respawn them even
10714            // though their receipts now permit another periodic invocation.
10715            let expired =
10716                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10717            for service in [operation, "housekeeping"] {
10718                std::fs::write(
10719                    home.join("service-ticks").join(format!("daemon-{service}")),
10720                    &expired,
10721                )
10722                .unwrap();
10723            }
10724            job.status = crate::worker::Status::Finished;
10725            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10726            drop(lease);
10727            tokio::time::timeout(Duration::from_secs(2), drain)
10728                .await
10729                .expect("the settled service must allow the drain to finish")
10730                .unwrap();
10731            let after = queue.get(&task.id).unwrap();
10732            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10733            assert!(after.action_applied(&q.id));
10734            for service in [operation, "housekeeping"] {
10735                assert_eq!(
10736                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10737                        .unwrap(),
10738                    expired,
10739                    "the final once rescan must not restart {service}"
10740                );
10741            }
10742        }
10743    }
10744
10745    #[test]
10746    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10747        let stop = Stop::new();
10748        stop.busy.store(1, Ordering::SeqCst);
10749        assert!(
10750            !stop.finishing(),
10751            "a busy loop nobody has asked to stop is just running"
10752        );
10753
10754        stop.stop();
10755        assert!(
10756            stop.finishing(),
10757            "a stop asked for mid-run has not landed until the run is settled"
10758        );
10759
10760        stop.busy.store(0, Ordering::SeqCst);
10761        assert!(
10762            !stop.finishing(),
10763            "once the run is settled the stop has landed and there is nothing to finish"
10764        );
10765    }
10766
10767    #[test]
10768    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10769        let stop = Stop::new();
10770        stop.busy.store(2, Ordering::SeqCst);
10771        stop.stop();
10772        assert!(stop.finishing(), "two runs still in flight");
10773
10774        stop.busy.store(1, Ordering::SeqCst);
10775        assert!(
10776            stop.finishing(),
10777            "one run finished, but a sibling is still working"
10778        );
10779
10780        stop.busy.store(0, Ordering::SeqCst);
10781        assert!(
10782            !stop.finishing(),
10783            "the last run out is what actually lands the stop"
10784        );
10785    }
10786
10787    #[tokio::test]
10788    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10789        let dir = tempfile::tempdir().unwrap();
10790        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10791        let stop = Stop::new();
10792        stop.stop();
10793
10794        let began = std::time::Instant::now();
10795        tokio::time::timeout(
10796            Duration::from_secs(2),
10797            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10798        )
10799        .await
10800        .expect("a stopped loop must return, not sit out its poll interval")
10801        .expect("the loop's own setup and teardown must not fail");
10802        assert!(
10803            began.elapsed() < opts.poll,
10804            "returned only after {:?}, which is a poll interval, not a stop",
10805            began.elapsed()
10806        );
10807    }
10808
10809    #[tokio::test]
10810    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10811        let dir = tempfile::tempdir().unwrap();
10812        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10813        let stop = Stop::new();
10814
10815        // Asked for after the loop is already parked on its empty queue, which
10816        // is the case an operator tapping stop on a phone actually hits.
10817        let asker = {
10818            let stop = stop.clone();
10819            tokio::spawn(async move {
10820                tokio::time::sleep(Duration::from_millis(20)).await;
10821                stop.stop();
10822            })
10823        };
10824
10825        let began = std::time::Instant::now();
10826        tokio::time::timeout(
10827            Duration::from_secs(2),
10828            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10829        )
10830        .await
10831        .expect("a stop asked for while idle must wake the wait")
10832        .expect("the loop's own setup and teardown must not fail");
10833        asker.await.unwrap();
10834        assert!(
10835            began.elapsed() < opts.poll,
10836            "returned only after {:?}, so the stop waited on the sleep",
10837            began.elapsed()
10838        );
10839    }
10840
10841    #[tokio::test]
10842    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10843        let dir = tempfile::tempdir().unwrap();
10844        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10845        let stop = Stop::new();
10846        stop.stop();
10847
10848        tokio::time::timeout(
10849            Duration::from_secs(2),
10850            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10851        )
10852        .await
10853        .expect("a stopped loop must return")
10854        .expect("the loop's own setup and teardown must not fail");
10855
10856        assert!(
10857            home.is_dir(),
10858            "the loop did publish a status file, so its removal is the teardown and not an absence"
10859        );
10860        assert!(
10861            !status_file.exists(),
10862            "a stopped loop clears its status file"
10863        );
10864        assert!(
10865            read_status(&home).is_none(),
10866            "a reader must see no daemon at all, not a heartbeat that merely stopped"
10867        );
10868    }
10869
10870    #[tokio::test]
10871    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10872        let dir = tempfile::tempdir().unwrap();
10873        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10874
10875        let mut settled = RunState::new(
10876            dir.path().join("repo"),
10877            "main".to_owned(),
10878            "abc1234".to_owned(),
10879            "fixture".to_owned(),
10880            Config::default(),
10881        );
10882        settled.status = RunStatus::Ready;
10883        let run_dir = home.join("runs").join(&settled.id);
10884        std::fs::create_dir_all(&run_dir).unwrap();
10885        std::fs::write(
10886            run_dir.join("run.json"),
10887            serde_json::to_string_pretty(&settled).unwrap(),
10888        )
10889        .unwrap();
10890        let questions = Questions::at(home.join("questions"));
10891        let mut question = ask::Question::new(
10892            settled.id.clone(),
10893            "review".to_owned(),
10894            "reviewer-1".to_owned(),
10895            "Continue?".to_owned(),
10896            String::new(),
10897            Vec::new(),
10898        );
10899        questions.put(&mut question).unwrap();
10900
10901        run_service_worker(
10902            &home,
10903            serde_json::to_value(ServiceWorker {
10904                opts,
10905                queue: queue.root().to_path_buf(),
10906                worktrees_root: worktrees,
10907                operation: "housekeeping".to_owned(),
10908            })
10909            .unwrap(),
10910        )
10911        .await
10912        .unwrap();
10913
10914        assert_eq!(
10915            questions.get(&question.id).unwrap().status,
10916            ask::QuestionStatus::Abandoned,
10917            "the independent housekeeping worker settles ended-run questions"
10918        );
10919    }
10920
10921    #[test]
10922    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10923        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10924
10925        assert!(
10926            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10927            "never checked before: due at once"
10928        );
10929
10930        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10931        assert!(
10932            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10933            "well inside the interval: not due yet"
10934        );
10935
10936        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10937        assert!(
10938            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10939            "exactly at the edge: not yet due, same convention as `clean::due`"
10940        );
10941
10942        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10943        assert!(
10944            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10945            "past the interval: due again"
10946        );
10947    }
10948
10949    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
10950    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
10951    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
10952    /// and the congestion test below both need, and must not drift apart.
10953    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10954        let config = dir.join("magi.toml");
10955        // A literal (single-quoted) TOML string, not a basic one: the cache
10956        // path is a Windows path full of backslashes, and a basic string
10957        // would have TOML try to interpret `\U` (from `\Users\...`) as a
10958        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
10959        // `{{ vars.cache }}` rendering documents.
10960        std::fs::write(
10961            &config,
10962            format!(
10963                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10964                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10965                cache_dir.display()
10966            ),
10967        )
10968        .unwrap();
10969        Opts {
10970            config: Some(config),
10971            repo: dir.join("repo"),
10972            ..Opts::default()
10973        }
10974    }
10975
10976    #[tokio::test]
10977    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10978        let dir = tempfile::tempdir().unwrap();
10979        let home = dir.path().join("home");
10980        let cache_dir = dir.path().join("cache");
10981        std::fs::create_dir_all(&cache_dir).unwrap();
10982        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10983        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10984
10985        // Nobody has asked this daemon to stop, which is the ordinary case;
10986        // the skip that a stop buys is asserted by its own test below.
10987        let running = Stop::new();
10988        let mut last_checked = None;
10989        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10990        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10991            .await;
10992        assert_eq!(
10993            crate::disk::dir_size(&cache_dir),
10994            0,
10995            "over the cap on the first check ever: pruned at once, no idle queue required"
10996        );
10997        assert_eq!(last_checked, Some(t0));
10998
10999        // A fresh oversized file lands, but the next check is not due yet.
11000        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
11001        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
11002        maybe_prune_cache_between_runs(
11003            &opts.repo,
11004            &opts,
11005            &home,
11006            &running,
11007            &mut last_checked,
11008            too_soon,
11009        )
11010        .await;
11011        assert_eq!(
11012            crate::disk::dir_size(&cache_dir),
11013            10,
11014            "too soon since the last check: left alone rather than rescanned every call"
11015        );
11016        assert_eq!(
11017            last_checked,
11018            Some(t0),
11019            "an idle check does not reset the clock"
11020        );
11021
11022        // Once the interval elapses, the same oversized cache is caught again.
11023        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11024        maybe_prune_cache_between_runs(
11025            &opts.repo,
11026            &opts,
11027            &home,
11028            &running,
11029            &mut last_checked,
11030            due_again,
11031        )
11032        .await;
11033        assert_eq!(
11034            crate::disk::dir_size(&cache_dir),
11035            0,
11036            "due again: pruned back under the cap"
11037        );
11038    }
11039
11040    /// A stop must not queue behind housekeeping. The prune below is a
11041    /// synchronous walk of the whole cache with no await point in it, so a
11042    /// loop that entered it could not get back to its own `stopped()` test
11043    /// until the walk finished - and because no run is in flight at this
11044    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
11045    /// the stop had already landed. The idle branch has always made this same
11046    /// check before reaching `janitor`; the between-runs path makes it too.
11047    #[tokio::test]
11048    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
11049        let dir = tempfile::tempdir().unwrap();
11050        let home = dir.path().join("home");
11051        let cache_dir = dir.path().join("cache");
11052        std::fs::create_dir_all(&cache_dir).unwrap();
11053        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11054        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11055
11056        let stop = Stop::new();
11057        stop.stop();
11058        assert!(
11059            !stop.finishing(),
11060            "no run is in flight at a between-runs boundary, so nothing else \
11061             would tell the operator this stop had not taken effect yet"
11062        );
11063
11064        let mut last_checked = None;
11065        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11066        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
11067            .await;
11068        assert_eq!(
11069            crate::disk::dir_size(&cache_dir),
11070            10,
11071            "over its cap, and due for the first check ever, but a stop outranks \
11072             it: the cap is a standing policy the next start measures again"
11073        );
11074        assert_eq!(
11075            last_checked, None,
11076            "a check that never happened must not claim the interval"
11077        );
11078    }
11079
11080    /// A backlog must not starve cache pruning. The finite cache worker runs
11081    /// independently of queue drain and must not consume any task attempts.
11082    #[tokio::test]
11083    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
11084        let dir = tempfile::tempdir().unwrap();
11085        let cache_dir = dir.path().join("cache");
11086        std::fs::create_dir_all(&cache_dir).unwrap();
11087        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
11088
11089        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
11090        opts.poll = Duration::from_millis(20);
11091        opts.max_attempts = 1_000;
11092
11093        let queue = Queue::at(dir.path().join("queue"));
11094        for i in 0..128 {
11095            let mut task = Task::new(
11096                format!("queued work {i}"),
11097                format!("queued work {i}"),
11098                opts.repo.clone(),
11099                Source::Human,
11100            );
11101            queue.put(&mut task).unwrap();
11102        }
11103
11104        let home = dir.path().join("home");
11105        let worktrees = dir.path().join("wt");
11106        run_service_worker(
11107            &home,
11108            serde_json::to_value(ServiceWorker {
11109                opts,
11110                queue: queue.root().to_path_buf(),
11111                worktrees_root: worktrees,
11112                operation: "cache".to_owned(),
11113            })
11114            .unwrap(),
11115        )
11116        .await
11117        .unwrap();
11118        let after = queue.list();
11119        assert_eq!(after.len(), 128);
11120        assert!(
11121            after
11122                .iter()
11123                .all(|task| task.status.runnable() && task.attempts == 0)
11124        );
11125
11126        assert_eq!(
11127            crate::disk::dir_size(&cache_dir),
11128            0,
11129            "an oversized cache must not be left to grow unboundedly just because the \
11130             queue kept the loop busy the whole time"
11131        );
11132    }
11133
11134    #[test]
11135    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
11136        let dir = tempfile::tempdir().unwrap();
11137        let queue = Queue::at(dir.path().join("queue"));
11138        let questions = Questions::at(dir.path().join("questions"));
11139        let mut task = task();
11140        queue.put(&mut task).unwrap();
11141
11142        let mut task_question = ask::Question::new(
11143            task.id.clone(),
11144            crate::conduct::NODE.to_owned(),
11145            "conduct".to_owned(),
11146            "Which backend?".to_owned(),
11147            String::new(),
11148            Vec::new(),
11149        );
11150        questions.put(&mut task_question).unwrap();
11151        task.block(vec![task_question.id.clone()], None);
11152        queue.put(&mut task).unwrap();
11153
11154        let mut run_question = ask::Question::new(
11155            "20260101-000000-run1".to_owned(),
11156            "review".to_owned(),
11157            "reviewer-1".to_owned(),
11158            "Run question".to_owned(),
11159            String::new(),
11160            Vec::new(),
11161        );
11162        questions.put(&mut run_question).unwrap();
11163
11164        // A question from another node whose `run` happens to equal this
11165        // task's id — the same field, filled in for an unrelated reason. Only
11166        // `crate::conduct::NODE` questions use `run` as a task id; this one
11167        // must never be touched by this reconciliation, even after release.
11168        let mut coincidental = ask::Question::new(
11169            task.id.clone(),
11170            "review".to_owned(),
11171            "reviewer-1".to_owned(),
11172            "Unrelated review question".to_owned(),
11173            String::new(),
11174            Vec::new(),
11175        );
11176        questions.put(&mut coincidental).unwrap();
11177
11178        reconcile_task_questions(&queue, &questions);
11179        assert!(questions.get(&task_question.id).unwrap().status.open());
11180        assert!(questions.get(&run_question.id).unwrap().status.open());
11181        assert!(questions.get(&coincidental.id).unwrap().status.open());
11182
11183        task.release();
11184        queue.put(&mut task).unwrap();
11185        reconcile_task_questions(&queue, &questions);
11186        assert_eq!(
11187            questions.get(&task_question.id).unwrap().status,
11188            ask::QuestionStatus::Abandoned
11189        );
11190        assert!(
11191            questions.get(&run_question.id).unwrap().status.open(),
11192            "run questions remain the run janitor's responsibility"
11193        );
11194        assert!(
11195            questions.get(&coincidental.id).unwrap().status.open(),
11196            "a non-conductor question must not be abandoned just because its \
11197             run id coincides with a task id"
11198        );
11199    }
11200
11201    #[test]
11202    fn a_freshly_started_running_task_is_never_stalled() {
11203        let dir = tempfile::tempdir().unwrap();
11204        let mut t = task();
11205        t.start("run-1".to_owned());
11206        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
11207        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
11208        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
11209    }
11210
11211    #[test]
11212    fn a_long_running_task_with_no_live_daemon_is_stalled() {
11213        let dir = tempfile::tempdir().unwrap();
11214        let mut t = task();
11215        t.start("run-1".to_owned());
11216        t.updated_at = Timestamp::now()
11217            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
11218        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
11219        assert_eq!(
11220            stalled_tasks(
11221                &Queue::at(dir.path().join("q")),
11222                dir.path(),
11223                Timestamp::now()
11224            )
11225            .len(),
11226            0,
11227            "the task was never written to this queue"
11228        );
11229    }
11230
11231    #[test]
11232    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
11233        let dir = tempfile::tempdir().unwrap();
11234        let mut t = task();
11235        t.id = "20260903-080340-0167".to_owned();
11236        t.start("20260903-080619-01c2".to_owned());
11237        t.updated_at = Timestamp::now()
11238            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
11239
11240        let mut status = Status::new();
11241        status.current = vec![Current {
11242            worker: None,
11243            task: t.id.clone(),
11244            run: "20260903-080619-01c2".to_owned(),
11245        }];
11246        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11247
11248        assert!(
11249            !is_stalled(&t, dir.path(), Timestamp::now()),
11250            "a live daemon's own heartbeat rules out stalled, however long the task has run"
11251        );
11252    }
11253
11254    /// Rewrite a task's `updated_at` on disk directly, bypassing
11255    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
11256    /// a fixture look like it has genuinely been `running` for a while.
11257    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
11258        let path = queue.path_of(id);
11259        let body = std::fs::read_to_string(&path).unwrap();
11260        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
11261        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
11262        v["updated_at"] = serde_json::Value::String(old.to_string());
11263        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
11264    }
11265
11266    #[test]
11267    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
11268        // The realistic `poll()` ordering, not `is_stalled` in isolation:
11269        // `reclaim_orphaned_running` runs first, on every poll, and settles
11270        // any `running` task whose claim it can actually take. For most
11271        // crashes that is immediate - a dead pid is proof enough for
11272        // `sweep_stale_claims` to drop the lock the same tick, and the very
11273        // next claim attempt succeeds. But a lock whose pid cannot be parsed
11274        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
11275        // `sweep_stale_claims`'s own doc), so the lock - and the claim
11276        // failure behind it - can legitimately outlive many polls. This is
11277        // exactly the gap `stalled_tasks` exists to surface well before that
11278        // six-hour sweep would: reclaim leaves the task `running`, and it
11279        // must still reach the conductor as stalled.
11280        let dir = tempfile::tempdir().unwrap();
11281        let queue = Queue::at(dir.path().join("queue"));
11282        let home = dir.path().join("home");
11283
11284        let mut t = task();
11285        t.id = "20260101-000001-lock".to_owned();
11286        t.start("run-1".to_owned());
11287        queue.put(&mut t).unwrap();
11288        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
11289        std::fs::write(
11290            dir.path().join("queue").join(format!("{}.lock", t.id)),
11291            "not a pid",
11292        )
11293        .unwrap();
11294
11295        let now = Timestamp::now();
11296        assert!(
11297            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
11298            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
11299             and reclaim must leave the task alone"
11300        );
11301        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
11302
11303        let stalled = stalled_tasks(&queue, &home, now);
11304        assert_eq!(
11305            stalled.len(),
11306            1,
11307            "reclaim's inability to claim it yet must not hide it from the conductor"
11308        );
11309        assert_eq!(stalled[0].id, t.id);
11310    }
11311
11312    #[test]
11313    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
11314        let dir = tempfile::tempdir().unwrap();
11315        crate::run::set_home(dir.path().join("run-home"));
11316        let queue = Queue::at(dir.path().join("queue"));
11317        let home = dir.path().join("home");
11318        let questions = Questions::at(dir.path().join("questions"));
11319
11320        let mut t = task();
11321        t.id = "20260101-000003-dead".to_owned();
11322        t.start("missing-run".to_owned());
11323        queue.put(&mut t).unwrap();
11324        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
11325
11326        // This is the real poll ordering: retain the deterministic stalled
11327        // input before a claim proves the owner is gone and reclaims it.
11328        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11329        assert_eq!(
11330            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
11331            [&t.id]
11332        );
11333        assert_eq!(
11334            reclaim_orphaned_running(&queue, 2, &Default::default()),
11335            [t.id.clone()]
11336        );
11337        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11338
11339        // Reclaim drops its guard before conductor decisions are applied, so
11340        // the decision for the captured stalled input has a real write path.
11341        crate::conduct::apply(
11342            &queue,
11343            &questions,
11344            &crate::conduct::Verdict {
11345                decisions: vec![crate::conduct::Decision {
11346                    id: t.id.clone(),
11347                    recovery: Some(crate::conduct::Recovery::Requeue),
11348                    ..crate::conduct::Decision::default()
11349                }],
11350            },
11351        )
11352        .unwrap();
11353        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11354    }
11355
11356    #[test]
11357    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
11358        let dir = tempfile::tempdir().unwrap();
11359        let queue = Queue::at(dir.path().join("queue"));
11360        let home = dir.path().join("home");
11361
11362        let mut fresh = task();
11363        fresh.id = "20260101-000001-aaaa".to_owned();
11364        fresh.start("run-1".to_owned());
11365        queue.put(&mut fresh).unwrap();
11366
11367        let mut old = task();
11368        old.id = "20260101-000002-bbbb".to_owned();
11369        old.start("run-2".to_owned());
11370        queue.put(&mut old).unwrap();
11371        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
11372
11373        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11374        assert_eq!(stalled.len(), 1);
11375        assert_eq!(stalled[0].id, old.id);
11376    }
11377
11378    #[test]
11379    fn queued_and_finished_task_views_partition_by_status() {
11380        let dir = tempfile::tempdir().unwrap();
11381        let queue = Queue::at(dir.path().join("queue"));
11382
11383        let mut queued = task();
11384        queued.id = "20260101-000001-aaaa".to_owned();
11385        queue.put(&mut queued).unwrap();
11386
11387        let mut failed = task();
11388        failed.id = "20260101-000002-bbbb".to_owned();
11389        failed.start("run-1".to_owned());
11390        failed.fail("gate red", 5);
11391        queue.put(&mut failed).unwrap();
11392
11393        let mut held = task();
11394        held.id = "20260101-000003-cccc".to_owned();
11395        held.hold_machine(None);
11396        queue.put(&mut held).unwrap();
11397
11398        let mut running = task();
11399        running.id = "20260101-000004-dddd".to_owned();
11400        running.start("run-2".to_owned());
11401        queue.put(&mut running).unwrap();
11402
11403        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
11404        assert_eq!(queued_ids, [queued.id.clone()]);
11405
11406        let mut finished_ids: Vec<String> =
11407            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
11408        finished_ids.sort_unstable();
11409        let mut want = vec![failed.id.clone(), held.id.clone()];
11410        want.sort_unstable();
11411        assert_eq!(finished_ids, want);
11412    }
11413
11414    #[test]
11415    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
11416        for short in [false, true] {
11417            let dir = tempfile::tempdir().unwrap();
11418            let queue = Queue::at(dir.path().join("queue"));
11419            let questions = ask::Questions::at(dir.path().join("questions"));
11420            let mut running = task();
11421            running.id = "20261013-192213-feb2".into();
11422            running.start("existing-run".into());
11423            queue.put(&mut running).unwrap();
11424            let mut middle = task();
11425            middle.id = "20261013-193611-ca5b".into();
11426            middle.block(
11427                vec![if short {
11428                    "feb2".into()
11429                } else {
11430                    running.id.clone()
11431                }],
11432                None,
11433            );
11434            queue.put(&mut middle).unwrap();
11435            let mut waiting = task();
11436            waiting.id = "20261013-202849-ee37".into();
11437            waiting.block(
11438                vec![if short {
11439                    "ca5b".into()
11440                } else {
11441                    middle.id.clone()
11442                }],
11443                Some("wait for implementation".into()),
11444            );
11445            queue.put(&mut waiting).unwrap();
11446            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
11447            let inv = crate::blockers::Inventory::load(&queue, &questions);
11448            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
11449            assert!(inv.stuck().is_empty());
11450            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11451            assert!(report.quarantined.is_empty());
11452            assert!(report.asked.is_empty());
11453            resolve_blockers(&queue, &questions);
11454            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11455            assert!(questions.list().is_empty());
11456            // Finishing the transitive prerequisite alone does not satisfy
11457            // the task's direct dependency.
11458            running.succeed();
11459            queue.put(&mut running).unwrap();
11460            resolve_blockers(&queue, &questions);
11461            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
11462            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11463            middle = queue.get(&middle.id).unwrap();
11464            middle.succeed();
11465            queue.put(&mut middle).unwrap();
11466            resolve_blockers(&queue, &questions);
11467            let after = queue.get(&waiting.id).unwrap();
11468            assert_eq!(after.status, TaskStatus::Queued);
11469            assert!(after.blocked_by.is_empty());
11470            assert_eq!(after.instruction, waiting.instruction);
11471        }
11472    }
11473
11474    #[test]
11475    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
11476        for future_schema in [false, true] {
11477            let name = "20261013-193611-ca5b";
11478            let mut future = task();
11479            future.id = name.into();
11480            future.schema = crate::queue::SCHEMA + 1;
11481            let contents = if future_schema {
11482                serde_json::to_string(&future).unwrap()
11483            } else {
11484                "corrupt".into()
11485            };
11486            let dir = tempfile::tempdir().unwrap();
11487            let queue = Queue::at(dir.path().join("queue"));
11488            let questions = ask::Questions::at(dir.path().join("questions"));
11489            let mut waiting = task();
11490            waiting.id = "20261013-202849-ee37".into();
11491            waiting.block(vec!["ca5b".into()], None);
11492            queue.put(&mut waiting).unwrap();
11493            std::fs::write(queue.path_of(name), contents).unwrap();
11494            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
11495            assert!(
11496                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
11497            );
11498            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11499            assert!(report.asked.is_empty());
11500            resolve_blockers(&queue, &questions);
11501            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11502            assert!(questions.list().is_empty());
11503        }
11504        let dir = tempfile::tempdir().unwrap();
11505        let queue = Queue::at(dir.path().join("queue"));
11506        let questions = ask::Questions::at(dir.path().join("questions"));
11507        let mut waiting = task();
11508        waiting.id = "20261013-202849-ee37".into();
11509        waiting.block(vec!["ca5b".into()], None);
11510        queue.put(&mut waiting).unwrap();
11511        let mut done = task();
11512        done.id = "20261013-193611-ca5b".into();
11513        done.succeed();
11514        queue.put(&mut done).unwrap();
11515        // An unreadable second match must not disappear from uniqueness
11516        // checks just because Queue::list skips it.
11517        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
11518        assert!(queue.get("ca5b").is_err());
11519        assert_eq!(
11520            crate::queue::dependency(&queue, &questions, "ca5b"),
11521            crate::queue::Dependency::Ambiguous
11522        );
11523        resolve_blockers(&queue, &questions);
11524        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11525        assert!(report.asked.is_empty());
11526        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11527        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
11528    }
11529
11530    #[test]
11531    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
11532        for held in [false, true] {
11533            for question in [false, true] {
11534                for reference in ["ca5b", "20261013-193611-ca5b"] {
11535                    let dir = tempfile::tempdir().unwrap();
11536                    let queue = Queue::at(dir.path().join("queue"));
11537                    let questions = ask::Questions::at(dir.path().join("questions"));
11538                    let mut prerequisite = task();
11539                    prerequisite.id = "20261013-193611-ca5b".into();
11540                    prerequisite.start("existing-run".into());
11541                    queue.put(&mut prerequisite).unwrap();
11542                    let mut waiting = task();
11543                    waiting.id = "20261013-202849-ee37".into();
11544                    if held {
11545                        waiting.hold_machine(Some("waiting for separate consent".into()));
11546                    }
11547                    queue.put(&mut waiting).unwrap();
11548                    let reason = "Deleting saved data requires separate owner consent";
11549                    crate::conduct::apply(
11550                        &queue,
11551                        &questions,
11552                        &crate::conduct::Verdict {
11553                            decisions: vec![crate::conduct::Decision {
11554                                id: waiting.id.clone(),
11555                                blocked_by: vec![reference.into()],
11556                                question: question.then(|| "May the saved data be deleted?".into()),
11557                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11558                                reason: Some(reason.into()),
11559                                ..crate::conduct::Decision::default()
11560                            }],
11561                        },
11562                    )
11563                    .unwrap();
11564                    let before = queue.get(&waiting.id).unwrap();
11565                    if question {
11566                        assert_eq!(before.status, TaskStatus::Blocked);
11567                        let q = questions.get(&before.blocked_by[0]).unwrap();
11568                        assert_eq!(q.summary, "May the saved data be deleted?");
11569                        assert!(q.status.open());
11570                    } else {
11571                        assert_eq!(before.status, TaskStatus::Held);
11572                        let recorded_reason = before.hold_reason.as_deref().unwrap();
11573                        assert!(recorded_reason.starts_with(reason));
11574                        if held {
11575                            assert!(recorded_reason.contains("waiting for separate consent"));
11576                        }
11577                    }
11578                    prerequisite.succeed();
11579                    queue.put(&mut prerequisite).unwrap();
11580                    resolve_blockers(&queue, &questions);
11581                    let after = queue.get(&waiting.id).unwrap();
11582                    assert_eq!(after.status, before.status);
11583                    assert_eq!(after.blocked_by, before.blocked_by);
11584                    assert_eq!(after.hold_reason, before.hold_reason);
11585                    assert_eq!(after.instruction, waiting.instruction);
11586                    if question {
11587                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11588                    }
11589                    assert!(
11590                        queue.next_runnable().is_none(),
11591                        "dependency completion is not consent"
11592                    );
11593                }
11594            }
11595        }
11596    }
11597
11598    #[test]
11599    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11600        let dir = tempfile::tempdir().unwrap();
11601        let queue = Queue::at(dir.path().join("queue"));
11602        let questions = ask::Questions::at(dir.path().join("questions"));
11603
11604        let mut dep = task();
11605        dep.id = "20260101-000001-dep0".to_owned();
11606        dep.succeed();
11607        queue.put(&mut dep).unwrap();
11608
11609        let mut still_going = task();
11610        still_going.id = "20260101-000002-dep1".to_owned();
11611        queue.put(&mut still_going).unwrap();
11612
11613        let mut blocked = task();
11614        blocked.id = "20260101-000003-main".to_owned();
11615        blocked.block(
11616            vec![dep.id.clone(), still_going.id.clone()],
11617            Some("waits on both".to_owned()),
11618        );
11619        queue.put(&mut blocked).unwrap();
11620
11621        resolve_blockers(&queue, &questions);
11622
11623        let after = queue.get(&blocked.id).unwrap();
11624        assert_eq!(
11625            after.status,
11626            TaskStatus::Blocked,
11627            "one dependency is still outstanding"
11628        );
11629        assert_eq!(after.blocked_by, [still_going.id.clone()]);
11630    }
11631
11632    #[test]
11633    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11634        let dir = tempfile::tempdir().unwrap();
11635        let queue = Queue::at(dir.path().join("queue"));
11636        let questions = ask::Questions::at(dir.path().join("questions"));
11637
11638        let mut q = crate::ask::Question::new(
11639            "20260101-000001-main".to_owned(),
11640            crate::conduct::NODE.to_owned(),
11641            "conduct".to_owned(),
11642            "Which backend?".to_owned(),
11643            String::new(),
11644            Vec::new(),
11645        );
11646        questions.put(&mut q).unwrap();
11647        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11648            .unwrap();
11649        questions.put(&mut q).unwrap();
11650
11651        let mut blocked = task();
11652        blocked.id = "20260101-000001-main".to_owned();
11653        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11654        queue.put(&mut blocked).unwrap();
11655
11656        resolve_blockers(&queue, &questions);
11657
11658        let after = queue.get(&blocked.id).unwrap();
11659        assert_eq!(
11660            after.status,
11661            TaskStatus::Queued,
11662            "the only blocker resolved"
11663        );
11664        assert_eq!(after.answers.len(), 1);
11665        assert_eq!(after.answers[0].question, "Which backend?");
11666        assert_eq!(after.answers[0].answer, "SQLite");
11667
11668        // And the run this task starts next is told about it.
11669        let instruction = instruction_for(&after);
11670        assert!(instruction.contains("Which backend?"));
11671        assert!(instruction.contains("SQLite"));
11672    }
11673
11674    #[test]
11675    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11676        let dir = tempfile::tempdir().unwrap();
11677        let queue = Queue::at(dir.path().join("queue"));
11678        let questions = ask::Questions::at(dir.path().join("questions"));
11679
11680        let mut q = crate::ask::Question::new(
11681            "20260101-000001-main".to_owned(),
11682            crate::conduct::NODE.to_owned(),
11683            "conduct".to_owned(),
11684            "Is the setup done?".to_owned(),
11685            String::new(),
11686            Vec::new(),
11687        );
11688        q.abandon("no answer within 60s of asking");
11689        questions.put(&mut q).unwrap();
11690
11691        let mut blocked = task();
11692        blocked.id = "20260101-000001-main".to_owned();
11693        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11694        queue.put(&mut blocked).unwrap();
11695
11696        resolve_blockers(&queue, &questions);
11697
11698        let after = queue.get(&blocked.id).unwrap();
11699        assert_eq!(
11700            after.status,
11701            TaskStatus::Held,
11702            "never left blocked on nothing"
11703        );
11704        assert!(!after.operator_held(), "a machine hold, for triage");
11705        assert!(
11706            after
11707                .hold_reason
11708                .as_deref()
11709                .unwrap_or_default()
11710                .contains("went unanswered")
11711        );
11712    }
11713
11714    #[test]
11715    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11716        // Reproduces the reported bug (task 3958): a task held out of
11717        // attempts, blocked on a `crate::conduct` follow-up question, must
11718        // come back `held` once that question is answered - never `queued`,
11719        // whatever the answer said - or it silently re-enters the
11720        // competition queue with its attempts already exhausted.
11721        let dir = tempfile::tempdir().unwrap();
11722        let queue = Queue::at(dir.path().join("queue"));
11723        let questions = ask::Questions::at(dir.path().join("questions"));
11724
11725        let mut q = crate::ask::Question::new(
11726            "20260101-000001-main".to_owned(),
11727            crate::conduct::NODE.to_owned(),
11728            "conduct".to_owned(),
11729            "How should this be handled?".to_owned(),
11730            String::new(),
11731            Vec::new(),
11732        );
11733        questions.put(&mut q).unwrap();
11734        q.answer(crate::ask::Answer::Text(
11735            "leave it held, a human will look at it later".to_owned(),
11736        ))
11737        .unwrap();
11738        questions.put(&mut q).unwrap();
11739
11740        let mut held = task();
11741        held.id = "20260101-000001-main".to_owned();
11742        held.hold_machine(Some("out of attempts".to_owned()));
11743        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11744        queue.put(&mut held).unwrap();
11745
11746        resolve_blockers(&queue, &questions);
11747
11748        let after = queue.get(&held.id).unwrap();
11749        assert_eq!(after.status, TaskStatus::Held);
11750        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11751        assert_eq!(
11752            after.answers[0].answer,
11753            "leave it held, a human will look at it later"
11754        );
11755    }
11756
11757    #[test]
11758    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11759        let dir = tempfile::tempdir().unwrap();
11760        let queue = Queue::at(dir.path().join("queue"));
11761        let questions = ask::Questions::at(dir.path().join("questions"));
11762        let mut dep = task();
11763        dep.id = "20260101-000001-gone".to_owned();
11764        queue.put(&mut dep).unwrap();
11765        let mut blocked = task();
11766        blocked.id = "20260101-000003-main".to_owned();
11767        blocked.block(vec![dep.id.clone()], None);
11768        queue.put(&mut blocked).unwrap();
11769
11770        // Claimed, so `remove` cannot rewrite it and the resolver must.
11771        let claim = queue.claim(&blocked.id).unwrap();
11772        queue.remove(&dep.id, false, &questions).unwrap();
11773        drop(claim);
11774        resolve_blockers(&queue, &questions);
11775
11776        let after = queue.get(&blocked.id).unwrap();
11777        assert_eq!(after.status, TaskStatus::Queued);
11778        assert!(after.blocked_by.is_empty());
11779    }
11780
11781    #[test]
11782    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11783        // Reproduces the reported bug: a task blocked on a task id that was
11784        // removed (`magi task rm`, or deleted by hand) can never see that id
11785        // reach `Done`, so the ordinary per-id loop has nothing to notice and
11786        // would otherwise leave the task `blocked` forever with no way for an
11787        // operator to find out why.
11788        let dir = tempfile::tempdir().unwrap();
11789        let queue = Queue::at(dir.path().join("queue"));
11790        let questions = ask::Questions::at(dir.path().join("questions"));
11791
11792        let mut still_going = task();
11793        still_going.id = "20260101-000002-dep1".to_owned();
11794        queue.put(&mut still_going).unwrap();
11795
11796        let mut blocked = task();
11797        blocked.id = "20260101-000003-main".to_owned();
11798        blocked.block(
11799            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11800            Some("waits on both".to_owned()),
11801        );
11802        queue.put(&mut blocked).unwrap();
11803
11804        resolve_blockers(&queue, &questions);
11805
11806        let after = queue.get(&blocked.id).unwrap();
11807        assert_eq!(
11808            after.status,
11809            TaskStatus::Held,
11810            "a missing dependency must not leave the task blocked forever"
11811        );
11812        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11813        assert!(after.blocked_by.is_empty());
11814        let reason = after.hold_reason.as_deref().unwrap_or_default();
11815        assert!(
11816            reason.contains("20260101-000001-gone"),
11817            "the missing id must be named so an operator can tell what happened: {reason}"
11818        );
11819        assert!(
11820            reason.contains(&still_going.id),
11821            "the still-valid dependency must not silently vanish from the record: {reason}"
11822        );
11823    }
11824
11825    #[test]
11826    fn instruction_for_is_unchanged_without_any_answers() {
11827        let t = task();
11828        assert_eq!(instruction_for(&t), t.instruction);
11829    }
11830
11831    #[test]
11832    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11833        let dir = tempfile::tempdir().unwrap();
11834        let q = Queue::at(dir.path().join("queue"));
11835        let src = dir.path().join("shot.png");
11836        std::fs::write(&src, "x").unwrap();
11837        let mut t = task();
11838        q.attach(&mut t, &[src]).unwrap();
11839        let paths = task_attachments(&q, &t).unwrap();
11840        assert_eq!(paths.len(), 1);
11841        assert!(paths[0].is_absolute() && paths[0].is_file());
11842        std::fs::remove_file(&paths[0]).unwrap();
11843        let err = task_attachments(&q, &t).unwrap_err().to_string();
11844        assert!(err.contains("shot.png"), "{err}");
11845    }
11846
11847    #[tokio::test]
11848    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11849        let dir = tempfile::tempdir().unwrap();
11850        let queue_path = dir.path().join("queue");
11851        let queue = Queue::at(queue_path.clone());
11852        let mut t = task();
11853        t.source = Source::Agent {
11854            run: "originating-chat".into(),
11855            node: crate::queue::CHAT_NODE.into(),
11856        };
11857        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11858            stage: "config-fetch",
11859            target: "origin/main".into(),
11860        });
11861        record_config_failure(&mut t, &fetch);
11862        t.hold_machine(Some(format!("{fetch:#}")));
11863        let fetch_key = t.chat_notice_due().unwrap();
11864        t.chat_notices.push(fetch_key.clone());
11865        queue.put(&mut t).unwrap();
11866
11867        let queue = Queue::at(queue_path);
11868        let mut t = queue.get(&t.id).unwrap();
11869        let a = dir.path().join("a.toml");
11870        let b = dir.path().join("b.toml");
11871        for (path, text, new_cause) in [
11872            (&a, "[graph", true),
11873            (&a, "[verify", false),
11874            (&a, "[graph]\nimplementers = 'invalid-type'", true),
11875            (&b, "[graph]\nimplementers = 'invalid-type'", true),
11876        ] {
11877            t.release_operator("test", None);
11878            std::fs::write(path, text).unwrap();
11879            let error = Config::discover_fetched(dir.path(), Some(path))
11880                .await
11881                .unwrap_err();
11882            record_config_failure(&mut t, &error);
11883            t.hold_machine(Some(format!("{error:#}")));
11884            let due = t.chat_notice_due();
11885            assert_eq!(due.is_some(), new_cause, "{error:#}");
11886            if let Some(key) = due {
11887                assert_ne!(key, fetch_key);
11888                t.chat_notices.push(key);
11889            }
11890        }
11891        t.succeed();
11892        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11893    }
11894
11895    #[test]
11896    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11897        let dir = tempfile::tempdir().unwrap();
11898        let queue_path = dir.path().join("queue");
11899        let queue = Queue::at(queue_path.clone());
11900        let mut t = task();
11901        t.source = crate::queue::Source::Agent {
11902            run: "originating-chat".into(),
11903            node: crate::queue::CHAT_NODE.into(),
11904        };
11905        let a = dir.path().join("a.png");
11906        let b = dir.path().join("b.png");
11907        std::fs::write(&a, "a").unwrap();
11908        std::fs::write(&b, "b").unwrap();
11909        queue.attach(&mut t, &[a, b]).unwrap();
11910        let paths = task_attachments(&queue, &t).unwrap();
11911        for path in &paths {
11912            std::fs::remove_file(path).unwrap();
11913        }
11914        let missing = task_attachments(&queue, &t).unwrap_err();
11915        t.attempts += 1;
11916        let reason = missing.to_string();
11917        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11918        let first = t.chat_notice_due().expect("first attachment notice");
11919        t.chat_notices.push(first.clone());
11920        queue.put(&mut t).unwrap();
11921
11922        let queue = Queue::at(queue_path.clone());
11923        let mut t = queue.get(&t.id).unwrap();
11924        assert!(t.chat_notice_due().is_none(), "restart does not replay");
11925        t.release_operator("test", None);
11926        t.attempts += 1;
11927        let missing = task_attachments(&queue, &t).unwrap_err();
11928        t.fail_startup_target(
11929            "startup-attachments",
11930            missing.name,
11931            "same missing attachment with regenerated wording",
11932            1,
11933        );
11934        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11935
11936        std::fs::write(&paths[0], "restored").unwrap();
11937        t.release_operator("test", None);
11938        t.attempts += 1;
11939        let missing = task_attachments(&queue, &t).unwrap_err();
11940        let reason = missing.to_string();
11941        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11942        let second = t
11943            .chat_notice_due()
11944            .expect("different attachment must notify");
11945        assert_ne!(first, second);
11946        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11947    }
11948
11949    #[test]
11950    fn resumed_instruction_is_unchanged_without_any_answers() {
11951        let t = task();
11952        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11953    }
11954
11955    #[test]
11956    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11957        let mut t = task();
11958        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11959        // The run's own instruction on disk predates the answer: it is the
11960        // plain original text `Runner::start` saved before the operator was
11961        // ever asked anything.
11962        let old = t.instruction.clone();
11963
11964        let refreshed = resumed_instruction(&old, &t);
11965        assert!(refreshed.starts_with(&old), "the original text is kept");
11966        assert!(refreshed.contains("Which backend?"));
11967        assert!(refreshed.contains("SQLite"));
11968    }
11969
11970    #[test]
11971    fn resumed_instruction_keeps_an_original_answers_heading() {
11972        let mut t = task();
11973        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11974        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11975
11976        let refreshed = resumed_instruction(&t.instruction, &t);
11977
11978        assert!(
11979            refreshed.starts_with(&t.instruction),
11980            "an answers heading in the original instruction is not the appended block"
11981        );
11982        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11983        assert!(refreshed.contains("Which backend?"));
11984        assert!(refreshed.contains("SQLite"));
11985
11986        let repeated = resumed_instruction(&refreshed, &t);
11987        assert_eq!(
11988            repeated, refreshed,
11989            "only the final appended block is refreshed"
11990        );
11991    }
11992
11993    #[test]
11994    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11995        let mut t = task();
11996        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11997
11998        // A first resume appends the block; a second resume of the same run,
11999        // with no new answer in between, must reproduce exactly the same
12000        // text rather than appending the block a second time.
12001        let once = resumed_instruction(&t.instruction, &t);
12002        let twice = resumed_instruction(&once, &t);
12003        assert_eq!(once, twice);
12004        assert_eq!(once.matches("Which backend?").count(), 1);
12005
12006        // A later answer replaces the block wholesale rather than growing it.
12007        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
12008        let refreshed = resumed_instruction(&once, &t);
12009        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
12010        assert!(refreshed.contains("Which backend?"));
12011        assert!(refreshed.contains("Which cache?"));
12012    }
12013
12014    #[test]
12015    fn prepare_instruction_covers_all_three_starters() {
12016        let mut t = task();
12017        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12018
12019        // Start: a fresh run gets the task text plus every answer so far —
12020        // exactly `instruction_for`.
12021        assert_eq!(
12022            prepare_instruction(&Starter::Start, None, &t),
12023            Some(instruction_for(&t))
12024        );
12025
12026        // Resume: the run's prior instruction is refreshed with the answer,
12027        // not discarded and not left stale.
12028        let old = t.instruction.clone();
12029        assert_eq!(
12030            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
12031            Some(resumed_instruction(&old, &t))
12032        );
12033
12034        // Review: a review-only pass builds its own instruction from the
12035        // branch's history in `crate::graph`, with no task statement at all -
12036        // this boundary must leave it alone.
12037        assert_eq!(
12038            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
12039            None
12040        );
12041    }
12042
12043    #[test]
12044    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
12045        assert_eq!(
12046            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
12047            Starter::Review("magi/eba2/A".to_owned())
12048        );
12049    }
12050
12051    #[test]
12052    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
12053        assert_eq!(
12054            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
12055            Starter::Start,
12056            "a vanished review branch must not fall back to resuming the old run either"
12057        );
12058    }
12059
12060    #[test]
12061    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
12062        let mut t = task();
12063        t.start("old-run".to_owned());
12064        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
12065        t.release();
12066        let branch = t.review_branch.take();
12067        assert_eq!(
12068            choose_starter(branch.as_deref(), true, Some("old-run")),
12069            Starter::Review("magi/eba2/A".to_owned()),
12070            "a review wins over resuming the old run"
12071        );
12072    }
12073
12074    #[test]
12075    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
12076        assert_eq!(
12077            choose_starter(None, false, Some("some-run")),
12078            Starter::Resume("some-run".to_owned())
12079        );
12080        assert_eq!(choose_starter(None, false, None), Starter::Start);
12081    }
12082
12083    #[test]
12084    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
12085        let mut released = task();
12086        released.start("stalled-run".to_owned());
12087        released.requeue();
12088        let unfinished = (!released.fresh_start)
12089            .then(|| Some("stalled-run".to_owned()))
12090            .flatten();
12091        assert_eq!(
12092            choose_starter(None, false, unfinished.as_deref()),
12093            Starter::Start,
12094            "release keeps run history but must not resume it"
12095        );
12096        assert_eq!(released.runs, ["stalled-run"]);
12097    }
12098
12099    #[test]
12100    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
12101        let dir = tempfile::tempdir().unwrap();
12102        let queue = Queue::at(dir.path().join("queue"));
12103        let mut state = run_state(RunStatus::Blocked);
12104        state.merge_decision = Some(crate::merge_decision::Decision {
12105            question: "hold-inquiry".into(),
12106            target: crate::merge_decision::Target {
12107                pr: "https://example.test/pull/1".into(),
12108                head: "reviewed-head".into(),
12109                language: "en".into(),
12110            },
12111            choice: land::HOLD.into(),
12112            closed: false,
12113            replacement_run: None,
12114            replacement_pr: None,
12115        });
12116        let mut t = task();
12117        t.start(state.id.clone());
12118        settle_and_diagnose(
12119            &mut t,
12120            Verdict {
12121                status: RunStatus::Blocked,
12122                left_pr: true,
12123                quota_hit: false,
12124                parked: false,
12125                no_viable_candidates: false,
12126            },
12127            "held",
12128            2,
12129            &state,
12130        );
12131        queue.put(&mut t).unwrap();
12132        t.release_operator("chat", None);
12133        t.edit("revised".into(), "revised instruction".into())
12134            .unwrap();
12135        queue.put(&mut t).unwrap();
12136        drop(state);
12137        assert_eq!(
12138            queue
12139                .get(&t.id)
12140                .unwrap()
12141                .decision_effects
12142                .get("hold-inquiry"),
12143            Some(&format!("decision: {}", land::HOLD))
12144        );
12145    }
12146
12147    fn stopped_public_run(status: RunStatus) -> RunState {
12148        let mut state = run_state(status);
12149        state.driver_exited = true;
12150        state.config.graph.land = true;
12151        state.config.graph.review_rounds = 1;
12152        state.reviews = vec![review_round(1)];
12153        state.merge = Some(crate::run::MergeOutcome {
12154            mode: MergeMode::Pr,
12155            ok: false,
12156            detail: "landing stopped".into(),
12157            empty: false,
12158        });
12159        state.pr = Some(crate::run::PrRecord {
12160            url: "https://example.test/pull/1".into(),
12161            number: 1,
12162            state: "open".into(),
12163            checks: "red".into(),
12164            round: 1,
12165            rounds: 1,
12166            red_at_merge: Vec::new(),
12167        });
12168        state
12169    }
12170
12171    #[test]
12172    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
12173        for status in [RunStatus::Blocked, RunStatus::Gating] {
12174            let home = tempfile::tempdir().unwrap();
12175            let mut state = stopped_public_run(status);
12176            state.save_under(home.path()).unwrap();
12177            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
12178            assert!(!exhausted_review_budget(&state));
12179            let mut task = held_task_with(&state.id);
12180            task.release();
12181            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
12182            assert_eq!(
12183                choose_starter(None, false, unfinished.as_deref()),
12184                Starter::Resume(state.id.clone())
12185            );
12186            let question = action_question(&state.id, resume_action(&state.id));
12187            assert_eq!(
12188                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12189                    state.clone()
12190                )),
12191                ActionDecision::Resume(state.id.clone())
12192            );
12193            // The control-plane command uses this same preflight before pinning.
12194            assert_eq!(
12195                crate::resume::validate(home.path(), &state.id).unwrap().id,
12196                state.id
12197            );
12198            let queue = Queue::at(home.path().join("queue"));
12199            let mut controlled = Task::new(
12200                "resume land".into(),
12201                state.instruction.clone(),
12202                state.repo.clone(),
12203                Source::Agent {
12204                    run: "talk".into(),
12205                    node: crate::queue::CHAT_NODE.into(),
12206                },
12207            );
12208            controlled.runs.push(state.id.clone());
12209            controlled.hold_machine(Some("land stopped".into()));
12210            queue.put(&mut controlled).unwrap();
12211            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
12212            assert_eq!(resumed.status, TaskStatus::Queued);
12213            assert_eq!(
12214                resumed.resume_override.unwrap().pinned_run,
12215                Some(state.id.clone())
12216            );
12217            assert_eq!(resumed.attempts, 0);
12218        }
12219    }
12220
12221    #[test]
12222    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
12223        for review_rounds in [0, 1] {
12224            let home = tempfile::tempdir().unwrap();
12225            let mut state = run_state(RunStatus::Blocked);
12226            state.config.graph.review_rounds = review_rounds;
12227            if review_rounds > 0 {
12228                let mut review = review_round(1);
12229                review.clean = true;
12230                state.reviews = vec![review];
12231            }
12232            state.gate_ran = true;
12233            state.gate = vec![crate::run::CommandOutcome {
12234                command: "verify".into(),
12235                code: Some(1),
12236                output_tail: "gate failed after repair budget exhausted".into(),
12237                duration_ms: 0,
12238                resource_blocked: false,
12239            }];
12240            state.save_under(home.path()).unwrap();
12241            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
12242            assert!(exhausted_review_budget(&state));
12243            let mut task = held_task_with(&state.id);
12244            task.release();
12245            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
12246            let question = action_question(&state.id, resume_action(&state.id));
12247            assert_ne!(
12248                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12249                    state.clone()
12250                )),
12251                ActionDecision::Resume(state.id.clone())
12252            );
12253            let error = crate::resume::validate(home.path(), &state.id)
12254                .unwrap_err()
12255                .to_string();
12256            assert!(!error.contains("review budget exhausted"), "{error}");
12257            assert!(
12258                error.contains(if review_rounds == 0 {
12259                    "review is disabled"
12260                } else {
12261                    "gate already ran"
12262                }),
12263                "{error}"
12264            );
12265
12266            // An unexecuted gate still has work to do with or without reviews.
12267            state.gate_ran = false;
12268            state.gate.clear();
12269            assert!(!exhausted_review_budget(&state));
12270            assert_eq!(
12271                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
12272                Some(state.id)
12273            );
12274        }
12275    }
12276
12277    #[test]
12278    fn resource_blocked_verification_resumes_the_same_run() {
12279        for (kind, stage) in [
12280            ("cache", "clean"),
12281            ("coordination", "clean"),
12282            ("cache", "review-e2e"),
12283            ("coordination", "no-reviews"),
12284            ("coordination", "handoff"),
12285        ] {
12286            let home = tempfile::tempdir().unwrap();
12287            let mut state = run_state(RunStatus::Blocked);
12288            state.config.graph.review_rounds = 1;
12289            let mut review = review_round(1);
12290            review.clean = true;
12291            state.reviews = vec![review];
12292            if stage == "review-e2e" {
12293                let review = &mut state.reviews[0];
12294                review.clean = false;
12295                review.blocking = 1;
12296                review.e2e = vec![crate::run::CommandOutcome {
12297                    command: "verify".into(),
12298                    code: None,
12299                    output_tail: "resource wait expired".into(),
12300                    duration_ms: 0,
12301                    resource_blocked: true,
12302                }];
12303            } else if stage == "no-reviews" {
12304                state.config.graph.review_rounds = 0;
12305                state.reviews.clear();
12306            } else if stage == "handoff" {
12307                // A completed final verification can hand off to the gate
12308                // even when the review still carries contested findings.
12309                let review = &mut state.reviews[0];
12310                review.clean = false;
12311                review.blocking = 1;
12312                review.e2e = vec![crate::run::CommandOutcome {
12313                    command: "verify".into(),
12314                    code: Some(0),
12315                    output_tail: String::new(),
12316                    duration_ms: 0,
12317                    resource_blocked: false,
12318                }];
12319            }
12320            state.gate_ran = false;
12321            state.resource_block = Some(crate::run::ResourceBlock {
12322                cause: crate::run::ResourceBlockCause::Other,
12323                node: if stage == "review-e2e" {
12324                    "review"
12325                } else {
12326                    "gate"
12327                }
12328                .into(),
12329                kind: kind.into(),
12330                detail: "resource wait expired".into(),
12331                at: jiff::Timestamp::now(),
12332            });
12333            state.save_under(home.path()).unwrap();
12334            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
12335            assert!(!exhausted_review_budget(&state));
12336            let mut task = held_task_with(&state.id);
12337            task.release();
12338            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
12339            assert_eq!(
12340                choose_starter(None, false, unfinished.as_deref()),
12341                Starter::Resume(state.id.clone())
12342            );
12343            let question = action_question(&state.id, resume_action(&state.id));
12344            assert_eq!(
12345                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12346                    state.clone()
12347                )),
12348                ActionDecision::Resume(state.id.clone())
12349            );
12350            assert_eq!(
12351                crate::resume::validate(home.path(), &state.id).unwrap().id,
12352                state.id
12353            );
12354            let queue = Queue::at(home.path().join("queue"));
12355            let mut controlled = Task::new(
12356                "resume verification".into(),
12357                state.instruction.clone(),
12358                state.repo.clone(),
12359                Source::Agent {
12360                    run: "talk".into(),
12361                    node: crate::queue::CHAT_NODE.into(),
12362                },
12363            );
12364            controlled.runs.push(state.id.clone());
12365            controlled.hold_machine(Some("verification resource unavailable".into()));
12366            queue.put(&mut controlled).unwrap();
12367            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
12368            assert_eq!(resumed.status, TaskStatus::Queued);
12369            assert_eq!(
12370                resumed.resume_override.unwrap().pinned_run,
12371                Some(state.id.clone())
12372            );
12373            assert_eq!(resumed.attempts, 0);
12374
12375            // A genuinely unresolved final review still exhausts the budget.
12376            state.config.graph.review_rounds = 1;
12377            let mut unresolved = review_round(1);
12378            unresolved.blocking = 1;
12379            state.reviews = vec![unresolved];
12380            state.resource_block = None;
12381            state.save_under(home.path()).unwrap();
12382            assert!(exhausted_review_budget(&state));
12383            assert!(crate::resume::validate(home.path(), &state.id).is_err());
12384        }
12385    }
12386
12387    #[tokio::test]
12388    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
12389        if !crate::standalone_test(
12390            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
12391        ) {
12392            return;
12393        }
12394        let home = tempfile::tempdir().unwrap();
12395        let mut owner = stopped_public_run(RunStatus::Blocked);
12396        owner.save_under(home.path()).unwrap();
12397        let history = vec![owner.id.clone()];
12398        let repo = owner.repo.clone();
12399        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
12400        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
12401        let initial =
12402            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
12403        assert!(
12404            initial.is_pending(),
12405            "a busy record must not hold or resume the task"
12406        );
12407        owner.retired_to = Some("20260101-000001-bbbb".into());
12408        owner.save_under(home.path()).unwrap();
12409        drop(lock);
12410        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
12411            .await
12412            .expect("ownership lock released")
12413            .expect("read settled owner");
12414        assert!(
12415            result.is_none(),
12416            "the retired owner must not be resumed from a stale read"
12417        );
12418    }
12419
12420    #[tokio::test]
12421    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
12422        if !crate::standalone_test(
12423            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
12424        ) {
12425            return;
12426        }
12427        let home = tempfile::tempdir().unwrap();
12428        let mut owner = stopped_public_run(RunStatus::Blocked);
12429        let repo = tempfile::tempdir().unwrap();
12430        crate::git::git(repo.path(), &["init"]).await.unwrap();
12431        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
12432        owner.id = "20260101-000000-aaaa".into();
12433        owner.save_under(home.path()).unwrap();
12434        let mut successor = run_state(RunStatus::Blocked);
12435        successor.id = "20260101-000001-bbbb".into();
12436        successor.save_under(home.path()).unwrap();
12437        let runs = vec![owner.id.clone(), successor.id.clone()];
12438        assert_eq!(
12439            public_resume_owner(home.path(), &runs, &owner.repo)
12440                .await
12441                .unwrap()
12442                .unwrap()
12443                .id,
12444            owner.id
12445        );
12446        let subdir = owner.repo.join("nested");
12447        std::fs::create_dir(&subdir).unwrap();
12448        assert_eq!(
12449            public_resume_owner(home.path(), &runs, &subdir)
12450                .await
12451                .unwrap()
12452                .unwrap()
12453                .id,
12454            owner.id
12455        );
12456        #[cfg(unix)]
12457        {
12458            let alias = home.path().join("repo-alias");
12459            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
12460            assert_eq!(
12461                public_resume_owner(home.path(), &runs, &alias.join("nested"))
12462                    .await
12463                    .unwrap()
12464                    .unwrap()
12465                    .id,
12466                owner.id
12467            );
12468        }
12469        let different = tempfile::tempdir().unwrap();
12470        crate::git::git(different.path(), &["init"]).await.unwrap();
12471        assert!(
12472            public_resume_owner(home.path(), &runs, different.path())
12473                .await
12474                .is_err()
12475        );
12476        std::fs::remove_file(
12477            home.path()
12478                .join("runs")
12479                .join(&successor.id)
12480                .join("run.json"),
12481        )
12482        .unwrap();
12483        assert!(
12484            public_resume_owner(home.path(), &runs, &owner.repo)
12485                .await
12486                .is_err()
12487        );
12488    }
12489
12490    #[test]
12491    fn an_ordinary_release_keeps_a_resumable_run_available() {
12492        let mut released = task();
12493        released.start("stalled-run".to_owned());
12494        released.release();
12495        let unfinished = (!released.fresh_start)
12496            .then(|| Some("stalled-run".to_owned()))
12497            .flatten();
12498        assert_eq!(
12499            choose_starter(None, false, unfinished.as_deref()),
12500            Starter::Resume("stalled-run".to_owned()),
12501            "manual release must preserve the normal resume path"
12502        );
12503    }
12504
12505    #[test]
12506    fn resume_refusals_explain_admission_without_changing_task_or_run() {
12507        use crate::handover::{ResumeRefusal, resume_refusal_under};
12508        let home = tempfile::tempdir().unwrap();
12509        let mut exhausted = run_state(RunStatus::Blocked);
12510        exhausted.driver_exited = true;
12511        exhausted.config.graph.review_rounds = 3;
12512        exhausted.reviews = (1..=3).map(review_round).collect();
12513        for refusal in [
12514            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
12515            ResumeRefusal::Status(RunStatus::Ready),
12516            ResumeRefusal::Released("20261022-000000-aaaa".into()),
12517            ResumeRefusal::Retired("retirement-successor".into()),
12518            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
12519        ] {
12520            let mut state = exhausted.clone();
12521            let expected = match refusal {
12522                ResumeRefusal::Status(_) => {
12523                    state.status = RunStatus::Ready;
12524                    "status `ready`"
12525                }
12526                ResumeRefusal::Released(ref target) => {
12527                    state.released_to = Some(target.clone());
12528                    "execution was released"
12529                }
12530                ResumeRefusal::Retired(ref target) => {
12531                    state.retired_to = Some(target.clone());
12532                    "execution was retired"
12533                }
12534                ResumeRefusal::OwnershipTransferred(ref target) => {
12535                    state.pr_taken_over_by = Some(target.clone());
12536                    "PR ownership was transferred"
12537                }
12538                _ => "review budget exhausted (3/3 rounds used)",
12539            };
12540            assert_eq!(
12541                resume_refusal_under(&state, Some(home.path())),
12542                Some(refusal.clone())
12543            );
12544            assert_eq!(
12545                refusal.successor(),
12546                state
12547                    .released_to
12548                    .as_deref()
12549                    .or(state.retired_to.as_deref())
12550                    .or(state.pr_taken_over_by.as_deref())
12551            );
12552            state.save_under(home.path()).unwrap();
12553            let queue = Queue::at(home.path().join("queue"));
12554            let mut task = Task::new(
12555                "retained implementation".into(),
12556                state.instruction.clone(),
12557                state.repo.clone(),
12558                Source::Agent {
12559                    run: "talk".into(),
12560                    node: crate::queue::CHAT_NODE.into(),
12561                },
12562            );
12563            task.runs.push(state.id.clone());
12564            task.hold_machine(Some("stopped".into()));
12565            queue.put(&mut task).unwrap();
12566            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
12567            let before_run = serde_json::to_value(&state).unwrap();
12568            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
12569                .unwrap_err()
12570                .to_string();
12571            assert!(error.contains(expected), "{error}");
12572            assert!(!error.contains("only a stalled or blocked"), "{error}");
12573            if matches!(refusal, ResumeRefusal::Status(_)) {
12574                assert!(
12575                    error.contains("is final; there is nothing left to resume"),
12576                    "{error}"
12577                );
12578            }
12579            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
12580                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
12581                assert!(error.contains("review-only successor with a new review budget"));
12582                assert!(error.contains("does not resume this run"));
12583            }
12584            for target in [
12585                &state.released_to,
12586                &state.retired_to,
12587                &state.pr_taken_over_by,
12588            ]
12589            .into_iter()
12590            .flatten()
12591            {
12592                let short = if state.retired_to.as_ref() == Some(target) {
12593                    target.as_str()
12594                } else {
12595                    crate::run::short_of(target)
12596                };
12597                assert!(
12598                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
12599                    "{error}"
12600                );
12601                if short != target {
12602                    assert!(!error.contains(target), "full successor id leaked: {error}");
12603                }
12604            }
12605            assert_eq!(
12606                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12607                before_task
12608            );
12609            assert_eq!(
12610                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12611                    .unwrap(),
12612                before_run
12613            );
12614            let question = action_question(&state.id, resume_action(&state.id));
12615            for phrases in [&PHRASES_EN, &PHRASES_JA] {
12616                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
12617                    RunState::load_under(id, home.path())
12618                });
12619                let ActionDecision::Refuse(detail) = decision else {
12620                    panic!(
12621                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
12622                        state.id,
12623                        home.path().display()
12624                    );
12625                };
12626                assert!(detail.contains(expected), "{detail}");
12627            }
12628        }
12629        // Preserve predicate ordering, while keeping every recorded destination visible.
12630        exhausted.status = RunStatus::Ready;
12631        exhausted.released_to = Some("released".into());
12632        exhausted.retired_to = Some("retired".into());
12633        exhausted.pr_taken_over_by = Some("owner".into());
12634        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12635        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12636        let detail = reason.diagnostic(&exhausted);
12637        for target in ["released", "retired", "owner"] {
12638            assert!(detail.contains(&format!("magi show {target}")));
12639        }
12640    }
12641
12642    #[test]
12643    fn resume_action_ignores_question_checkpoints_in_another_home() {
12644        crate::run::pin_test_home();
12645        let home = tempfile::tempdir().unwrap();
12646        let mut state = run_state(RunStatus::Blocked);
12647        // The private directory reserves this fixture's identity even while
12648        // other tests write questions into the process-wide store.
12649        state.id = format!(
12650            "resume-context-{}",
12651            home.path().file_name().unwrap().to_str().unwrap()
12652        );
12653        state.driver_exited = true;
12654        state.config.graph.review_rounds = 1;
12655        state.reviews = vec![review_round(1)];
12656        state.save_under(home.path()).unwrap();
12657        let task = held_task_with(&state.id);
12658        let answer = action_question(&state.id, resume_action(&state.id));
12659        let mut checkpoint = approval_question(&state.id);
12660        let foreign = Questions::open();
12661        foreign.put(&mut checkpoint).unwrap();
12662        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
12663        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12664            RunState::load_under(id, home.path())
12665        });
12666        let matching: Vec<_> = foreign
12667            .list()
12668            .into_iter()
12669            .filter(|q| q.run == state.id && q.status.open())
12670            .collect();
12671        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
12672        assert!(
12673            matches!(decision, ActionDecision::Refuse(_)),
12674            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
12675            state.id,
12676            home.path().display(),
12677            crate::run::test_home().display()
12678        );
12679        assert_eq!(
12680            refusal,
12681            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
12682        );
12683        let local = Questions::at(home.path().join("questions"));
12684        for status in [
12685            ask::QuestionStatus::Open,
12686            ask::QuestionStatus::Answered,
12687            ask::QuestionStatus::Abandoned,
12688        ] {
12689            let mut question = checkpoint.clone();
12690            match status {
12691                ask::QuestionStatus::Open => {}
12692                ask::QuestionStatus::Answered => {
12693                    question
12694                        .answer(ask::Answer::Choice(question.choices[0].clone()))
12695                        .unwrap();
12696                }
12697                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
12698            }
12699            local.put(&mut question).unwrap();
12700            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12701                RunState::load_under(id, home.path())
12702            });
12703            if status.open() {
12704                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
12705            } else {
12706                assert!(
12707                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
12708                    "status={status:?}, decision={decision:?}"
12709                );
12710            }
12711        }
12712    }
12713
12714    #[test]
12715    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
12716        let home = tempfile::tempdir().unwrap();
12717        let mut state = run_state(RunStatus::Stalled);
12718        state.id = format!(
12719            "resume-driver-{}",
12720            home.path().file_name().unwrap().to_str().unwrap()
12721        );
12722        state.driver_claimed = Some(false);
12723        state.save_under(home.path()).unwrap();
12724        let task = held_task_with(&state.id);
12725        let question = action_question(&state.id, resume_action(&state.id));
12726        let decide = || {
12727            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
12728                RunState::load_under(id, home.path())
12729            })
12730        };
12731        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
12732        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
12733        assert_eq!(
12734            decide(),
12735            ActionDecision::Refuse("run already has a live driver".into())
12736        );
12737        drop(lease);
12738        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
12739    }
12740
12741    #[test]
12742    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12743        let home = tempfile::tempdir().unwrap();
12744        let mut state = run_state(RunStatus::Blocked);
12745        state.driver_exited = true;
12746        state.config.graph.review_rounds = 1;
12747        state.reviews = vec![review_round(1)];
12748        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12749        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12750            let mut saved = state.clone();
12751            match checkpoint {
12752                "publication" => saved.pr_publication_pending = true,
12753                "approval" => {
12754                    saved.land_approval = Some(crate::run::LandApproval {
12755                        question: "approval".into(),
12756                        head: "head".into(),
12757                    })
12758                }
12759                "armed" => saved.land_armed_head = Some("head".into()),
12760                "landing" => saved.status = RunStatus::Landing,
12761                _ => {
12762                    let mut question = ask::Question::new(
12763                        saved.id.clone(),
12764                        "review".into(),
12765                        "review-1".into(),
12766                        "continue?".into(),
12767                        String::new(),
12768                        vec!["continue".into()],
12769                    );
12770                    ask::Questions::at(home.path().join("questions"))
12771                        .put(&mut question)
12772                        .unwrap();
12773                }
12774            }
12775            saved.save_under(home.path()).unwrap();
12776            assert!(
12777                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12778                "{checkpoint}"
12779            );
12780            assert!(
12781                crate::resume::validate(home.path(), &saved.id).is_ok(),
12782                "{checkpoint}"
12783            );
12784        }
12785    }
12786
12787    #[test]
12788    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12789        let mut state = run_state(RunStatus::Blocked);
12790        state.config.graph.review_rounds = 3;
12791        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12792        assert!(exhausted_review_budget(&state));
12793
12794        // One round still unused: resuming can still ask a reviewer something.
12795        state.reviews.pop();
12796        assert!(!exhausted_review_budget(&state));
12797
12798        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
12799        // count: only a `Blocked` run re-enters the review loop on resume.
12800        let mut stalled = run_state(RunStatus::Stalled);
12801        stalled.config.graph.review_rounds = 1;
12802        stalled.reviews = vec![review_round(1)];
12803        assert!(!exhausted_review_budget(&stalled));
12804    }
12805
12806    fn review_round(round: usize) -> crate::run::ReviewRound {
12807        crate::run::ReviewRound {
12808            round,
12809            head: "deadbeef".to_owned(),
12810            verified_head: None,
12811            verified_at: None,
12812            reviews: Vec::new(),
12813            e2e: Vec::new(),
12814            verify_retried: false,
12815            e2e_deferred: false,
12816            e2e_defer_reason: None,
12817            fix: None,
12818            blocking: 0,
12819            answered: 1,
12820            expected: 1,
12821            clean: false,
12822            progressed: true,
12823            vote_split: false,
12824            reconsideration: Vec::new(),
12825            verdict: None,
12826        }
12827    }
12828
12829    #[test]
12830    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12831        let mut run = RunState::new(
12832            PathBuf::from("/repo"),
12833            "main".to_owned(),
12834            "abc1234def".to_owned(),
12835            "add retries".to_owned(),
12836            Config::default(),
12837        );
12838        run.status = RunStatus::Judging;
12839        run.parked = true;
12840        let mut task = Task::new(
12841            "add retries".to_owned(),
12842            "add retries".to_owned(),
12843            PathBuf::from("/repo"),
12844            crate::queue::Source::Human,
12845        );
12846        task.status = TaskStatus::Failed;
12847        task.runs = vec![run.id.clone()];
12848        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12849        assert!(with(&task, &run), "parked after judging is the case");
12850        let mut parked_task = task.clone();
12851        parked_task.status = TaskStatus::Parked;
12852        assert!(with(&parked_task, &run), "the Parked status is the case");
12853
12854        let mut not_parked = run.clone();
12855        not_parked.parked = false;
12856        not_parked.status = RunStatus::Stalled;
12857        assert!(!with(&task, &not_parked), "a stall is the conductor's");
12858
12859        let mut fresh = task.clone();
12860        fresh.fresh_start = true;
12861        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12862
12863        let mut review = task.clone();
12864        review.review_branch = Some("magi/x/A".to_owned());
12865        assert!(!with(&review, &run), "review is ranked before resume");
12866
12867        let mut held = task.clone();
12868        held.status = TaskStatus::Held;
12869        assert!(!with(&held, &run), "a hold stays visible to the conductor");
12870
12871        let mut released = run.clone();
12872        released.released_to = Some("20260901-000000-new1".to_owned());
12873        assert!(!with(&task, &released), "nothing left to resume into");
12874
12875        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12876            "unreadable"
12877        )));
12878    }
12879
12880    #[test]
12881    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12882        let mut released = RunState::new(
12883            PathBuf::from("/repo"),
12884            "main".to_owned(),
12885            "abc1234def".to_owned(),
12886            "add retries".to_owned(),
12887            Config::default(),
12888        );
12889        released.status = RunStatus::Blocked;
12890        assert_eq!(
12891            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12892            Some(released.id.clone())
12893        );
12894        released.released_to = Some("20260901-000000-new1".to_owned());
12895        assert_eq!(
12896            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12897            None,
12898            "there is nothing left to resume it into"
12899        );
12900    }
12901
12902    #[test]
12903    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12904        // Mirrors the failure this exists to close: a task's last run ended
12905        // `Blocked` with the review budget spent, `crate::conduct` chose
12906        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
12907        // evidence), and without this check `attempt` would go on treating
12908        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
12909        // review loop iterates zero times over an already-spent budget, so
12910        // the resumed run settles right back to `Blocked` having asked nobody
12911        // anything, and `Requeue`'s promised fresh competition never happens.
12912        let mut exhausted = RunState::new(
12913            PathBuf::from("/repo"),
12914            "main".to_owned(),
12915            "abc1234def".to_owned(),
12916            "add retries".to_owned(),
12917            Config::default(),
12918        );
12919        exhausted.status = RunStatus::Blocked;
12920        exhausted.config.graph.review_rounds = 1;
12921        exhausted.reviews = vec![review_round(1)];
12922
12923        assert_eq!(
12924            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12925            None,
12926            "an exhausted `Blocked` run must not be offered as resumable"
12927        );
12928
12929        // A `Blocked` run with rounds still unused is genuinely worth
12930        // resuming, and must still be found.
12931        let mut has_budget_left = RunState::new(
12932            PathBuf::from("/repo"),
12933            "main".to_owned(),
12934            "abc1234def".to_owned(),
12935            "add retries".to_owned(),
12936            Config::default(),
12937        );
12938        has_budget_left.status = RunStatus::Blocked;
12939        has_budget_left.config.graph.review_rounds = 3;
12940        has_budget_left.reviews = vec![review_round(1)];
12941
12942        assert_eq!(
12943            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12944                Ok(has_budget_left.clone())
12945            }),
12946            Some(has_budget_left.id.clone())
12947        );
12948    }
12949
12950    #[test]
12951    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12952        let mut run = RunState::new(
12953            PathBuf::from("/repo"),
12954            "main".to_owned(),
12955            "abc1234def".to_owned(),
12956            "add retries".to_owned(),
12957            Config::default(),
12958        );
12959        run.status = RunStatus::Blocked;
12960        run.config.graph.review_rounds = 1;
12961        run.reviews = vec![review_round(1)];
12962        run.pr_publication_pending = true;
12963        assert_eq!(
12964            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12965            Some(run.id.clone()),
12966            "a spent review budget must not turn a failed publication into a re-competition"
12967        );
12968    }
12969
12970    #[test]
12971    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12972        let mut task = Task::new(
12973            "recover work".into(),
12974            "recover work".into(),
12975            PathBuf::from("/repo"),
12976            crate::queue::Source::Human,
12977        );
12978        let mut history = std::collections::BTreeMap::new();
12979        for index in 0..8 {
12980            let mut run = run_state(RunStatus::Blocked);
12981            run.id = format!("20260101-000000-{index:04}");
12982            run.base_commit = format!("upstream-{index}");
12983            // Seven empty newer attempts must not erase the old recovery owner.
12984            if index > 0 {
12985                run.candidates.clear();
12986            }
12987            task.runs.extend([run.id.clone(), run.id.clone()]);
12988            history.insert(run.id.clone(), run);
12989            task.requeue();
12990        }
12991        let check = |task: &Task, starter: &Starter, limit| {
12992            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12993        };
12994        assert!(
12995            check(&task, &Starter::Start, 8)
12996                .unwrap()
12997                .contains("8 unretired")
12998        );
12999        assert!(check(&task, &Starter::Start, 9).is_none());
13000        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
13001        task.release_operator("owner", None);
13002        assert_eq!(task.attempts, 0);
13003        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13004        assert!(check(&restored, &Starter::Start, 8).is_some());
13005        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
13006        assert!(check(&restored, &Starter::Start, 0).is_none());
13007    }
13008
13009    #[test]
13010    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
13011        let tmp = tempfile::tempdir().unwrap();
13012        let mut task = Task::new(
13013            "recover selected PR".into(),
13014            "preserve implementation".into(),
13015            tmp.path().join("repo"),
13016            crate::queue::Source::Human,
13017        );
13018        let mut failed = run_state(RunStatus::Failed);
13019        failed.id = "20260101-000000-fail".into();
13020        failed.candidates.clear();
13021        failed.prep_complete = Some(false);
13022        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
13023        failed.startup = Some(crate::run::Startup {
13024            kind: "pr-recovery".into(),
13025            branch: Some("selected-public-head".into()),
13026            stage: "worktree-setup".into(),
13027            complete: false,
13028            failure: Some("setup modified a tracked file and failed".into()),
13029        });
13030        // Setup may fail before a candidate is recorded; its dirty worktree
13031        // still needs protection and consumes the independent retained bound.
13032        let worktree = failed.worktree_root().join("under-review");
13033        std::fs::create_dir_all(&worktree).unwrap();
13034        let retained_edit = worktree.join("implementation");
13035        std::fs::write(&retained_edit, "retained setup edit").unwrap();
13036        task.record_startup_failure(crate::run::StartupFailure {
13037            run: failed.id.clone(),
13038            stage: "worktree-setup".into(),
13039        });
13040        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13041        assert!(task.runs.is_empty() && task.passes.is_empty());
13042        assert_eq!(task.attempts, 0);
13043        let starter = Starter::Review("selected-public-head".into());
13044        assert!(
13045            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
13046                .unwrap()
13047                .contains("1 unretired")
13048        );
13049        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
13050        assert!(
13051            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
13052                .unwrap()
13053                .contains("Cannot verify")
13054        );
13055        // Older or mixed writers can link the same reservation in both lists.
13056        let mut mixed = task.clone();
13057        mixed.runs.push(failed.id.clone());
13058        mixed
13059            .startup_failures
13060            .push(task.startup_failures[0].clone());
13061        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
13062        failed.retired_to = Some("verified-recovery-owner".into());
13063        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
13064        assert!(
13065            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
13066                panic!("resuming the existing owner must not allocate a new attempt")
13067            })
13068            .is_none()
13069        );
13070        assert_eq!(
13071            std::fs::read_to_string(retained_edit).unwrap(),
13072            "retained setup edit"
13073        );
13074        assert!(task.runs.is_empty() && task.passes.is_empty());
13075        assert_eq!(task.attempts, 0);
13076    }
13077
13078    #[test]
13079    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
13080        let mut task = Task::new(
13081            "recover work".into(),
13082            "recover work".into(),
13083            PathBuf::from("/repo"),
13084            crate::queue::Source::Human,
13085        );
13086        let mut run = run_state(RunStatus::Superseded);
13087        run.candidates.clear();
13088        task.runs.push(run.id.clone());
13089        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
13090        run.retired_to = Some("authority".into());
13091        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13092        run.retired_to = None;
13093        run.released_to = Some("authority".into());
13094        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13095        assert!(
13096            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
13097                .unwrap()
13098                .contains("Cannot verify")
13099        );
13100        // Resuming an existing owner needs no new inventory or worktree budget.
13101        assert!(
13102            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
13103                panic!("resume must not load historical attempts")
13104            })
13105            .is_none()
13106        );
13107    }
13108
13109    #[test]
13110    fn retired_resume_requires_a_valid_same_repository_authority() {
13111        let mut source = run_state(RunStatus::Blocked);
13112        let mut empty = run_state(RunStatus::Blocked);
13113        empty.retired_to = Some(source.id.clone());
13114        let runs = vec![source.id.clone(), empty.id.clone()];
13115        let resolve = |source: &RunState, empty: &RunState| {
13116            unfinished_run_with(&runs, "fixture", |id| {
13117                if id == source.id {
13118                    Ok(source.clone())
13119                } else if id == empty.id {
13120                    Ok(empty.clone())
13121                } else {
13122                    bail!("unreadable authority")
13123                }
13124            })
13125        };
13126        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
13127        assert_eq!(
13128            choose_starter(None, false, resolve(&source, &empty).as_deref()),
13129            Starter::Resume(source.id.clone())
13130        );
13131        source.retired_to = Some(empty.id.clone());
13132        assert!(
13133            resolve(&source, &empty).is_none(),
13134            "cycles do not revive obsolete runs"
13135        );
13136        source.retired_to = None;
13137        source.repo = PathBuf::from("/another-repository");
13138        assert!(resolve(&source, &empty).is_none());
13139        source.repo = empty.repo.clone();
13140        source.released_to = Some("later".into());
13141        assert!(resolve(&source, &empty).is_none());
13142        empty.retired_to = Some("unlisted-run".into());
13143        assert!(resolve(&source, &empty).is_none());
13144    }
13145
13146    #[test]
13147    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
13148        // A task whose history holds an *older* run that still looks
13149        // resumable (say, a competition `Runner::review` was started
13150        // alongside after that older run went `Stalled`) and a *newest* run
13151        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
13152        // on this task must mean a fresh competition — falling back to the
13153        // stale, superseded `Stalled` run instead would resurrect history
13154        // nothing asked to revisit and silently defeat the requeue.
13155        let mut older_stalled = RunState::new(
13156            PathBuf::from("/repo"),
13157            "main".to_owned(),
13158            "abc1234def".to_owned(),
13159            "add retries".to_owned(),
13160            Config::default(),
13161        );
13162        older_stalled.status = RunStatus::Stalled;
13163
13164        let mut newest_exhausted = RunState::new(
13165            PathBuf::from("/repo"),
13166            "main".to_owned(),
13167            "abc1234def".to_owned(),
13168            "add retries".to_owned(),
13169            Config::default(),
13170        );
13171        newest_exhausted.status = RunStatus::Blocked;
13172        newest_exhausted.config.graph.review_rounds = 1;
13173        newest_exhausted.reviews = vec![review_round(1)];
13174
13175        assert_eq!(
13176            unfinished_run_with(
13177                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
13178                "t",
13179                |_| Ok(newest_exhausted.clone())
13180            ),
13181            None,
13182            "the newest run is exhausted, so nothing here is worth resuming - \
13183             least of all the older, already-superseded run"
13184        );
13185    }
13186
13187    #[test]
13188    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
13189        assert_eq!(
13190            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
13191                Err(anyhow::anyhow!("fixture is absent"))
13192            }),
13193            None
13194        );
13195    }
13196
13197    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
13198        let mut q = ask::Question::new(
13199            run.to_owned(),
13200            "implement".to_owned(),
13201            "impl-A".to_owned(),
13202            "continue?".to_owned(),
13203            String::new(),
13204            vec!["resume で続行する".to_owned(), "other".to_owned()],
13205        );
13206        q.actions.insert("resume で続行する".to_owned(), action);
13207        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
13208            .unwrap();
13209        q
13210    }
13211
13212    fn held_task_with(run: &str) -> Task {
13213        let mut t = task();
13214        t.runs = vec![run.to_owned()];
13215        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
13216        t
13217    }
13218
13219    fn resume_action(run: &str) -> ask::ChoiceAction {
13220        ask::ChoiceAction::Resume { run: run.into() }
13221    }
13222
13223    #[test]
13224    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
13225        let home = crate::run::test_home();
13226        for parked in [false, true] {
13227            let mut t = task();
13228            t.start("A".into());
13229            t.start("B".into());
13230            assert_eq!(t.runs, vec!["A", "B"]);
13231            t.start("A".into());
13232            let mut resumed = run_state(RunStatus::Blocked);
13233            resumed.id = "A".into();
13234            resumed.parked = parked;
13235            resumed.driver_exited = true;
13236            t.hold_machine(Some("resumed run stopped".into()));
13237            let q = action_question("A", resume_action("A"));
13238            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13239            assert_eq!(
13240                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
13241                    assert_eq!(id, "A");
13242                    Ok(resumed.clone())
13243                }),
13244                ActionDecision::Resume("A".into())
13245            );
13246            assert_eq!(
13247                action_standing(&t, &action_question("B", resume_action("B"))),
13248                ActionStanding::Stale
13249            );
13250            t.release_operator("cli", None);
13251            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
13252                assert_eq!(id, "A");
13253                Ok(resumed.clone())
13254            });
13255            assert_eq!(
13256                choose_starter(None, false, unfinished.as_deref()),
13257                Starter::Resume("A".into())
13258            );
13259            assert_eq!(t.runs, vec!["B", "A"]);
13260        }
13261    }
13262
13263    #[test]
13264    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
13265        let home = crate::run::test_home();
13266        let mut state = crate::land::tests::repair_state(true, true);
13267        state.status = RunStatus::Landing;
13268        state.parked = true;
13269        state.driver_exited = true;
13270        let mut q = ask::Question::new(
13271            state.id.clone(),
13272            land::APPROVAL_NODE.into(),
13273            "land".into(),
13274            "Merge?".into(),
13275            String::new(),
13276            vec![land::APPROVE.into(), land::HOLD.into()],
13277        );
13278        q.id = state.id.clone();
13279        state.land_approval = Some(crate::run::LandApproval {
13280            question: q.id.clone(),
13281            head: "current-head".into(),
13282        });
13283        assert!(land::upgrade_repair_choice(&mut q, &state));
13284        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13285        let mut task = held_task_with(&state.id);
13286        task.status = TaskStatus::Parked;
13287        assert_eq!(
13288            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
13289            ActionDecision::Resume(state.id.clone())
13290        );
13291        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13292        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
13293        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
13294        assert_eq!(
13295            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
13296            ActionDecision::Resume(state.id.clone()),
13297            "a repair answer newer than the manual hold resumes the existing owner"
13298        );
13299        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
13300        for answered_at in [q.answered_at, None] {
13301            let mut older = q.clone();
13302            older.answered_at = answered_at;
13303            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
13304                panic!("a later manual hold must prevent dispatch")
13305            });
13306            let ActionDecision::Refuse(reason) = refused else {
13307                panic!("expected an actionable refusal, got {refused:?}");
13308            };
13309            assert!(reason.contains("later operator decision"));
13310            assert!(reason.contains(&format!("magi task release {}", task.id)));
13311        }
13312        task.operator_decided_at = None;
13313        let mut superseded = state.clone();
13314        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
13315        assert_eq!(
13316            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
13317            ActionDecision::Stale
13318        );
13319        for case in 1..4 {
13320            let mut changed = state.clone();
13321            match case {
13322                1 => changed.status = RunStatus::Blocked,
13323                2 => changed.released_to = Some("new-owner".into()),
13324                _ => changed.land_approval.as_mut().unwrap().head.clear(),
13325            }
13326            assert!(matches!(
13327                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
13328                ActionDecision::Refuse(_)
13329            ));
13330        }
13331        assert!(matches!(
13332            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
13333                "missing owner"
13334            )),
13335            ActionDecision::Refuse(_)
13336        ));
13337        task.runs.push("replacement".into());
13338        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
13339        assert_eq!(
13340            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
13341                "old owner must not load"
13342            )),
13343            ActionDecision::Stale
13344        );
13345    }
13346
13347    #[test]
13348    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
13349        let mut state = crate::land::tests::repair_state(true, true);
13350        state.status = RunStatus::Landing;
13351        state.parked = true;
13352        state.driver_exited = true;
13353        let mut q = ask::Question::new(
13354            state.id.clone(),
13355            land::APPROVAL_NODE.into(),
13356            "land".into(),
13357            "Merge?".into(),
13358            String::new(),
13359            vec![land::APPROVE.into(), land::HOLD.into()],
13360        );
13361        q.id = state.id.clone();
13362        state.land_approval = Some(crate::run::LandApproval {
13363            question: q.id.clone(),
13364            head: "current-head".into(),
13365        });
13366        state.save().unwrap();
13367        land::upgrade_repair_choice(&mut q, &state);
13368        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13369        Questions::open().put(&mut q).unwrap();
13370        let tmp = tempfile::tempdir().unwrap();
13371        let queue = Queue::at(tmp.path().join("queue"));
13372        let mut task = held_task_with(&state.id);
13373        task.status = TaskStatus::Parked;
13374        queue.put(&mut task).unwrap();
13375        let empty = Arc::new(tokio::sync::Semaphore::new(0));
13376        let free = Arc::new(tokio::sync::Semaphore::new(1));
13377        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
13378        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
13379        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
13380        assert!(claim.permit.is_some());
13381        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
13382        drop(claim);
13383        Questions::open()
13384            .update(&q.id, |q| {
13385                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
13386                Ok(())
13387            })
13388            .unwrap();
13389        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
13390        assert!(claim.permit.is_none());
13391        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
13392    }
13393
13394    #[test]
13395    fn decide_action_resumes_only_the_latest_resumable_run() {
13396        let home = crate::run::test_home();
13397        let t = held_task_with("r1");
13398        let q = action_question("r1", resume_action("r1"));
13399        let load = |s: RunState| move |_: &str| Ok(s);
13400        assert_eq!(
13401            decide_action(
13402                &home,
13403                &t,
13404                &q,
13405                &PHRASES_EN,
13406                load(run_state(RunStatus::Blocked))
13407            ),
13408            ActionDecision::Resume("r1".into())
13409        );
13410        // Not the latest run of the task.
13411        let q_other = action_question("r1", resume_action("r0"));
13412        assert!(matches!(
13413            decide_action(
13414                &home,
13415                &t,
13416                &q_other,
13417                &PHRASES_EN,
13418                load(run_state(RunStatus::Blocked))
13419            ),
13420            ActionDecision::Refuse(_)
13421        ));
13422        // A finished run cannot make progress.
13423        assert!(matches!(
13424            decide_action(
13425                &home,
13426                &t,
13427                &q,
13428                &PHRASES_EN,
13429                load(run_state(RunStatus::Ready))
13430            ),
13431            ActionDecision::Refuse(_)
13432        ));
13433        // A released one either.
13434        let mut released = run_state(RunStatus::Blocked);
13435        released.released_to = Some("elsewhere".into());
13436        assert!(matches!(
13437            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
13438            ActionDecision::Refuse(_)
13439        ));
13440        // Unreadable state is a refusal, never a fresh competition.
13441        assert!(matches!(
13442            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
13443            ActionDecision::Refuse(_)
13444        ));
13445    }
13446
13447    #[test]
13448    fn decide_action_ignores_a_question_about_an_earlier_run() {
13449        let home = crate::run::test_home();
13450        let mut t = held_task_with("r1");
13451        t.runs.push("r2".to_owned());
13452        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13453        assert_eq!(
13454            decide_action(
13455                &home,
13456                &t,
13457                &action_question("r1", ask::ChoiceAction::Done),
13458                &PHRASES_EN,
13459                never
13460            ),
13461            ActionDecision::Stale
13462        );
13463    }
13464
13465    #[test]
13466    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
13467        let home = crate::run::test_home();
13468        let mut t = held_task_with("r1");
13469        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13470        assert_eq!(
13471            decide_action(
13472                &home,
13473                &t,
13474                &action_question("r1", ask::ChoiceAction::Requeue),
13475                &PHRASES_EN,
13476                never
13477            ),
13478            ActionDecision::Requeue
13479        );
13480        let done_q = action_question("r1", ask::ChoiceAction::Done);
13481        assert_eq!(
13482            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13483            ActionDecision::Done
13484        );
13485        t.mark_action_applied(&done_q.id);
13486        assert_eq!(
13487            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13488            ActionDecision::Skip
13489        );
13490
13491        // A plain answer (no action for that label) does nothing.
13492        let mut plain = action_question("r1", ask::ChoiceAction::Done);
13493        plain.actions.clear();
13494        assert_eq!(
13495            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
13496            ActionDecision::Skip
13497        );
13498        // A running task is left alone.
13499        let mut running = held_task_with("r1");
13500        running.status = TaskStatus::Running;
13501        assert_eq!(
13502            decide_action(
13503                &home,
13504                &running,
13505                &action_question("r1", ask::ChoiceAction::Done),
13506                &PHRASES_EN,
13507                never
13508            ),
13509            ActionDecision::Skip
13510        );
13511    }
13512
13513    #[test]
13514    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
13515        crate::run::pin_test_home();
13516        for legacy in [false, true] {
13517            let dir = tempfile::tempdir().unwrap();
13518            let queue = Queue::at(dir.path().join("queue"));
13519            let questions = Questions::at(dir.path().join("questions"));
13520            let run = "20260101-000000-hold";
13521            let mut task = held_task_with(run);
13522            task.status = TaskStatus::Parked;
13523            let mut q = ask::Question::new(
13524                run.into(),
13525                land::APPROVAL_NODE.into(),
13526                "land".into(),
13527                "Repair?".into(),
13528                String::new(),
13529                vec![land::REPAIR.into()],
13530            );
13531            q.actions.insert(land::REPAIR.into(), resume_action(run));
13532            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13533            // Deterministically order the answer before the actual manual hold.
13534            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13535            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
13536            questions.put(&mut q).unwrap();
13537            task.hold_manual(Some("Keep this PR paused".into()));
13538            if legacy {
13539                task.hold_source = None;
13540            }
13541            queue.put(&mut task).unwrap();
13542
13543            apply_task_choice_actions(&queue, &questions, dir.path());
13544            let after = queue.get(&task.id).unwrap();
13545            assert!(after.operator_held());
13546            assert_eq!(after.hold_source, task.hold_source);
13547            assert_eq!(after.operator_decided_at, task.operator_decided_at);
13548            assert_eq!(after.runs, task.runs);
13549            assert_eq!(after.instruction, task.instruction);
13550            assert!(after.resume_override.is_none());
13551            assert!(after.action_applied(&q.id));
13552            let reason = after.hold_reason.as_deref().unwrap();
13553            assert!(reason.starts_with("Keep this PR paused"));
13554            assert!(reason.contains("later operator decision"));
13555            assert!(reason.contains(&format!("magi task release {}", task.id)));
13556
13557            for recovery in [
13558                crate::conduct::Recovery::Review,
13559                crate::conduct::Recovery::Requeue,
13560            ] {
13561                crate::conduct::apply(
13562                    &queue,
13563                    &questions,
13564                    &crate::conduct::Verdict {
13565                        decisions: vec![crate::conduct::Decision {
13566                            id: task.id.clone(),
13567                            recovery: Some(recovery),
13568                            ..Default::default()
13569                        }],
13570                    },
13571                )
13572                .unwrap();
13573            }
13574            // Reconciliation is idempotent, and automatic recovery cannot
13575            // reopen this owner after it observes the rejected repair answer.
13576            apply_task_choice_actions(&queue, &questions, dir.path());
13577            let still_held = queue.get(&task.id).unwrap();
13578            assert!(still_held.operator_held());
13579            assert_eq!(still_held.hold_reason, after.hold_reason);
13580            assert_eq!(still_held.runs, task.runs);
13581            assert!(still_held.review_branch.is_none());
13582            assert!(!still_held.fresh_start);
13583            assert!(queue.next_runnable().is_none());
13584        }
13585    }
13586
13587    #[test]
13588    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
13589        for held in [false, true] {
13590            for retry in [false, true] {
13591                let dir = tempfile::tempdir().unwrap();
13592                let queue = Queue::at(dir.path().join("queue"));
13593                let questions = Questions::at(dir.path().join("questions"));
13594                let home = dir.path().join("home");
13595                let mut t = task();
13596                if held {
13597                    t.hold_machine(Some("driver state unknown".into()));
13598                }
13599                queue.put(&mut t).unwrap();
13600                let verdict = serde_json::from_value(serde_json::json!({
13601                    "decisions": [{
13602                        "id": t.id,
13603                        "question": "Driver state unknown; retry the checks or hold?",
13604                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
13605                        "actions": {
13606                            "daemon: recheck and retry": {"do": "requeue"},
13607                            "daemon: hold the task": {"do": "hold"}
13608                        }
13609                    }]
13610                }))
13611                .unwrap();
13612                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
13613                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13614                let mut q = questions.list().pop().unwrap();
13615                let choice = if retry {
13616                    "daemon: recheck and retry"
13617                } else {
13618                    "daemon: hold the task"
13619                };
13620                assert_eq!(q.actions.len(), 2);
13621                q.answer(ask::Answer::Choice(choice.into())).unwrap();
13622                questions.put(&mut q).unwrap();
13623
13624                // A Web answer does not remove the deputy's fresh lease.
13625                questions.beat(&q.id, ask::WaiterKind::Deputy);
13626                for _ in 0..2 {
13627                    resolve_blockers(&queue, &questions);
13628                    apply_task_choice_actions(&queue, &questions, &home);
13629                    let waiting = queue.get(&t.id).unwrap();
13630                    assert_eq!(waiting.status, TaskStatus::Blocked);
13631                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
13632                    assert!(waiting.answers.is_empty());
13633                    assert!(!waiting.action_applied(&q.id));
13634                    assert!(runnable(&queue).is_empty());
13635                    let free = Arc::new(tokio::sync::Semaphore::new(1));
13636                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
13637                }
13638                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13639
13640                // Releasing the blocker and applying the operation share one save.
13641                resolve_blockers(&queue, &questions);
13642                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13643                apply_task_choice_actions(&queue, &questions, &home);
13644                let after = queue.get(&t.id).unwrap();
13645                assert_eq!(
13646                    after.status,
13647                    if retry {
13648                        TaskStatus::Queued
13649                    } else {
13650                        TaskStatus::Held
13651                    }
13652                );
13653                assert!(after.action_applied(&q.id));
13654                assert_eq!(after.operator_held(), !retry);
13655                assert_eq!(after.answers.len(), 1);
13656
13657                // A later operator decision must not replay this answer.
13658                let mut changed = after;
13659                if retry {
13660                    changed.hold_manual(Some("later hold".into()));
13661                } else {
13662                    changed.release_operator("test", None);
13663                }
13664                let expected = changed.status;
13665                queue.put(&mut changed).unwrap();
13666                apply_task_choice_actions(&queue, &questions, &home);
13667                assert_eq!(queue.get(&t.id).unwrap().status, expected);
13668            }
13669        }
13670    }
13671
13672    #[test]
13673    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
13674        let dir = tempfile::tempdir().unwrap();
13675        let queue = Queue::at(dir.path().join("queue"));
13676        let questions = Questions::at(dir.path().join("questions"));
13677        let home = dir.path().join("home");
13678        let mut state = run_state(RunStatus::Blocked);
13679        state.id = "20260101-000000-act1".to_owned();
13680        state.save_under(&home).unwrap();
13681
13682        let mut t = held_task_with(&state.id);
13683        queue.put(&mut t).unwrap();
13684        let mut q = action_question(&state.id, resume_action(&state.id));
13685        questions.put(&mut q).unwrap();
13686
13687        apply_task_choice_actions(&queue, &questions, &home);
13688        let after = queue.get(&t.id).unwrap();
13689        assert_eq!(after.status, TaskStatus::Queued);
13690        assert!(!after.fresh_start);
13691        assert!(after.action_applied(&q.id));
13692        let pin = after.resume_override.clone().unwrap();
13693        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
13694        assert!(pin.forced);
13695
13696        // Held again later: the same answer does not release it a second time.
13697        let mut again = queue.get(&t.id).unwrap();
13698        again.hold_machine(Some("later".into()));
13699        queue.put(&mut again).unwrap();
13700        apply_task_choice_actions(&queue, &questions, &home);
13701        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13702    }
13703
13704    #[test]
13705    fn a_delivered_answer_is_still_acted_on_exactly_once() {
13706        let dir = tempfile::tempdir().unwrap();
13707        let queue = Queue::at(dir.path().join("queue"));
13708        let questions = Questions::at(dir.path().join("questions"));
13709        let home = dir.path().join("home");
13710        let mut state = run_state(RunStatus::Blocked);
13711        state.id = "20260101-000000-act2".to_owned();
13712        state.save_under(&home).unwrap();
13713
13714        let mut t = held_task_with(&state.id);
13715        queue.put(&mut t).unwrap();
13716        let mut q = action_question(&state.id, resume_action(&state.id));
13717        q.answer_delivered = true;
13718        questions.put(&mut q).unwrap();
13719
13720        // Delivered, and the agent then died: the task is still held, so the
13721        // chosen action applies.
13722        apply_task_choice_actions(&queue, &questions, &home);
13723        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13724        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
13725
13726        // Held again: the same answer does nothing a second time.
13727        let mut again = queue.get(&t.id).unwrap();
13728        again.hold_machine(Some("later".into()));
13729        queue.put(&mut again).unwrap();
13730        apply_task_choice_actions(&queue, &questions, &home);
13731        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13732    }
13733
13734    #[test]
13735    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
13736        let dir = tempfile::tempdir().unwrap();
13737        let queue = Queue::at(dir.path().join("queue"));
13738        let questions = Questions::at(dir.path().join("questions"));
13739        let home = dir.path().join("home");
13740        let mut state = run_state(RunStatus::Blocked);
13741        state.id = "20260101-000000-act3".to_owned();
13742        state.save_under(&home).unwrap();
13743        let mut t = held_task_with(&state.id);
13744        queue.put(&mut t).unwrap();
13745        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
13746        questions.put(&mut q).unwrap();
13747
13748        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
13749        apply_task_choice_actions(&queue, &questions, &home);
13750        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13751
13752        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13753        apply_task_choice_actions(&queue, &questions, &home);
13754        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13755    }
13756
13757    #[test]
13758    fn action_standing_tells_the_reasons_apart() {
13759        let mut t = held_task_with("r1");
13760        let q = action_question("r1", ask::ChoiceAction::Requeue);
13761        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13762        let mut plain = q.clone();
13763        plain.actions.clear();
13764        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
13765
13766        // Applied wins over everything, even a running task.
13767        t.mark_action_applied(&q.id);
13768        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
13769
13770        // A newer attempt running: the old question is Stale, not Busy.
13771        let mut t = held_task_with("r1");
13772        t.start("r2".to_owned());
13773        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
13774        // The same question about the latest run just waits.
13775        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
13776        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13777        t.status = TaskStatus::Blocked;
13778        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13779
13780        // A conductor question is keyed by the task, never stale.
13781        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
13782        c.node = crate::conduct::NODE.to_owned();
13783        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
13784        assert!(!ActionStanding::Busy.daemon_owns());
13785    }
13786
13787    #[test]
13788    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
13789        let dir = tempfile::tempdir().unwrap();
13790        let queue = Queue::at(dir.path().join("queue"));
13791        let questions = Questions::at(dir.path().join("questions"));
13792        let home = dir.path().join("home");
13793        let mut state = run_state(RunStatus::Blocked);
13794        state.id = "20260101-000000-act4".to_owned();
13795        state.save_under(&home).unwrap();
13796        let mut t = held_task_with(&state.id);
13797        t.status = TaskStatus::Running;
13798        queue.put(&mut t).unwrap();
13799        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13800        q.cwd = Some(dir.path().display().to_string());
13801        questions.put(&mut q).unwrap();
13802
13803        // While the task runs the daemon will not act, so the waiter still
13804        // delivers the word to the dead asker's seat ...
13805        let running = queue.get(&t.id).unwrap();
13806        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13807        assert!(matches!(
13808            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13809            crate::waiter::Action::Deliver(_)
13810        ));
13811        // ... and the daemon waits while the task runs, then applies once.
13812        apply_task_choice_actions(&queue, &questions, &home);
13813        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13814        let mut back = queue.get(&t.id).unwrap();
13815        back.hold_machine(Some("later".into()));
13816        queue.put(&mut back).unwrap();
13817        apply_task_choice_actions(&queue, &questions, &home);
13818        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13819        let mut again = queue.get(&t.id).unwrap();
13820        again.hold_machine(Some("again".into()));
13821        queue.put(&mut again).unwrap();
13822        apply_task_choice_actions(&queue, &questions, &home);
13823        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13824    }
13825}