Skip to main content

magi/
daemon.rs

1//! The unattended scheduler and independently leased task workers.
2//!
3//! The scheduler chooses tasks and execution lanes; a detached worker owns each
4//! queue claim, graph driver and outcome settlement. Replacing the scheduler
5//! reconstructs occupied slots from live worker jobs, without touching their
6//! attempts, passes or paid agent calls. Finite maintenance jobs follow the same
7//! lifetime rule. Explicit parking is durable control, never an upgrade step.
8//!
9//! # A crashed worker is legible
10//!
11//! A task is written `Running`, with its run id, before graph execution. The
12//! worker keeps its claim until the outcome is recorded. Recovery requires both
13//! no live worker reservation and an obtainable task claim, and settles the
14//! saved run through the same policy as a live finish. A scheduler's missing
15//! heartbeat alone is never evidence that a run died.
16//!
17//! # Retries are bounded
18//!
19//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
20//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
21//! exception is a run that ended `Stalled`: the panel collapsed because the
22//! agent CLIs hit their quota, which is a fact about the machine and not about
23//! the task, so it must not spend an attempt. Without that exception a quota
24//! outage would quietly hold the entire backlog, and the operator would come
25//! back to a reset quota and nothing left that the loop is willing to run.
26
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Mutex, MutexGuard};
31use std::time::Duration;
32
33use anyhow::{Context, Result, bail};
34use jiff::Timestamp;
35use serde::{Deserialize, Serialize};
36use tokio::sync::Notify;
37
38use crate::ask::{self, Questions};
39use crate::clean;
40use crate::conduct::Conductor;
41use crate::config::{Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{Queue, Task, TaskStatus};
46use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
47use crate::triage;
48
49/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
50pub const SCHEMA: u32 = 1;
51
52/// How often the status file is refreshed. A reader treats a status file older
53/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
54/// that a busy daemon is never mistaken for a dead one.
55pub const HEARTBEAT: Duration = Duration::from_secs(5);
56
57/// How old a heartbeat may be before a reader calls the daemon dead. Six
58/// missed beats: long enough to survive a slow filesystem, short enough that
59/// a crashed daemon is not still reported as running a task.
60///
61/// The single threshold every reader shares — the web UI's `/api/health` and
62/// `magi doctor` both call [`Reading::running`] rather than each comparing
63/// against their own copy of this number, so a crashed daemon cannot look
64/// alive on one screen and dead on another.
65pub const STALE_SECS: i64 = 30;
66
67/// Default queue poll interval.
68pub const POLL: Duration = Duration::from_secs(5);
69
70/// How old a claim has to be before startup sweeps it. Longer than any run
71/// this graph plausibly takes, so a sweep cannot pull a task out from under a
72/// daemon that is merely slow.
73pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
74
75/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
76/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
77///
78/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
79/// poll, by attempting the task's own claim: a dead pid is proof enough for
80/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
81/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
82/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
83/// age instead, since there is nothing else to check (see
84/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
85/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
86/// task `running` — see
87/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
88/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
89/// conductor well before the mechanical six-hour sweep would, and thirty
90/// minutes is comfortably below `STALE_CLAIM` while still being generous
91/// enough that a task merely late to publish its first [`HEARTBEAT`] is
92/// never mistaken for abandoned.
93pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
94
95/// What the loop is working on, for the status file.
96#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(default)]
98pub struct Current {
99    /// Worker reservation that produced this claim; absent on legacy drivers.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub worker: Option<String>,
102    /// Task id being run.
103    pub task: String,
104    /// Run id the task produced.
105    pub run: String,
106}
107
108/// The daemon's liveness, published to `<home>/daemon.json`.
109///
110/// This is the only interface between the loop and the web UI, which is why it
111/// carries `updated_at` as well as `started_at`: a reader cannot tell a
112/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
113/// can compare the heartbeat against the clock.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Status {
116    /// On-disk format version.
117    pub schema: u32,
118    /// Process id, so a human can find or kill the daemon.
119    pub pid: u32,
120    /// When this process started.
121    pub started_at: Timestamp,
122    /// Last heartbeat.
123    pub updated_at: Timestamp,
124    /// True when the queue has nothing runnable.
125    pub idle: bool,
126    /// Every task and run currently in flight. More than one entry means the
127    /// loop is driving more than one run at once — see
128    /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
129    /// nothing is running, so a reader never has to treat "no field" and "an
130    /// empty list" as two different kinds of idle.
131    pub current: Vec<Current>,
132    /// Tasks that reached a terminal status in this process.
133    pub completed: usize,
134    /// Queue polls since start, so a wedged loop shows up as a frozen count.
135    pub polls: u64,
136    /// Effective startup capabilities of the question recovery loops.
137    #[serde(default)]
138    pub question_recovery: Option<crate::question_delivery::Recovery>,
139    /// Independent-worker control protocol supported by this scheduler.
140    #[serde(default)]
141    pub worker_protocol: Option<u32>,
142}
143
144impl Status {
145    /// A fresh, idle status for this process.
146    #[must_use]
147    pub fn new() -> Self {
148        let now = Timestamp::now();
149        Self {
150            schema: SCHEMA,
151            pid: std::process::id(),
152            started_at: now,
153            updated_at: now,
154            idle: true,
155            current: Vec::new(),
156            completed: 0,
157            polls: 0,
158            question_recovery: None,
159            worker_protocol: Some(1),
160        }
161    }
162}
163
164impl Default for Status {
165    fn default() -> Self {
166        Self::new()
167    }
168}
169
170/// How the loop should behave.
171#[derive(Debug, Clone, Serialize, Deserialize)]
172#[serde(default)]
173pub struct Opts {
174    /// Repository used by tasks that name none.
175    pub repo: PathBuf,
176    /// Explicit `magi.toml`, instead of the discovered layer stack.
177    pub config: Option<PathBuf>,
178    /// Queue poll interval.
179    pub poll: Duration,
180    /// Attempts a task gets before it is held for a human.
181    pub max_attempts: usize,
182    /// Drain what is runnable now, then return, instead of waiting for more.
183    pub once: bool,
184    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
185    pub merge: Option<String>,
186    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
187    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
188    /// `None` resolves to [`crate::run::default_worktree_root`] - the
189    /// operator's real `~/wt/<repo>` - the same way a run with no
190    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
191    /// that does not own that directory (a test, an embedding that manages
192    /// worktrees itself) must set this, or every idle tick reclaims worktrees
193    /// out from under whoever actually does.
194    pub worktrees_root: Option<PathBuf>,
195}
196
197impl Default for Opts {
198    fn default() -> Self {
199        Self {
200            repo: PathBuf::from("."),
201            config: None,
202            poll: POLL,
203            max_attempts: 2,
204            once: false,
205            merge: None,
206            worktrees_root: None,
207        }
208    }
209}
210
211impl Opts {
212    fn absolute(&self) -> Result<Self> {
213        let mut opts = self.clone();
214        opts.repo = std::path::absolute(&opts.repo)?;
215        opts.config = opts
216            .config
217            .as_deref()
218            .map(std::path::absolute)
219            .transpose()?;
220        opts.worktrees_root = opts
221            .worktrees_root
222            .as_deref()
223            .map(std::path::absolute)
224            .transpose()?;
225        Ok(opts)
226    }
227}
228
229/// How many runs a plain `usize` from config may drive concurrently, floored
230/// at one. A `0` in a config file would otherwise stall the loop entirely -
231/// no runnable task could ever start - which is never what an operator who
232/// wrote `0` meant.
233fn max_concurrent(n: usize) -> usize {
234    n.max(1)
235}
236
237/// Where the status file lives.
238#[must_use]
239pub fn status_path() -> PathBuf {
240    crate::run::home().join("daemon.json")
241}
242
243/// Publish the status file for this process.
244pub fn write_status(status: &Status) -> Result<()> {
245    write_status_to(&status_path(), status)
246}
247
248/// Publish a status to an explicit path.
249///
250/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
251/// on every health poll and must never see a half-written one.
252pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
253    if let Some(parent) = path.parent() {
254        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
255    }
256    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
257    let tmp = path.with_extension("json.tmp");
258    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
259    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
260    Ok(())
261}
262
263/// Delete the status file. Called on the way out so a clean exit reads as
264/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
265pub fn clear_status() {
266    clear_status_at(&status_path());
267}
268
269/// Delete a status file at an explicit path, so the loop's teardown and
270/// [`clear_status`] cannot drift apart: the loop is handed the path it
271/// published to, and a test can watch a temp file disappear.
272fn clear_status_at(path: &Path) {
273    let _ = std::fs::remove_file(path);
274}
275
276/// A cooperative stop, shared with whoever asked the loop to run.
277///
278/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
279/// Ctrl-C listener and the web UI keep others, and every clone points at the
280/// same flag. There is no channel because there is nothing to send — the only
281/// message is "stop", it is idempotent, and a flag cannot be missed by a
282/// receiver that was not listening yet.
283///
284/// A stop ends scheduler dispatch promptly. Its busy snapshot is observational:
285/// detached task workers keep their own lifetimes and ownership after this
286/// handle's scheduler exits.
287#[derive(Debug, Clone, Default)]
288pub struct Stop {
289    /// Set once, never cleared: a stop is not something an operator takes back
290    /// half way through, and a clearable flag would let a start racing a stop
291    /// resurrect a loop that is already unwinding.
292    stopped: Arc<AtomicBool>,
293    /// Live task workers observed by the scheduler's latest dispatch snapshot.
294    busy: Arc<std::sync::atomic::AtomicUsize>,
295    /// Wakes the idle wait. Without this a stop would not be seen until the
296    /// poll interval elapsed, and an operator tapping stop on a phone would
297    /// watch a button do nothing for five seconds.
298    wake: Arc<Notify>,
299    /// Handed to the run in flight, so a stop can also mean "park at the next
300    /// node boundary" instead of "finish the whole competition first".
301    pause: crate::graph::Pause,
302}
303
304impl Stop {
305    /// A stop nobody has asked for yet.
306    #[must_use]
307    pub fn new() -> Self {
308        Self::default()
309    }
310
311    /// Ask the loop to stop. Idempotent, and safe to call before the loop
312    /// starts: the flag is checked before the first poll.
313    pub fn stop(&self) {
314        self.stopped.store(true, Ordering::SeqCst);
315        // `notify_one` rather than `notify_waiters` because the loop may not be
316        // parked yet: this stores a permit, so a wait that registers a moment
317        // later returns at once instead of sleeping out the whole interval.
318        self.wake.notify_one();
319    }
320
321    /// Has a stop been asked for?
322    #[must_use]
323    pub fn stopped(&self) -> bool {
324        self.stopped.load(Ordering::SeqCst)
325    }
326
327    /// Whether a requested scheduler retirement still has an active snapshot.
328    /// Workers continue independently after the scheduler has retired.
329    #[must_use]
330    pub fn finishing(&self) -> bool {
331        self.stopped() && self.busy_now()
332    }
333
334    /// Ask the loop to stop *and* the run in flight to park at its next node
335    /// boundary.
336    ///
337    /// Unlike plain stop, explicit park asks workers to checkpoint at their
338    /// existing safe boundaries. Binary replacement never needs a park.
339    pub fn park(&self, cause: crate::run::ParkCause) {
340        self.pause.park_for(cause);
341        self.stop();
342    }
343
344    /// Has a park been asked for?
345    #[must_use]
346    pub fn parking(&self) -> bool {
347        self.pause.parked()
348    }
349
350    /// The pause handle to give a runner.
351    #[must_use]
352    pub fn pause(&self) -> crate::graph::Pause {
353        self.pause.clone()
354    }
355
356    /// Whether the scheduler's latest snapshot contains active task workers.
357    #[must_use]
358    pub fn busy_now(&self) -> bool {
359        self.busy.load(Ordering::SeqCst) > 0
360    }
361
362    /// Wait out one poll interval, returning early once a stop is asked for.
363    async fn idle(&self, poll: Duration) {
364        tokio::select! {
365            () = tokio::time::sleep(poll) => {}
366            () = self.wake.notified() => {}
367        }
368    }
369}
370
371/// The daemon's published state, read permissively.
372///
373/// This mirrors [`Status`], but is a separate declaration on purpose: every
374/// field defaults, so a status file from an older or newer magi still yields
375/// a usable reading — one this build has never heard of — instead of a parse
376/// error that hides the daemon entirely.
377#[derive(Debug, Clone, Default, Deserialize)]
378#[serde(default)]
379pub struct Reading {
380    /// Format version the daemon claims.
381    pub schema: u32,
382    /// Daemon process id, for an operator who wants to stop it.
383    pub pid: Option<u32>,
384    /// When that process started.
385    pub started_at: Option<Timestamp>,
386    /// Last heartbeat. Absent means the file is unusable, hence not running.
387    pub updated_at: Option<Timestamp>,
388    /// True when the queue had nothing runnable at the last poll.
389    pub idle: bool,
390    /// What the daemon is working on. Empty means idle; more than one entry
391    /// means more than one run is in flight at once.
392    ///
393    /// `deserialize_with` rather than the plain derive: a daemon started
394    /// before this field became a list is still out there writing the old
395    /// shape — a single `{"task":...,"run":...}` object, or its absence —
396    /// on every heartbeat until it is restarted, and a live process reading
397    /// that file during the rollout must still see it as running rather than
398    /// as absent. A bare type change here would fail the whole struct's
399    /// deserialization on a type mismatch, defeating the permissiveness this
400    /// type exists for.
401    #[serde(deserialize_with = "de_current")]
402    pub current: Vec<Current>,
403    /// Tasks this daemon process has finished.
404    pub completed: u64,
405    /// Queue polls this daemon process has made.
406    pub polls: u64,
407    /// Effective startup capabilities of the question recovery loops.
408    #[serde(default)]
409    pub question_recovery: Option<crate::question_delivery::Recovery>,
410    /// Independent-worker control protocol, absent on legacy embedded loops.
411    pub worker_protocol: Option<u32>,
412}
413
414/// Accept the old single-`Current`-or-absent shape as well as the current
415/// list, so a reader never has to know which build wrote the file.
416fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
417where
418    D: serde::Deserializer<'de>,
419{
420    #[derive(Deserialize)]
421    #[serde(untagged)]
422    enum Shape {
423        Many(Vec<Current>),
424        One(Current),
425    }
426    Ok(
427        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
428            Shape::Many(v) => v,
429            Shape::One(c) => vec![c],
430        }),
431    )
432}
433
434impl Reading {
435    /// Seconds since the last heartbeat, or `None` when there has never been
436    /// one.
437    #[must_use]
438    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
439        self.updated_at
440            .map(|at| (now.as_second() - at.as_second()).max(0))
441    }
442
443    /// Whether the loop counts as running: a heartbeat no older than
444    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
445    /// progress hours after the daemon that owned it was killed.
446    #[must_use]
447    pub fn running(&self, now: Timestamp) -> bool {
448        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
449    }
450}
451
452/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
453/// usable there.
454///
455/// Missing, half-written and unparseable all collapse to `None`, because the
456/// only question a reader asks is whether a daemon is alive, and a file it
457/// cannot read is not evidence that one is.
458#[must_use]
459pub fn read_status(home: &Path) -> Option<Reading> {
460    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
461    serde_json::from_str(&body).ok()
462}
463
464/// Read-only evidence of runs owned by a live daemon or independent worker.
465///
466/// CLI, sandboxed conversation controls and Web cleanup share this observation.
467/// A stale daemon heartbeat does not invalidate a worker's OS-held lease.
468/// Starting reservations and unknown worker state remain protected; observing
469/// them never creates, reconciles or archives files in the worker store.
470/// Callers interested in one identity use [`is_working_on`] or
471/// [`is_working_on_task`].
472#[must_use]
473pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
474    let mut current = read_status(home)
475        .filter(|reading| reading.running(now))
476        .map(|reading| reading.current)
477        .unwrap_or_default();
478    let workers = crate::worker::observe_active(home).and_then(|jobs| {
479        jobs.into_iter()
480            .filter(|job| job.kind == "task")
481            .map(|job| {
482                let request: TaskWorker = serde_json::from_value(job.payload)?;
483                let run = Queue::at(request.queue)
484                    .get(&request.task)
485                    .ok()
486                    .and_then(|task| task.runs.last().cloned())
487                    .unwrap_or_default();
488                Ok(Current {
489                    worker: Some(job.id),
490                    task: request.task,
491                    run,
492                })
493            })
494            .collect::<Result<Vec<_>>>()
495    });
496    match workers {
497        Ok(workers) => {
498            for worker in workers {
499                if !current.iter().any(|claim| {
500                    claim.task == worker.task
501                        && claim.run == worker.run
502                        && claim.worker == worker.worker
503                }) {
504                    current.push(worker);
505                }
506            }
507        }
508        Err(error) => {
509            // This API gates destructive cleanup. Unknown worker ownership
510            // protects every known task/run instead of pretending it is idle.
511            tracing::error!("cannot determine active workers: {error:#}");
512            current.extend(
513                Queue::at(home.join("queue"))
514                    .list()
515                    .into_iter()
516                    .map(|task| Current {
517                        worker: None,
518                        task: task.id,
519                        run: task.runs.last().cloned().unwrap_or_default(),
520                    }),
521            );
522            current.extend(
523                crate::run::list_ids_in(&home.join("runs"))
524                    .into_iter()
525                    .map(|run| Current {
526                        worker: None,
527                        task: String::new(),
528                        run,
529                    }),
530            );
531        }
532    }
533    current
534}
535
536/// Whether a live daemon is working on this run at this moment.
537#[must_use]
538pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
539    current_work(home, now).iter().any(|c| c.run == run)
540}
541
542/// Admission may ignore only this process's confirmed worker reservation.
543/// Keep anonymous/legacy daemon claims and every other worker, even for the
544/// same task. The run's execution lease and process identity are checked by
545/// the caller under the owner lock as well.
546pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
547    // A helper or test may inherit an identity from a different run store.
548    // That identity grants no exception here; retain all ownership evidence.
549    let same_home = std::env::var_os("MAGI_WORKER_HOME")
550        .is_some_and(|worker_home| Path::new(&worker_home) == home);
551    let caller = if same_home {
552        crate::worker::current_job(home)?
553    } else {
554        None
555    }
556    .filter(|job| {
557        job.kind == "task"
558            && job.status == crate::worker::Status::Running
559            && job.pid == Some(std::process::id())
560    });
561    Ok(other_claims_run(
562        &current_work(home, now),
563        run,
564        caller.as_ref().map(|job| job.id.as_str()),
565    ))
566}
567
568fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
569    claims
570        .iter()
571        .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
572}
573
574/// Whether a live daemon is working on a run whose short id is this one.
575///
576/// For a worktree that has no run record to compare against at all -
577/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
578/// id is not available to hand to [`is_working_on`]. The short id is: a run's
579/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
580/// and it is exactly the gap between the daemon claiming a task and
581/// `RunState::new` saving the first `run.json` that this exists to protect -
582/// a run genuinely in flight but invisible to a scan of `runs/`.
583#[must_use]
584pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
585    current_work(home, now)
586        .iter()
587        .any(|c| crate::run::short_of(&c.run) == short)
588}
589
590/// Whether a live daemon is working on this task at this moment.
591#[must_use]
592pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
593    current_work(home, now).iter().any(|c| c.task == task)
594}
595
596/// Remove claim files whose owner is provably dead, or that have simply
597/// outlived `older_than`, and return the task ids swept.
598///
599/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
600/// destructor, and the orphaned `.lock` file would make its task permanently
601/// unclaimable — the backlog would stop for good at exactly the task that was
602/// in flight when the machine went down.
603///
604/// The pid recorded in the lock is the authority whenever it can be read at
605/// all; age is only a fallback for when it cannot be.
606///
607/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
608///   full stop — dead sweeps the lock immediately, regardless of age; alive
609///   protects it, regardless of age. This is what lets a lock be reclaimed in
610///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
611///   before this daemon even started, next to a `queued` task, no longer has
612///   to sit for six hours before anything notices its owner is gone.
613/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
614///   falls back to `older_than`, since there is nothing else to check.
615///
616/// Age must never override a *positive* liveness confirmation. `sweep`
617/// polls concurrently with independently running task workers. A worker may
618/// legitimately run longer than `older_than`; its live pid must still protect
619/// its claim. Age alone must never turn that claim into a second task attempt,
620/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
621/// to a second attempt — two `Runner`s writing the same `run.json` and the
622/// same worktree at once. `pid_alive` answering "alive" for anything it
623/// cannot determine (a live process, a pid this build cannot check, one
624/// under another account) is exactly what keeps that path from ever
625/// firing on a guess.
626///
627/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
628/// output unreadable must not be license to guess, and the risk of an
629/// unparseable lock outliving a genuinely dead owner is bounded by an order
630/// of magnitude above any plausible run rather than by a positive check.
631///
632/// Runs on every poll, not only at startup — a daemon up for days must keep
633/// noticing a lock some other, now-dead, daemon left behind just as readily
634/// as one it trips over on the way up.
635pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
636    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
637}
638
639/// [`sweep_stale_claims`] with its process-query boundary supplied by the
640/// caller. This keeps the lock policy testable where process listing is
641/// unavailable, while production still uses the platform query above.
642fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
643where
644    F: Fn(u32) -> bool,
645{
646    let this_process = std::process::id();
647    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
648        .into_iter()
649        .flatten()
650        .flatten()
651        .map(|e| e.path())
652        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
653        .filter(|p| {
654            match std::fs::read_to_string(p)
655                .ok()
656                .and_then(|body| body.trim().parse::<u32>().ok())
657            {
658                // This process wrote it and is asking the question right
659                // now, so it is definitionally still alive - settled without
660                // spawning a helper process at all.
661                Some(pid) if pid == this_process => false,
662                Some(pid) => !pid_alive(pid),
663                None => p
664                    .metadata()
665                    .and_then(|m| m.modified())
666                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
667                    .is_ok_and(|age| age >= older_than),
668            }
669        })
670        .filter(|p| std::fs::remove_file(p).is_ok())
671        .filter_map(|p| {
672            p.file_stem()
673                .and_then(|s| s.to_str())
674                .map(std::borrow::ToOwned::to_owned)
675        })
676        .collect();
677    swept.sort_unstable();
678    swept
679}
680
681/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
682/// no live daemon's heartbeat naming it? Deterministic — no model call, and
683/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
684/// shown.
685fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
686    task.status == TaskStatus::Running
687        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
688        && !is_working_on_task(home, &task.id, now)
689}
690
691/// Every task [`is_stalled`] right now — "止まったタスク" in
692/// `crate::conduct`'s vocabulary.
693fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
694    queue
695        .list()
696        .into_iter()
697        .filter(|t| is_stalled(t, home, now))
698        .collect()
699}
700
701/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
702/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
703/// `Failed`-and-so-also-runnable: a task that already attempted and lost
704/// belongs in [`finished_tasks`], where the question is a recovery, not a
705/// dependency.
706fn queued_tasks(queue: &Queue) -> Vec<Task> {
707    queue
708        .list()
709        .into_iter()
710        .filter(|t| t.status == TaskStatus::Queued)
711        .collect()
712}
713
714/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
715/// タスク" in `crate::conduct`'s vocabulary.
716fn finished_tasks(queue: &Queue) -> Vec<Task> {
717    queue
718        .list()
719        .into_iter()
720        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
721        .collect()
722}
723
724/// Deterministically resolve `Task::blocked_by`: a dependency task that
725/// reached `Done`, or a question that was answered, is removed — no model
726/// involved, on every poll. An answered question's content is copied onto
727/// the task ([`Task::record_answer`]) before its id is dropped, so it
728/// reaches the next `crate::conduct` prompt and the next run's instruction
729/// (see [`instruction_for`]) rather than only clearing the block.
730///
731/// A `blocked_by` id that names neither an existing task nor an existing
732/// question - `magi task rm` (or an operator by hand) deleted it while this
733/// task was still waiting - is caught before any of that: it can never
734/// become `Done` or `Answered`, so the ordinary loop below would otherwise
735/// leave the task `blocked` forever with nothing to notice. Such a task is
736/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
737/// which puts it in front of `crate::triage::run_once`'s own walk the next
738/// time it runs - see that module's doc for why the choice is "ask a human",
739/// never "assume the missing dependency was satisfied and unblock anyway".
740fn resolve_blockers(queue: &Queue, questions: &Questions) {
741    for listed in queue.list() {
742        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
743            continue;
744        }
745        let Ok(_claim) = queue.claim(&listed.id) else {
746            continue;
747        };
748        let Ok(mut task) = queue.get(&listed.id) else {
749            continue;
750        };
751        if task.status != TaskStatus::Blocked {
752            continue;
753        }
754        // A dependency deleted on purpose is released, not held - and before
755        // the missing check, so a pass that races the delete (or a claim that
756        // made `Queue::remove` skip this task) settles it quietly.
757        let deleted = queue.apply_deleted_blockers(&mut task, questions);
758        if !deleted.is_empty() {
759            record(queue, &mut task);
760            for id in &deleted {
761                queue.note_dependency_deleted(&task, id);
762            }
763            if task.status != TaskStatus::Blocked {
764                continue;
765            }
766        }
767        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
768        if !missing.is_empty() {
769            let language = language_of(&task, Path::new("."));
770            let mut cause = missing.clone();
771            cause.sort();
772            cause.dedup();
773            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
774            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
775                &task.blocked_by,
776                &missing,
777                &language,
778            )));
779            record(queue, &mut task);
780            continue;
781        }
782        // A conductor question nobody answered in time is retired by the
783        // waiter, and nothing else would ever move the task it blocks.
784        if let Some(q) = task.blocked_by.iter().find_map(|id| {
785            let crate::queue::Dependency::Question(full) =
786                crate::queue::dependency(queue, questions, id)
787            else {
788                return None;
789            };
790            questions.get(&full).ok().filter(|q| {
791                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
792            })
793        }) {
794            let language = language_of(&task, Path::new("."));
795            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
796            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
797            record(queue, &mut task);
798            continue;
799        }
800        let mut changed = false;
801        for id in task.blocked_by.clone() {
802            let resolved = crate::queue::dependency(queue, questions, &id);
803            if let crate::queue::Dependency::Task(full) = &resolved {
804                if queue
805                    .get(full)
806                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
807                {
808                    task.unblock(&id);
809                    changed = true;
810                }
811                continue;
812            }
813            if let crate::queue::Dependency::Question(full) = resolved
814                && let Ok(q) = questions.get(&full)
815                && q.status == ask::QuestionStatus::Answered
816            {
817                // The action sweep releases conductor blockers atomically
818                // with their selected operation. A fresh deputy lease must
819                // never leave an answered hold temporarily runnable.
820                if q.node == crate::conduct::NODE
821                    && q.chosen_action().is_some()
822                    && !task.action_applied(&q.id)
823                {
824                    continue;
825                }
826                let answer = match &q.answer {
827                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
828                    None => String::new(),
829                };
830                task.record_answer(q.summary.clone(), answer);
831                task.unblock(&id);
832                changed = true;
833            }
834        }
835        if changed {
836            record(queue, &mut task);
837        }
838    }
839}
840
841/// The `hold_reason` of a task whose conductor question went unanswered.
842fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
843    if crate::lang::is_japanese(language) {
844        format!(
845            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
846            q.short(),
847            q.summary
848        )
849    } else {
850        format!(
851            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
852            q.short(),
853            q.summary
854        )
855    }
856}
857
858/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
859/// for several unrelated reasons, and the waiter must not read them alike.
860#[derive(Debug, Clone, Copy, PartialEq, Eq)]
861pub(crate) enum ActionStanding {
862    /// The answer carries no action: the waiter delivers it as before.
863    NoAction,
864    /// The daemon will apply it (not applied, task idle, current attempt).
865    Pending,
866    /// Already applied (`Task::actions_applied`): the daemon has acted, so
867    /// delivering the word to the old seat would run it beside the new work.
868    Applied,
869    /// The question is about an earlier attempt than the task's latest.
870    Stale,
871    /// The task is running / blocked / done: the daemon defers for now.
872    Busy,
873}
874
875impl ActionStanding {
876    /// The daemon has acted or will act: the waiter must not deliver.
877    pub(crate) fn daemon_owns(self) -> bool {
878        matches!(self, Self::Pending | Self::Applied | Self::Stale)
879    }
880}
881
882/// Classify `q`'s chosen action against `task`. `Stale` is judged before
883/// `Busy`: a question about an earlier attempt must be stopped even while a
884/// newer competition is running.
885pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
886    if q.chosen_action().is_none() {
887        ActionStanding::NoAction
888    } else if task.action_applied(&q.id) {
889        ActionStanding::Applied
890    } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
891        ActionStanding::Stale
892    } else if matches!(
893        task.status,
894        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
895    ) {
896        ActionStanding::Busy
897    } else {
898        ActionStanding::Pending
899    }
900}
901
902/// What [`decide_action`] concluded about one answered question.
903#[derive(Debug, Clone, PartialEq, Eq)]
904enum ActionDecision {
905    /// Nothing to do now (no action, already applied, or the task is busy).
906    Skip,
907    /// Continue the named run instead of competing again.
908    Resume(String),
909    /// Requeue as a fresh competition.
910    Requeue,
911    /// Hold the task by explicit operator choice.
912    Hold,
913    /// Close the task as done.
914    Done,
915    /// The question is about an earlier attempt than the task's latest; it
916    /// is recorded as handled and changes nothing.
917    Stale,
918    /// The action cannot be carried out; hold the task and say why. Never
919    /// falls back to something else, because the operator chose this one.
920    Refuse(String),
921}
922
923/// Decide what the choice answered on `q` means for `task`. `load` reads a
924/// run's state, as with [`unfinished_run_with`]. `home` must name that same
925/// store for driver leases and question checkpoints.
926///
927/// `Resume` only fires on the task's *latest* run, and only while that run
928/// could actually make progress ([`RunStatus::resumable`], not released, review
929/// budget left); an answer naming anything else is refused rather than
930/// reinterpreted as a fresh competition.
931fn decide_action<F>(
932    home: &Path,
933    task: &Task,
934    q: &ask::Question,
935    p: &Phrases,
936    load: F,
937) -> ActionDecision
938where
939    F: FnOnce(&str) -> Result<RunState>,
940{
941    let Some(action) = q.chosen_action() else {
942        return ActionDecision::Skip;
943    };
944    if task.action_applied(&q.id)
945        || matches!(
946            task.status,
947            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
948        )
949    {
950        return ActionDecision::Skip;
951    }
952    // A question about an earlier attempt must not act on a newer one. A
953    // conductor question is keyed by the task id, not a run, so it is exempt.
954    if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
955        return ActionDecision::Stale;
956    }
957    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
958    let stopping = q.node == land::APPROVAL_NODE
959        && q.resolution()
960            .as_deref()
961            .is_some_and(crate::merge_decision::stops);
962    // An answer is the owner's decision as of when it was given: a manual hold
963    // placed before it (even after the question was asked) was seen and
964    // overruled by it, while a hold or release after it supersedes it.
965    let decision_at = q.answered_at.unwrap_or(q.asked_at);
966    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
967        return if repair || stopping {
968            ActionDecision::Refuse(format!(
969                "{} 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 {}`",
970                if repair { "repair" } else { "stop" },
971                q.id,
972                q.run,
973                task.id
974            ))
975        } else {
976            ActionDecision::Stale
977        };
978    }
979    match action {
980        a if a.maintenance() => ActionDecision::Skip,
981        ask::ChoiceAction::ResumeRun { .. }
982        | ask::ChoiceAction::ReleaseTask { .. }
983        | ask::ChoiceAction::RerunChecks { .. }
984        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
985        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
986        ask::ChoiceAction::Hold => ActionDecision::Hold,
987        ask::ChoiceAction::Done => ActionDecision::Done,
988        ask::ChoiceAction::Resume { run } => {
989            if task.runs.last() != Some(run) {
990                return ActionDecision::Refuse((p.resume_not_latest)(
991                    q.short(),
992                    ask::short_id(run),
993                ));
994            }
995            match load(run) {
996                Ok(s) if stopping => {
997                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
998                        || !s
999                            .land_approval
1000                            .as_ref()
1001                            .is_some_and(|binding| binding.question == q.id)
1002                    {
1003                        ActionDecision::Stale
1004                    } else if s.liveness_under(home, false) == Liveness::Live {
1005                        ActionDecision::Skip
1006                    } else if s.status == RunStatus::Landing
1007                        && !s.released()
1008                        && s.retired_to.is_none()
1009                    {
1010                        ActionDecision::Resume(run.clone())
1011                    } else {
1012                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1013                    }
1014                }
1015                Ok(s)
1016                    if q.node == land::APPROVAL_NODE
1017                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1018                {
1019                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1020                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1021                    {
1022                        // A live/manual driver already consumed or superseded
1023                        // this answer. Do not hold its fresh approval wait.
1024                        ActionDecision::Stale
1025                    } else if s.liveness_under(home, false) == Liveness::Live {
1026                        ActionDecision::Skip
1027                    } else if s.status != RunStatus::Landing
1028                        || s.released()
1029                        || s.reviews.is_empty()
1030                        || !implementers_match(task, &s)
1031                        || !s
1032                            .land_approval
1033                            .as_ref()
1034                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1035                    {
1036                        ActionDecision::Refuse(format!(
1037                            "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",
1038                            q.id, run, run
1039                        ))
1040                    } else {
1041                        ActionDecision::Resume(run.clone())
1042                    }
1043                }
1044                Ok(s) if s.liveness_under(home, false) == Liveness::Live => {
1045                    ActionDecision::Refuse("run already has a live driver".into())
1046                }
1047                Ok(s) => match crate::handover::resume_refusal_under(&s, Some(home)) {
1048                    None => ActionDecision::Resume(run.clone()),
1049                    Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1050                        q.short(),
1051                        ask::short_id(run),
1052                        &reason.diagnostic(&s),
1053                    )),
1054                },
1055                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1056                    q.short(),
1057                    ask::short_id(run),
1058                    &format!("{e:#}"),
1059                )),
1060            }
1061        }
1062    }
1063}
1064
1065/// The fixed prose the daemon writes into [`Task::last_error`] and
1066/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1067/// `triage::Wording` and `land::Words`: only English and Japanese are
1068/// translated, anything else falls back to English.
1069///
1070/// Rendered when the reason is *generated*, so a reason keeps the language it
1071/// was written in if the setting changes later. The notification frame
1072/// (`Task <id> is held:`) is not here and stays English.
1073///
1074/// Deliberately **not** translated, because other code reads them back by
1075/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1076/// and `gate red`. IDs, node names, paths and external error text are embedded
1077/// as they are.
1078struct Phrases {
1079    /// `{}` = status label, then the detail.
1080    graph_stopped: fn(&str, &str) -> String,
1081    quorum_lost: &'static str,
1082    /// Followed by the seats' names.
1083    quota_took_out: &'static str,
1084    /// Followed by the status label.
1085    run_ended: &'static str,
1086    /// Followed by the question's short id.
1087    waiting_for_answer: &'static str,
1088    recovered_running: &'static str,
1089    no_run_to_recover: &'static str,
1090    could_not_start: &'static str,
1091    resume_not_latest: fn(&str, &str) -> String,
1092    resume_cannot_progress: fn(&str, &str, &str) -> String,
1093    resume_unreadable: fn(&str, &str, &str) -> String,
1094    /// A takeover refusal: the operator-facing text. English is the error's own
1095    /// `Display`; a translation keeps the machine detail apart in parentheses.
1096    handover_refused: fn(&crate::handover::Refused) -> String,
1097    /// Appended to a refused handover's hold reason (leading space included).
1098    handover_hint: &'static str,
1099    /// (seats that never answered, review rounds) for the review loop's
1100    /// "refusing to call it clean" stop.
1101    reviewers_never_answered: fn(usize, usize) -> String,
1102}
1103
1104const PHRASES_EN: Phrases = Phrases {
1105    graph_stopped: |status, detail| {
1106        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1107    },
1108    quorum_lost: "the judging panel lost its quorum",
1109    quota_took_out: "; quota took out ",
1110    run_ended: "run ended ",
1111    waiting_for_answer: " - waiting for operator answer to question ",
1112    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1113    no_run_to_recover: "task was `running` with no live daemon and no readable \
1114                        run to recover; held for a human to check what happened",
1115    could_not_start: "could not start the run: ",
1116    resume_not_latest: |q, run| {
1117        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1118    },
1119    resume_cannot_progress: |q, run, reason| {
1120        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1121    },
1122    resume_unreadable: |q, run, e| {
1123        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1124    },
1125    handover_refused: |r| r.to_string(),
1126    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1127    reviewers_never_answered: |missing, rounds| {
1128        format!(
1129            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1130             refusing to call it clean"
1131        )
1132    },
1133};
1134
1135const PHRASES_JA: Phrases = Phrases {
1136    graph_stopped: |status, detail| {
1137        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1138    },
1139    quorum_lost: "審査パネルが定足数を失いました",
1140    quota_took_out: "。クォータで脱落: ",
1141    run_ended: "run 終了: ",
1142    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1143    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1144    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1145                        何が起きたか人が確認するため保留にしました",
1146    could_not_start: "run を開始できませんでした: ",
1147    resume_not_latest: |q, run| {
1148        format!(
1149            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1150        )
1151    },
1152    resume_cannot_progress: |q, run, reason| {
1153        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1154    },
1155    resume_unreadable: |q, run, e| {
1156        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1157    },
1158    handover_refused: |r| {
1159        use crate::handover::Refused;
1160        match r {
1161            Refused::Foreign { branch, path, why } => format!(
1162                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1163                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1164                 から、やり直してください(詳細: {why})"
1165            ),
1166            Refused::Unsafe { branch, path, why } => format!(
1167                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1168                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1169                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1170            ),
1171            Refused::ReleaseFailed { branch, path, run } => format!(
1172                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1173                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1174                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1175            ),
1176        }
1177    },
1178    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1179    reviewers_never_answered: |missing, rounds| {
1180        format!(
1181            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1182             クリーンとは認めません"
1183        )
1184    },
1185};
1186
1187fn phrases(language: &str) -> &'static Phrases {
1188    if crate::lang::is_japanese(language) {
1189        &PHRASES_JA
1190    } else {
1191        &PHRASES_EN
1192    }
1193}
1194
1195/// The language of the repository a task belongs to, read best-effort for the
1196/// paths that have no run (and so no config of their own) to ask. An unreadable
1197/// config is English, not an error: a hold reason must still get written.
1198fn language_of(task: &Task, fallback: &Path) -> String {
1199    crate::lang::of_repo(&repo_for(task, fallback))
1200}
1201
1202/// The task an answered question speaks for: the one whose runs include the
1203/// question's run, or - for a conductor question, filed under the task's own
1204/// id - the task with that id.
1205pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1206    if q.node == crate::conduct::NODE {
1207        return tasks.iter().find(|t| t.id == q.run);
1208    }
1209    tasks.iter().find(|t| t.runs.contains(&q.run))
1210}
1211
1212/// Legacy conductor prose never becomes a maintenance command by inference.
1213/// Replace unsupported open labels under the question lock before dispatch.
1214fn repair_choice_offers(questions: &Questions) {
1215    for q in questions.list().into_iter().filter(|q| {
1216        q.status.open()
1217            && q.node == crate::conduct::NODE
1218            && q.choices
1219                .iter()
1220                .any(|c| crate::choice_effect::describe(q, c).is_none())
1221    }) {
1222        let _ = questions.update(&q.id, |current| {
1223            if current.status.open() {
1224                crate::choice_effect::executable_conductor(current);
1225                if let Some(deputy) = &mut current.deputy {
1226                    deputy.brief = crate::deputy::brief(
1227                        &current.run,
1228                        &current.detail,
1229                        &current.choices,
1230                        &current.actions,
1231                    );
1232                }
1233            }
1234            Ok(())
1235        });
1236    }
1237}
1238
1239/// Apply answered typed choices. Only the daemon calls this in production;
1240/// deputies settle the question and never execute its actions.
1241pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1242    apply_maintenance_choices(queue, questions, home).await;
1243    apply_task_choice_actions(queue, questions, home);
1244}
1245
1246/// Apply bounded maintenance effects independently of question ownership: a
1247/// release watcher need not have a queue task, and a predecessor is another run.
1248async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1249    for q in questions.list() {
1250        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1251            continue;
1252        };
1253        // Receipt paths use question IDs, whose format is independent of run
1254        // IDs. Apply the question store's filename safety rule to both eras.
1255        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1256            continue;
1257        }
1258        let dir = home.join("choice-actions");
1259        if std::fs::create_dir_all(&dir).is_err() {
1260            continue;
1261        }
1262        let Ok(lock) = std::fs::OpenOptions::new()
1263            .create(true)
1264            .truncate(false)
1265            .write(true)
1266            .open(dir.join(format!("{}.lock", q.id)))
1267        else {
1268            continue;
1269        };
1270        if crate::pr_head::try_lock_file(&lock).is_err() {
1271            continue;
1272        }
1273        let fresh = !home
1274            .join("choice-actions")
1275            .join(format!("{}.json", q.id))
1276            .exists();
1277        let result = async {
1278            let receipt = dir.join(format!("{}.json", q.id));
1279            if receipt.exists() {
1280                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1281                anyhow::ensure!(
1282                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1283                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1284                );
1285                return Ok::<_, anyhow::Error>(());
1286            }
1287            // Never retry an uncertain external effect. The receipt is written
1288            // before calling gh, exactly like release_watch's rerun record.
1289            let record = |status: &str| -> anyhow::Result<()> {
1290                let tmp = receipt.with_extension("tmp");
1291                std::fs::write(
1292                    &tmp,
1293                    serde_json::to_vec(&serde_json::json!({
1294                        "action": action, "status": status,
1295                    }))?,
1296                )?;
1297                std::fs::rename(tmp, &receipt)?;
1298                Ok(())
1299            };
1300            let applied = async {
1301                match action {
1302                    ask::ChoiceAction::ResumeRun { run } => {
1303                        crate::resume::validate(home, run)?;
1304                        record("started")?;
1305                        let decided = q.answered_at.unwrap_or(q.asked_at);
1306                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1307                            crate::resume::validate_unqueued(home, run)?;
1308                            crate::resume::start(home, run.clone()).await?;
1309                        }
1310                    }
1311                    ask::ChoiceAction::ReleaseTask {
1312                        task,
1313                        held_at,
1314                        reason,
1315                    } => {
1316                        anyhow::ensure!(
1317                            queue.resolve_id(task)? == *task,
1318                            "task action requires an exact task ID"
1319                        );
1320                        let _claim = queue.claim(task)?;
1321                        let mut task = queue.get(task)?;
1322                        if task.action_applied(&q.id) {
1323                            return Ok(());
1324                        }
1325                        // Filing this conductor question temporarily wraps the
1326                        // original hold in a Blocked state. Restore only that
1327                        // exact blocker on the local copy before checking the
1328                        // hold binding; unrelated waits never authorize release.
1329                        if q.node == crate::conduct::NODE
1330                            && q.run == task.id
1331                            && task.status == TaskStatus::Blocked
1332                            && task.blocked_from == Some(TaskStatus::Held)
1333                            && task.blocked_by.as_slice() == [q.id.as_str()]
1334                        {
1335                            task.unblock(&q.id);
1336                        }
1337                        anyhow::ensure!(
1338                            task.status == TaskStatus::Held
1339                                && task.held_at == Some(*held_at)
1340                                && task.hold_reason.as_deref() == reason.as_deref()
1341                                && task
1342                                    .operator_decided_at
1343                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1344                            "task no longer has the hold this question names"
1345                        );
1346                        task.release_operator("choice", Some(&q.id));
1347                        task.mark_action_applied(&q.id);
1348                        queue.put(&mut task)?;
1349                    }
1350                    ask::ChoiceAction::AbandonRun { run } => {
1351                        record("started")?;
1352                        crate::driver::abandon_proven_dead(home, run)?;
1353                    }
1354                    ask::ChoiceAction::RerunChecks {
1355                        repo,
1356                        pr,
1357                        head,
1358                        runs,
1359                    } => {
1360                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1361                            .await?;
1362                    }
1363                    _ => unreachable!(),
1364                }
1365                Ok::<_, anyhow::Error>(())
1366            }
1367            .await;
1368            match applied {
1369                Ok(()) => record("applied"),
1370                Err(e) => {
1371                    record(&format!("refused or failed: {e:#}"))?;
1372                    Err(e)
1373                }
1374            }
1375        }
1376        .await;
1377        // Retire the originating blocker as well as the target operation.
1378        // A foreign resume leaves its issuer held instead of competing beside
1379        // the execution just started. Other successful maintenance lets the
1380        // original task retry its normal, guarded path.
1381        if home
1382            .join("choice-actions")
1383            .join(format!("{}.json", q.id))
1384            .exists()
1385            && let Some(listed) = task_of_question(&queue.list(), &q)
1386            && !listed.action_applied(&q.id)
1387            && let Ok(_claim) = queue.claim(&listed.id)
1388            && let Ok(mut origin) = queue.get(&listed.id)
1389        {
1390            if !origin.operator_held()
1391                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1392                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1393            {
1394                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1395                    origin.hold_machine(Some(format!(
1396                        "Maintenance choice {} settled; inspect its target before releasing this task",
1397                        q.id
1398                    )));
1399                } else {
1400                    origin.unblock(&q.id);
1401                }
1402            }
1403            origin.mark_action_applied(&q.id);
1404            let _ = queue.put(&mut origin);
1405        }
1406        if let Err(e) = result
1407            && fresh
1408        {
1409            notices::raise_in(
1410                home,
1411                Notice::warn(
1412                    &format!("action:{}", q.id),
1413                    format!("Choice action {} was not completed: {e:#}", q.id),
1414                )
1415                .link(if q.run_names_task() {
1416                    Link::Task { id: q.run.clone() }
1417                } else {
1418                    Link::Run { id: q.run.clone() }
1419                }),
1420            );
1421        }
1422    }
1423}
1424
1425/// Rerun the named failed workflow runs of a pull request, each at most once
1426/// per `request` (a question id, or a chat operation identity). The head,
1427/// lifecycle and failed state are re-read from the forge first; `started` is
1428/// called once those checks pass and before the first external call, and the
1429/// ledger entry is written before every `gh` call, so an uncertain result is
1430/// never repeated automatically.
1431pub(crate) async fn rerun_checks_once(
1432    home: &Path,
1433    request: &str,
1434    repo: &Path,
1435    pr: &str,
1436    head: &str,
1437    runs: &[String],
1438    started: impl FnOnce() -> anyhow::Result<()>,
1439) -> anyhow::Result<()> {
1440    use crate::release_watch::{GhForge, ReleaseForge};
1441    anyhow::ensure!(
1442        !runs.is_empty()
1443            && runs.len() <= 20
1444            && runs
1445                .iter()
1446                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1447            && !pr.starts_with('-'),
1448        "invalid rerun targets"
1449    );
1450    let snap = GhForge.snapshot(repo, pr).await?;
1451    anyhow::ensure!(
1452        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1453        "pull request head or lifecycle changed"
1454    );
1455    anyhow::ensure!(
1456        runs.iter().all(|r| snap
1457            .checks
1458            .iter()
1459            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1460        "named workflow is no longer failed on this pull request"
1461    );
1462    started()?;
1463    let dir = home.join("choice-actions");
1464    std::fs::create_dir_all(&dir)?;
1465    let rerun_lock = std::fs::OpenOptions::new()
1466        .create(true)
1467        .truncate(false)
1468        .write(true)
1469        .open(dir.join("reruns.lock"))?;
1470    crate::pr_head::try_lock_file(&rerun_lock)?;
1471    let ledger = dir.join("reruns.json");
1472    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1473        serde_json::from_slice(&std::fs::read(&ledger)?)?
1474    } else {
1475        Default::default()
1476    };
1477    for run in runs {
1478        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1479        if !recorded.insert(key) {
1480            continue;
1481        }
1482        let tmp = ledger.with_extension("tmp");
1483        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1484        std::fs::rename(tmp, &ledger)?;
1485        GhForge.rerun(repo, run).await?;
1486    }
1487    Ok(())
1488}
1489
1490/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1491///
1492/// Runs on every poll before the conductor looks at the queue. The task is
1493/// re-read under its claim, so a task somebody completed or held by hand in
1494/// the meantime is judged on what it is now. `Resume` releases the task and
1495/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1496/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1497/// ordinary `unfinished_run` logic resumes that same run.
1498pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1499    let tasks = queue.list();
1500    for q in questions.list() {
1501        // Dismissal is committed by the question writer, never a resume.
1502        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1503            continue;
1504        }
1505        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1506            continue;
1507        }
1508        let Some(listed) = task_of_question(&tasks, &q) else {
1509            if q.node == land::APPROVAL_NODE
1510                && q.resolution().as_deref().is_some_and(|choice| {
1511                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1512                })
1513            {
1514                notices::raise_in(
1515                    home,
1516                    Notice::warn(
1517                        &format!("repair-owner:{}", q.id),
1518                        format!(
1519                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1520                            q.run, q.run
1521                        ),
1522                    ).link(Link::Run { id: q.run.clone() }),
1523                );
1524            }
1525            continue;
1526        };
1527        if listed.action_applied(&q.id) {
1528            continue;
1529        }
1530        let Ok(_claim) = queue.claim(&listed.id) else {
1531            continue;
1532        };
1533        let Ok(mut task) = queue.get(&listed.id) else {
1534            continue;
1535        };
1536        // Work only on this local copy until the action can be committed.
1537        // In particular, a fresh lease below leaves the persisted task blocked.
1538        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1539            let blockers: Vec<_> = task
1540                .blocked_by
1541                .iter()
1542                .filter(|id| {
1543                    crate::queue::dependency(queue, questions, id)
1544                        == crate::queue::Dependency::Question(q.id.clone())
1545                })
1546                .cloned()
1547                .collect();
1548            if !blockers.is_empty() {
1549                for id in blockers {
1550                    task.unblock(&id);
1551                }
1552                let answer = match &q.answer {
1553                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1554                    None => String::new(),
1555                };
1556                task.record_answer(q.summary.clone(), answer);
1557            }
1558        }
1559        let language = language_of(&task, Path::new("."));
1560        let decision = decide_action(home, &task, &q, phrases(&language), |id| {
1561            RunState::load_under(id, home)
1562        });
1563        let ran = matches!(
1564            decision,
1565            ActionDecision::Resume(_)
1566                | ActionDecision::Requeue
1567                | ActionDecision::Hold
1568                | ActionDecision::Done
1569        );
1570        if ran && asker_may_still_read(questions, &q, home) {
1571            // The asking process or its seat can still take the word; act
1572            // once it has gone quiet. Bound on the remaining window: the
1573            // check is not atomic with the write below, so an asker that
1574            // takes the word in between (at most one poll, never more than
1575            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1576            // and `Task::actions_applied` under the claim keeps the action to
1577            // one application. The waiter does not deliver an answer that
1578            // carries an action (`waiter::decide_owned`), so it cannot race.
1579            continue;
1580        }
1581        let done = matches!(decision, ActionDecision::Done);
1582        match decision {
1583            ActionDecision::Skip => continue,
1584            ActionDecision::Resume(run) => {
1585                task.release_operator("choice", Some(&q.id));
1586                task.resume_override = Some(crate::queue::OperatorResume {
1587                    question_id: q.id.clone(),
1588                    at: Timestamp::now(),
1589                    conductor_rehold: None,
1590                    forced: true,
1591                    pinned_run: Some(run),
1592                });
1593            }
1594            ActionDecision::Stale => {}
1595            ActionDecision::Requeue => {
1596                task.release_operator("choice-requeue", Some(&q.id));
1597                task.requeue();
1598            }
1599            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1600            ActionDecision::Done => task.succeed(),
1601            ActionDecision::Refuse(why) => {
1602                if task.operator_held() {
1603                    // A rejected answer does not release the operator's hold
1604                    // or reclassify it as recoverable by the conductor.
1605                    task.hold_reason = Some(match task.hold_reason.take() {
1606                        Some(reason) => format!("{reason}\n\n{why}"),
1607                        None => why,
1608                    });
1609                } else {
1610                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1611                    task.hold_machine(Some(why));
1612                }
1613                notices::raise(
1614                    Notice::warn(
1615                        &format!("action:{}", q.id),
1616                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1617                    )
1618                    .link(Link::Task {
1619                        id: task.id.clone(),
1620                    }),
1621                );
1622            }
1623        }
1624        task.mark_action_applied(&q.id);
1625        // The applied id travels with the transition, so a failed save loses
1626        // neither and the answer is acted on at the next poll.
1627        record(queue, &mut task);
1628        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1629            supersede_prior_runs(&task, home);
1630        }
1631        // Delivery is only a note of who has read the answer; the task's own
1632        // mark above is the authority. Best effort.
1633        let _ = questions.update(&q.id, |r| {
1634            r.answer_delivered = true;
1635            Ok(())
1636        });
1637    }
1638}
1639
1640/// Whether something may still read the answer to `q`: a fresh lease, or the
1641/// asking seat still listed as active in its run (its CLI can outlive the
1642/// `magi ask` that was killed).
1643fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1644    let now = Timestamp::now();
1645    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1646        return true;
1647    }
1648    q.node != crate::conduct::NODE
1649        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1650            s.seats_active()
1651                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1652        })
1653}
1654
1655/// Retire an unanswered conductor question after its task no longer refers to
1656/// it. Conductor questions use the task id in `Question::run`, so run-based
1657/// cleanup cannot observe a manual release or completion.
1658///
1659/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1660/// own question also carries a `run`, and a run id that happens to collide
1661/// with some task's id is not this loop's business — only a conductor
1662/// question actually uses the task id that way. One `Questions::list()` scan
1663/// is taken up front and matched against the in-memory task set, rather than
1664/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1665fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1666    let tasks = queue.list();
1667    let by_id: std::collections::BTreeMap<&str, &Task> =
1668        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1669    let referenced: Vec<&str> = tasks
1670        .iter()
1671        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1672        .collect();
1673
1674    for mut question in questions.list() {
1675        if !question.status.open() || question.node != crate::conduct::NODE {
1676            continue;
1677        }
1678        // Keep questions a task still names, including when the reference
1679        // moved to a dependent task.
1680        // Preserve even ambiguous references: retiring a possibly referenced
1681        // question is unsafe until the operator disambiguates it.
1682        if referenced
1683            .iter()
1684            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1685        {
1686            continue;
1687        }
1688        let Some(task) = by_id.get(question.run.as_str()) else {
1689            continue;
1690        };
1691        question.abandon(format!(
1692            "task {} no longer waits for this answer",
1693            task.short()
1694        ));
1695        if let Err(e) = questions.put(&mut question) {
1696            tracing::warn!(
1697                "could not retire question {} for task {}: {e:#}",
1698                question.short(),
1699                task.short()
1700            );
1701        }
1702    }
1703}
1704
1705/// What a finished run tells the queue about the task it came from.
1706///
1707/// A struct rather than a fourth and fifth boolean argument: the two flags
1708/// answer different questions about the same run, and a call site passing
1709/// `(…, true, false)` is one transposition away from refunding attempts
1710/// forever.
1711#[derive(Debug, Clone, Copy)]
1712pub struct Verdict {
1713    /// Where the graph stopped.
1714    pub status: RunStatus,
1715    /// The run opened a pull request.
1716    pub left_pr: bool,
1717    /// At least one seat was lost to a rate limit.
1718    pub quota_hit: bool,
1719    /// The run parked at a node boundary because it was asked to.
1720    pub parked: bool,
1721    /// The run never produced a single candidate a judge could look at.
1722    ///
1723    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1724    /// still have another candidate worth judging, in which case the loss was
1725    /// not the reason nothing came of the run. This is `true` only when the
1726    /// implement wave ended with nothing viable at all.
1727    pub no_viable_candidates: bool,
1728}
1729
1730/// Record a finished run against the task it came from.
1731///
1732/// Kept pure and separate from the loop because this mapping *is* the retry
1733/// policy, and a policy that can only be exercised by spawning a graph is a
1734/// policy nobody checks. The table:
1735///
1736/// | run status                           | task becomes        | attempt spent |
1737/// |---------------------------------------|---------------------|---------------|
1738/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1739/// | `Merged`, `Ready`                      | `Done`               | yes          |
1740/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1741/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1742/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1743/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1744/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1745/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1746/// | `Blocked` with a PR                    | `Held`               | yes          |
1747/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1748/// | `VerifiedNoop`                          | `Held`               | yes          |
1749/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1750///
1751/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1752/// deliberately: every candidate agreeing there is nothing to write is not a
1753/// machine fact about a rate limit, it is an unverified claim about the
1754/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1755/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1756/// claim could be wrong (a misread instruction, a stale check), and closing
1757/// the task automatically on an implementer's say-so would be the exact
1758/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1759/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1760/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1761/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1762/// claim regardless of whether the one already-spent attempt is refunded, and
1763/// [`Task::release`] resets the count to zero anyway the moment a human looks
1764/// at the evidence and lets it run again.
1765///
1766/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1767/// twice, together. A quorum lost to rate limits is a property of the machine
1768/// and not of the task, so the attempt is refunded and a reset quota picks
1769/// the work up where it stopped — and that is just as true when every
1770/// implement seat lost the same race and `after_implement` bails with nothing
1771/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1772/// machine fact. The `no_viable_candidates` guard is what keeps that row
1773/// narrow: a `Failed` run that produced a real candidate which then lost for
1774/// some other reason still spends the attempt, exactly like the quorum lost
1775/// to judges that answered with the wrong shape is ordinary flakiness, and
1776/// refunding *that* takes the bound off the retry loop entirely: run e633
1777/// stalled with `quota: []` after two judges wrote unusable JSON, was
1778/// refunded, and the next attempt paid for a fresh hour-long implement wave
1779/// before it could fail the same way. `max_attempts` exists precisely so
1780/// that cannot repeat forever.
1781///
1782/// A non-terminal status means `execute` returned while the graph was still
1783/// mid-flight, which is a bug rather than a verdict; it is treated as a
1784/// failure so that a task cannot loop on it either.
1785///
1786/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1787/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1788pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1789    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1790}
1791
1792/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1793fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1794    // A parked run is the operator's own doing, and its work is intact on
1795    // disk. The task goes back in line with its attempt refunded so the next
1796    // loop resumes the same run - which `one_task` prefers over competing
1797    // again - and so that swapping the binary a few times cannot exhaust a
1798    // budget meant for agents that actually misbehaved.
1799    if verdict.parked {
1800        task.park(detail);
1801        return;
1802    }
1803    match verdict.status {
1804        RunStatus::Merged | RunStatus::Ready
1805            if task.pr_recovery.as_ref().is_some_and(|s| {
1806                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1807            }) =>
1808        {
1809            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()));
1810        }
1811        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1812        RunStatus::AlreadyInBase => task.already_landed(detail),
1813        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1814        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1815            task.stall(detail)
1816        }
1817        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1818        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1819        RunStatus::Blocked => task.fail(detail, max_attempts),
1820        RunStatus::VerifiedNoop => task.handed_off(detail),
1821        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1822    }
1823}
1824
1825/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1826/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1827/// itself has actually finished *and* its own last attempt is provably why:
1828/// this loads that run and requires `Merged`/`Ready` before touching
1829/// anything earlier in `runs`, since `Task::succeed` can also be called
1830/// directly on a task whose last attempt never landed at all.
1831///
1832/// Called right after whatever call set `task.status` to
1833/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1834/// `reclaim`'s, but also every other place a task can be closed by hand
1835/// without the loop ever settling it itself: `magi task done`
1836/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1837/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1838/// GitHub merge, say, exactly the workflow this repository's own
1839/// "Landing a run's winner by hand" documents — is just as much "this task's
1840/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1841/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1842/// forever, which is the exact backlog this status exists to clear. `pub`
1843/// for those two out-of-module callers; everything else about this stays
1844/// internal bookkeeping.
1845///
1846/// A run something is still actually driving is left alone: a
1847/// task cannot be `Done` while one of its *own* attempts is still in flight,
1848/// so a live one at this point can only be an unrelated process — a manual
1849/// `--resume` of this old, now-moot run — and rewriting under it would just
1850/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1851/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1852/// pair `run_report`/`run_detail` use for the same question elsewhere:
1853/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1854/// --resume` invoked by hand outside it, which `liveness` also checks via
1855/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1856/// (already terminal in some other way, or itself mid-run) is left untouched
1857/// too.
1858///
1859/// Best-effort, like the rest of this module's bookkeeping: a load or save
1860/// failure here is a `tracing::warn`, not a failed settle, and the next time
1861/// this same task's completion is recorded — or a daemon restart replays
1862/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1863/// separate reconciliation pass; if that gap ever matters in practice, one
1864/// can be added then.
1865///
1866/// `home` is a parameter, not the process-global [`crate::run::home`], for
1867/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1868/// calls this with `ui.home`, which is `crate::run::home()` in a real
1869/// process but a fixture's own directory under test — falling through to
1870/// the global there would read and write through whichever home some other
1871/// test in the same binary happened to pin into that `OnceLock` first, not
1872/// the run this call actually means.
1873pub fn supersede_prior_runs(task: &Task, home: &Path) {
1874    let now = Timestamp::now();
1875    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1876    // right behind a `Merged`/`Ready` verdict) from one set directly by
1877    // `magi task done`/its web equivalent/the conductor on a task whose last
1878    // recorded attempt never actually landed - that requires reading the
1879    // run itself, which is exactly what this does before trusting anything
1880    // in `runs` is safe to relabel.
1881    let last_run_succeeded = task
1882        .runs
1883        .last()
1884        .and_then(|id| RunState::load_under(id, home).ok())
1885        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1886    for id in task.superseded_attempts(last_run_succeeded) {
1887        let mut state = match RunState::load_under(id, home) {
1888            Ok(s) => s,
1889            Err(e) => {
1890                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1891                continue;
1892            }
1893        };
1894        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1895            continue;
1896        }
1897        let daemon_claims = is_working_on(home, id, now);
1898        if state.liveness(daemon_claims) == Liveness::Live {
1899            continue;
1900        }
1901        state.status = RunStatus::Superseded;
1902        if let Err(e) = state.save_under(home) {
1903            tracing::warn!("could not mark run {id} superseded: {e:#}");
1904        }
1905    }
1906}
1907
1908/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1909/// finish the moment it was called, because one of its earlier attempts was
1910/// still live then - a `magi run --resume` invoked by hand on an old run,
1911/// most likely.
1912///
1913/// That skip is correct at the time (rewriting under a run something is
1914/// still actively saving would just be undone), but a task only ever
1915/// reaches `Done` once, so without this nothing would ever look at it
1916/// again: if that manual process later ends anywhere other than
1917/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1918/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1919/// backlog this status exists to clear. Called on the same idle-only
1920/// cadence as [`janitor`], next to it rather than folded into it: this
1921/// walks `queue` and `janitor` never otherwise needs one.
1922///
1923/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1924/// more than one attempt, every pass: each call is a handful of local file
1925/// reads bounded by that task's own attempt count, the same order of cost
1926/// [`clean::fold_due`] already pays scanning every run on disk on the same
1927/// cadence, and a task already fully resolved costs one failed liveness
1928/// check turned no-op the moment its lingering attempt is no longer live.
1929fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1930    for task in queue.list() {
1931        if task.status != TaskStatus::Done || task.runs.len() < 2 {
1932            continue;
1933        }
1934        supersede_prior_runs(&task, home);
1935    }
1936}
1937
1938/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1939/// task ends up held.
1940///
1941/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1942/// dead daemon never got back to) share this, so the two cannot drift into
1943/// disagreeing about which held tasks get a diagnostic.
1944fn settle_and_diagnose(
1945    task: &mut Task,
1946    verdict: Verdict,
1947    detail: &str,
1948    max_attempts: usize,
1949    state: &RunState,
1950) {
1951    let p = phrases(&state.config.graph.language);
1952    // Shared by normal completion and crash recovery, under the task claim.
1953    // No new attempt can own the task until the old driver has exited.
1954    if let Some(d) = &state.merge_decision {
1955        use crate::merge_decision as md;
1956        if task.runs.last().is_some_and(|id| id != &state.id) {
1957            return;
1958        }
1959        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1960            task.succeed();
1961        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1962            if state.liveness(false) != Liveness::Dead {
1963                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1964                return;
1965            }
1966            let replacement = md::Replacement {
1967                question: d.question.clone(),
1968                run: state.id.clone(),
1969                pr: d.target.pr.clone(),
1970                agent: agent.to_owned(),
1971                context: format!(
1972                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1973                    d.target.pr,
1974                    state.id,
1975                    serde_json::to_string(&state.reviews).unwrap_or_default()
1976                ),
1977            };
1978            task.requeue();
1979            task.pr_recovery = None;
1980            task.review_of = None;
1981            task.replacement = Some(replacement);
1982        } else {
1983            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1984                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1985            } 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())) }));
1986        }
1987        task.mark_action_applied(&d.question);
1988        if let Some(pass) = state.passes.last() {
1989            task.record_pass_at(
1990                &state.id,
1991                pass.index,
1992                Some(pass.started_at),
1993                task.attempts,
1994                None,
1995            );
1996        }
1997        return;
1998    }
1999    if let Some(replacement) = &task.replacement
2000        && !state.parked
2001        && state.resource_block.is_none()
2002        && (state.viable().is_empty()
2003            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2004    {
2005        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)));
2006        return;
2007    }
2008    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2009        let mut agents: Vec<_> = state
2010            .quota
2011            .iter()
2012            .filter(|q| {
2013                q.cause == crate::agent::QuotaCause::Authentication
2014                    && state
2015                        .passes
2016                        .last()
2017                        .is_none_or(|pass| q.at >= pass.started_at)
2018            })
2019            .map(|q| q.agent.as_str())
2020            .collect();
2021        agents.sort_unstable();
2022        agents.dedup();
2023        if !agents.is_empty() {
2024            task.stall(detail);
2025            task.notice_cause("agent-authentication", None, None);
2026            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2027            return;
2028        }
2029    }
2030    let attempts_before = task.attempts;
2031    // A run that stopped because a shared resource stayed busy was never a
2032    // failure of the task or of an agent. Earlier nodes may have run; only
2033    // the blocked operation lacks a result. The attempt is
2034    // refunded and the task is held by the machine, under a reason `triage`
2035    // can re-check, so the same run resumes with the same agents once the
2036    // resource is free. A park request still wins (it is the operator's).
2037    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2038        task.notice_cause(
2039            &format!("resource:{}:{}", block.kind, block.node),
2040            None,
2041            None,
2042        );
2043        task.last_error = Some(detail.to_owned());
2044        task.diagnostic = None;
2045        task.attempts = task.attempts.saturating_sub(1);
2046        if block.kind == "agent authentication" {
2047            task.hold_machine(Some(format!(
2048                "[authentication] {}; no attempt was spent",
2049                block.detail
2050            )));
2051        } else if block.kind == "agent usage limit" {
2052            // Usage limits keep the existing cooldown-and-resume policy.
2053            if let Some(agent) = &state.config.graph.selected_implementer {
2054                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.")));
2055            } else {
2056                task.status = TaskStatus::Failed;
2057                task.last_error = Some(block.detail.clone());
2058            }
2059        } else if block.kind == "disk pressure" {
2060            task.hold_machine(Some(format!(
2061                "{}{}",
2062                crate::disk::RUNNING_PRESSURE,
2063                block.detail
2064            )));
2065        } else {
2066            task.hold_machine(Some(format!(
2067                "{}{}; no attempt was spent; resume to retry the affected operation",
2068                crate::cache::RESOURCE_HOLD,
2069                block.description()
2070            )));
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                attempts_before,
2078                None,
2079            );
2080        }
2081        return;
2082    }
2083    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2084        state.parked
2085            && state.status == RunStatus::Landing
2086            && state
2087                .pr_pushed_head
2088                .as_ref()
2089                .is_none_or(|h| h == &hold.head)
2090            && task.runs.last() == Some(&state.id)
2091    }) {
2092        // Settlement and crash recovery share this idempotency key. A later
2093        // explicit resume is a new pass and may refund its own attempt once.
2094        let pass = state.passes.last().map_or(0, |p| p.index);
2095        if !task
2096            .passes
2097            .iter()
2098            .any(|p| p.run == state.id && p.pass_index == pass)
2099        {
2100            task.attempts = task.attempts.saturating_sub(1);
2101        }
2102        task.hold_machine(Some(format!(
2103            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2104            hold.question
2105        )));
2106        task.last_error = Some(detail.to_owned());
2107        task.diagnostic = None;
2108        task.record_pass_at(
2109            &state.id,
2110            pass,
2111            state.passes.last().map(|p| p.started_at),
2112            attempts_before,
2113            Some(crate::run::ParkCause::Question),
2114        );
2115        return;
2116    }
2117    let unresolved = task.hold_notice_cause.clone();
2118    if state.base_sync_blocked() {
2119        // No automatic retry may turn a retained sync stop into a new competition.
2120        task.hold_machine(Some(detail.to_owned()));
2121        task.last_error = Some(detail.to_owned());
2122    } else if !verdict.parked
2123        && task
2124            .pr_recovery
2125            .as_ref()
2126            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2127        && matches!(
2128            verdict.status,
2129            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2130        )
2131    {
2132        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2133            task.succeed();
2134        } else {
2135            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()));
2136        }
2137    } else if !verdict.parked
2138        && task.pr_recovery.is_some()
2139        && matches!(
2140            verdict.status,
2141            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2142        )
2143        && !verdict.quota_hit
2144    {
2145        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.")));
2146    } else {
2147        settle_in(task, verdict, detail, max_attempts, p);
2148    }
2149    if !verdict.parked
2150        && !verdict.quota_hit
2151        && matches!(
2152            verdict.status,
2153            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2154        )
2155    {
2156        task.recovery_failed(state);
2157    }
2158    if state.prep_failure.is_some() {
2159        // Minting a run whose candidates could not be prepared is not work
2160        // on a newly approved attempt. Keep the unresolved outcome anchor.
2161        task.hold_notice_cause = unresolved;
2162        task.startup_notice_cause("startup-candidates");
2163    }
2164    // Written here, where the refund (or not) is decided, so the history is a
2165    // fact and not a later guess from the run's status.
2166    if let Some(pass) = state.passes.last() {
2167        let parked = match &pass.end {
2168            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2169            _ => None,
2170        };
2171        task.record_pass_at(
2172            &state.id,
2173            pass.index,
2174            Some(pass.started_at),
2175            attempts_before,
2176            parked,
2177        );
2178    }
2179    if task.status == TaskStatus::Held {
2180        if state.base_sync_blocked() {
2181            task.base_sync_notice(state);
2182        } else if state.prep_failure.is_none() {
2183            task.notice_cause(
2184                label(verdict.status),
2185                Some(&state.id),
2186                state.passes.last().map(|p| p.index),
2187            );
2188        }
2189        task.diagnostic = diagnostic(state);
2190        note_open_question(task, &state.id, p);
2191    }
2192}
2193
2194/// If `task` is held with a `magi ask` question still open on `run`, name the
2195/// question in [`Task::hold_reason`] rather than leaving the hold reading
2196/// only [`describe`]'s run summary.
2197///
2198/// This is the shape task 20260928-191407-05fd left underspecified: an
2199/// implementer settled a verified no-op and filed a question for the
2200/// operator, and the hold that followed said nothing about the question
2201/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2202/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2203/// marker) and must keep seeing it unchanged.
2204///
2205/// Best-effort: an unreadable question store must not stop a run from
2206/// settling, so this is a no-op rather than a propagated error when
2207/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2208fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2209    let Some(home) = crate::run::try_home() else {
2210        return;
2211    };
2212    let open = Questions::at(home.join("questions")).open_for(run);
2213    let Some(q) = open.first() else {
2214        return;
2215    };
2216    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2217    decisions.sort_unstable();
2218    task.notice_cause(
2219        &format!("questions:{}", decisions.join(",")),
2220        Some(run),
2221        None,
2222    );
2223    let base = task.hold_reason.clone().unwrap_or_default();
2224    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2225}
2226
2227/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2228/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2229/// by some other means entirely, like a manual `magi run` resume that
2230/// finishes the graph outside the queue's bookkeeping.
2231///
2232/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2233/// `settle` is separate from `attempt`: a task recovered this way must land
2234/// exactly where a live daemon would have put it — the same policy table,
2235/// not a second one that quietly drifts from it — and that is only checkable
2236/// without spawning a real run.
2237fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2238    match last_run {
2239        Some(state) => {
2240            let verdict = Verdict {
2241                status: state.status,
2242                left_pr: state.pr.is_some(),
2243                quota_hit: state.quota.iter().any(|loss| {
2244                    state
2245                        .passes
2246                        .last()
2247                        .is_none_or(|pass| loss.at >= pass.started_at)
2248                }),
2249                parked: state.parked,
2250                no_viable_candidates: state.viable().is_empty(),
2251            };
2252            let detail = format!(
2253                "{}{}",
2254                phrases(&state.config.graph.language).recovered_running,
2255                describe(&state)
2256            );
2257            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2258        }
2259        None => {
2260            // No run, so no config of its own: `language` is the task's
2261            // repository's setting, read by the caller.
2262            let why = phrases(language).no_run_to_recover;
2263            task.last_error = Some(why.to_owned());
2264            // The phone shows `hold_reason`, so a task held by the machine
2265            // says why there too and not only in `last_error`.
2266            task.notice_cause("missing-run", None, None);
2267            task.hold_machine(Some(why.to_owned()));
2268        }
2269    }
2270}
2271
2272/// Find every task left at `running` that no live process is actually
2273/// driving, and settle each one against whatever its last run became.
2274///
2275/// # Why a claim is proof, not a guess
2276///
2277/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2278/// `running`, and the guard is held for the task's whole time in that status:
2279/// `attempt` does not return, and the loop does not move past the scope
2280/// holding the claim, until the run has settled. So a `running` task whose
2281/// lock is gone cannot have a live owner — this process or any other —
2282/// without needing a staleness threshold or a pid check the way
2283/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2284/// task that never got as far as `running` at all. Taking the claim here is
2285/// the whole test: it either fails, because something really does hold it
2286/// and the task is left alone, or it succeeds, which is the proof — and it is
2287/// kept for the rest of the decision so nothing else can start a competing
2288/// run while this one is being written.
2289///
2290/// Called on every poll, not only at startup, for the reason
2291/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2292/// keep noticing this, not only on the one morning it happened to restart.
2293fn reclaim_orphaned_running(
2294    queue: &Queue,
2295    max_attempts: usize,
2296    live_workers: &std::collections::BTreeSet<String>,
2297) -> Vec<String> {
2298    let mut reclaimed = Vec::new();
2299    for listed in queue.list() {
2300        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2301            continue;
2302        }
2303        let Ok(_claim) = queue.claim(&listed.id) else {
2304            continue;
2305        };
2306        // Re-read under the claim: a release or an edit landed by a human
2307        // between the listing above and the claim just taken must not be
2308        // clobbered by a decision based on the stale copy.
2309        let Ok(mut task) = queue.get(&listed.id) else {
2310            continue;
2311        };
2312        if task.status != TaskStatus::Running {
2313            continue;
2314        }
2315        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2316        // `execute` normally abandons a run's own open questions the moment
2317        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2318        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2319        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2320        // with the question still `open`, because the process died before
2321        // reaching that call. `reclaim` itself stays pure on purpose (see its
2322        // own doc), so the same cleanup runs here instead, against the run
2323        // this reclaim is already reading. `settle_run` costs nothing when
2324        // `execute` already got there first.
2325        if let Some(state) = &last_run
2326            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2327        {
2328            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2329        }
2330        let language = if last_run.is_none() {
2331            language_of(&task, Path::new("."))
2332        } else {
2333            String::new()
2334        };
2335        reclaim(&mut task, last_run, max_attempts, &language);
2336        if task.status == TaskStatus::Done {
2337            supersede_prior_runs(&task, &crate::run::home());
2338        }
2339        record(queue, &mut task);
2340        reclaimed.push(task.id.clone());
2341    }
2342    reclaimed
2343}
2344
2345/// Find every run whose `run.json` is provably dead — every seat it still
2346/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2347/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2348/// not merely "no daemon claims it" — and fail it, clearing the leftover
2349/// active seats so the run stops reading as `implementing` (or whichever
2350/// node) forever.
2351///
2352/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2353/// `running`, using whatever `run.json` already says — but nothing in that
2354/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2355/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2356/// never got back to sits exactly where it was left: `active` full of seats
2357/// nobody will ever answer for, `status` stuck on whatever node was in
2358/// flight. `magi show` already tells an operator this in prose (`no live
2359/// daemon claims this run right now`); this is what makes that fact durable
2360/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2361/// stay stuck once nothing is driving it.
2362///
2363/// Runs on every poll, not only at startup, for the reason
2364/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2365/// daemon up for days must keep noticing a run some other, now-dead, daemon
2366/// left behind just as readily as one it trips over on the way up.
2367///
2368/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2369/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2370/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2371/// `runs` directory instead: `home` here is a parameter precisely so a test
2372/// can point it away from the operator's real history (see [`drive`]'s own
2373/// doc), and a scan that fell through to the global home anyway would walk
2374/// whichever directory some *other* process or test pinned into that
2375/// `OnceLock` first — mutating runs this call was never handed.
2376fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2377    reclaim_abandoned_runs_with(
2378        home,
2379        now,
2380        crate::proc::pid_status,
2381        crate::proc::process_started_at,
2382    )
2383}
2384
2385/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2386/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2387/// for the identical reason: this sweep's real damage (wiping a run's active
2388/// seats and failing it) has to be provable against an injected answer in a
2389/// test, not just the real process table.
2390fn reclaim_abandoned_runs_with<F, G>(
2391    home: &Path,
2392    now: Timestamp,
2393    query: F,
2394    identity: G,
2395) -> Vec<String>
2396where
2397    F: Fn(u32) -> Option<bool>,
2398    G: Fn(u32) -> Option<String>,
2399{
2400    let mut abandoned = Vec::new();
2401    for entry in std::fs::read_dir(home.join("runs"))
2402        .into_iter()
2403        .flatten()
2404        .flatten()
2405    {
2406        let id = entry.file_name().to_string_lossy().into_owned();
2407        if !crate::run::is_run_id(&id) {
2408            continue;
2409        }
2410        // Serialize the proof and save with claims and takeover: a new
2411        // execution must not be overwritten after the liveness observation.
2412        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2413            continue;
2414        };
2415        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2416        // that module's docs for why a run this cannot parse is left alone
2417        // rather than guessed at. A different schema number is not that: this
2418        // touches only `status` and `active`, never a field whose meaning a
2419        // schema bump changed, so an old record's values serve this exactly
2420        // as well as a current one's (see `clean::read_state`'s own doc for
2421        // the same reasoning applied to folding).
2422        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2423            continue;
2424        };
2425        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2426            continue;
2427        };
2428        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2429            continue;
2430        }
2431        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2432        // it", which is also the normal, healthy shape of a manual `magi
2433        // run` / `magi review` sharing this same home — this scan walks
2434        // every run on disk, not only ones this daemon itself started. Such
2435        // a run's active seats can legitimately sit past their own timeout
2436        // for a little while (the CLI finishing up, its result still being
2437        // collected) without the process driving it having died. `liveness`
2438        // is what actually tells the two apart, by corroborating
2439        // `driver_pid` against the process it names — see its own doc. Only
2440        // its strongest, provable answer licenses wiping this run's active
2441        // seats and failing it out from under whatever is still running it.
2442        let daemon_claims = is_working_on(home, &id, now);
2443        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2444            != crate::run::Liveness::Dead
2445        {
2446            continue;
2447        }
2448        state.abandon("daemon");
2449        if let Err(e) = state.save_under(home) {
2450            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2451            continue;
2452        }
2453        // This run never passes through `Runner::execute` again, so its end
2454        // is announced here.
2455        if let Some(notice) = notices::run_ended(&state) {
2456            notices::raise_in(home, notice);
2457        }
2458        // The seat that asked is gone for good now, exactly like any other
2459        // door `graph::Runner::settle_questions` closes the moment `status`
2460        // lands somewhere non-resumable - see that method's own doc. Nothing
2461        // else reaches this one before the next `janitor()` startup pass
2462        // (`clean::abandon_settled_questions`), and a daemon that stays up
2463        // for days must not leave an open question badging the operator
2464        // until it happens to restart.
2465        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2466            tracing::warn!("abandon questions for {id}: {e:#}");
2467        }
2468        abandoned.push(id);
2469    }
2470    abandoned
2471}
2472
2473#[derive(Debug, Clone, Serialize, Deserialize)]
2474struct TaskWorker {
2475    opts: Opts,
2476    queue: PathBuf,
2477    task: String,
2478    #[serde(default)]
2479    lane: PermitKind,
2480    #[serde(default)]
2481    standalone: bool,
2482}
2483
2484fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2485    Ok(crate::worker::active(home)?
2486        .into_iter()
2487        .filter(|job| job.kind == "task")
2488        .collect())
2489}
2490
2491fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2492    task_jobs(home)?
2493        .into_iter()
2494        .filter_map(
2495            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2496                Ok(request) if !request.standalone => Some(Ok(job)),
2497                Ok(_) => None,
2498                Err(error) => Some(Err(error.into())),
2499            },
2500        )
2501        .collect()
2502}
2503
2504/// Whether an independent scheduler can be controlled without its web parent.
2505#[must_use]
2506pub fn managed(home: &Path) -> bool {
2507    match crate::worker::active(home) {
2508        Err(error) => {
2509            tracing::error!("cannot determine scheduler ownership: {error:#}");
2510            true
2511        }
2512        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2513        Ok(_) => {
2514            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2515                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2516        }
2517    }
2518}
2519
2520/// Start a detached, singleton scheduler using this executable generation.
2521pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2522    anyhow::ensure!(
2523        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2524        "the scheduler is stopping; wait for retirement before starting it again"
2525    );
2526    crate::worker::spawn(
2527        home,
2528        "scheduler",
2529        "scheduler",
2530        serde_json::to_value(opts.absolute()?)?,
2531    )
2532    .await
2533}
2534
2535fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2536    home.join("worker-parks").join(format!("{}.json", job.id))
2537}
2538
2539fn request_task_park(
2540    home: &Path,
2541    job: &crate::worker::Job,
2542    cause: crate::run::ParkCause,
2543) -> Result<()> {
2544    let path = park_request_path(home, job);
2545    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2546    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2547    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2548}
2549
2550/// Stop dispatch immediately; only an explicit park reaches existing workers.
2551pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2552    if control == crate::worker::Control::Park {
2553        for job in owned_task_jobs(home)? {
2554            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2555        }
2556    }
2557    crate::worker::request(home, "scheduler", control)
2558}
2559
2560/// Replace the scheduler, leaving all active task and conversation jobs alone.
2561pub async fn restart_detached(home: &Path) -> Result<()> {
2562    let active = crate::worker::active(home)?;
2563    let prior = active.into_iter().find(|job| job.kind == "scheduler");
2564    if prior.is_none() && !managed(home) {
2565        return Ok(());
2566    }
2567    let opts: Opts = match prior {
2568        Some(job) => serde_json::from_value(job.payload)?,
2569        None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2570    };
2571    request_control(home, crate::worker::Control::Stop)?;
2572    loop {
2573        let reserved = crate::worker::active(home)?
2574            .iter()
2575            .any(|job| job.kind == "scheduler");
2576        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2577            break;
2578        }
2579        tokio::time::sleep(Duration::from_millis(100)).await;
2580    }
2581    spawn_detached(home, &opts).await?;
2582    Ok(())
2583}
2584
2585/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2586pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2587    let opts: Opts = serde_json::from_value(payload)?;
2588    let _ = home;
2589    serve_until(opts, Stop::new()).await
2590}
2591
2592/// Execute and settle one task with the queue claim owned by this process.
2593pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2594    let request: TaskWorker = serde_json::from_value(payload)?;
2595    let queue = Queue::at(request.queue);
2596    let key = format!("task:{}", request.task);
2597    let job = task_jobs(home)?
2598        .into_iter()
2599        .find(|job| job.key == key)
2600        .context("task worker reservation is missing")?;
2601    let park_path = park_request_path(home, &job);
2602    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2603    // our durable reservation. Never execute before that ownership hand-off.
2604    let _claim = loop {
2605        match queue.claim(&request.task) {
2606            Ok(claim) => break claim,
2607            // Only contention (the claim file exists) is worth waiting out; an
2608            // I/O failure must end this worker instead of pinning its lane.
2609            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2610                return Err(e.context("claim the task for its worker"));
2611            }
2612            Err(_) => {
2613                sweep_stale_claims(&queue, STALE_CLAIM);
2614                tokio::time::sleep(Duration::from_millis(50)).await;
2615            }
2616        }
2617    };
2618    let mut task = queue.get(&request.task)?;
2619    if !task.status.runnable()
2620        || (!request.standalone
2621            && request.lane
2622                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2623    {
2624        return Ok(());
2625    }
2626    let stop = Stop::new();
2627    let watcher = {
2628        let home = home.to_path_buf();
2629        let stop = stop.clone();
2630        let park_path = park_path.clone();
2631        tokio::spawn(async move {
2632            loop {
2633                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2634                    let cause = std::fs::read(&park_path)
2635                        .ok()
2636                        .and_then(|body| serde_json::from_slice(&body).ok())
2637                        .unwrap_or(crate::run::ParkCause::Operator);
2638                    stop.park(cause);
2639                    return;
2640                }
2641                tokio::time::sleep(Duration::from_millis(200)).await;
2642            }
2643        })
2644    };
2645    let quota = if request.standalone {
2646        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2647    } else {
2648        let status = Arc::new(Mutex::new(Status::new()));
2649        Box::pin(attempt(
2650            &request.opts,
2651            &queue,
2652            &status,
2653            &stop,
2654            crate::graph::Pause::new(),
2655            &mut task,
2656        ))
2657        .await
2658    };
2659    watcher.abort();
2660    let _ = std::fs::remove_file(park_path);
2661    persist_cooldown(home, &quota).await?;
2662    Ok(())
2663}
2664
2665/// Launch the standalone task worker with a claim-to-reservation handoff.
2666/// Returns only after the worker owns a durable execution reservation.
2667pub async fn spawn_claimed(
2668    home: &Path,
2669    opts: &Opts,
2670    queue: &Queue,
2671    task: &Task,
2672    claim: crate::queue::Claim,
2673) -> Result<crate::worker::Job> {
2674    let request = TaskWorker {
2675        opts: opts.absolute()?,
2676        queue: std::path::absolute(queue.root())?,
2677        task: task.id.clone(),
2678        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2679        standalone: true,
2680    };
2681    let job = crate::worker::spawn(
2682        home,
2683        "task",
2684        &format!("task:{}", task.id),
2685        serde_json::to_value(request)?,
2686    )
2687    .await?;
2688    drop(claim);
2689    Ok(job)
2690}
2691
2692/// Transfer a standalone caller's claim only after the detached worker is live,
2693/// then follow that worker to its final (non-automatically-retrying) outcome.
2694pub async fn run_detached_claimed(
2695    opts: &Opts,
2696    queue: &Queue,
2697    task: &mut Task,
2698    claim: crate::queue::Claim,
2699) -> Result<()> {
2700    let home = crate::run::home();
2701    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2702    loop {
2703        // Reconcile execution leases even without a scheduler. A dead worker
2704        // must become a reported failure, never an infinite persisted wait.
2705        crate::worker::active(&home)?;
2706        let current = crate::worker::get(&home, &job.id)?;
2707        if matches!(
2708            current.status,
2709            crate::worker::Status::Finished | crate::worker::Status::Failed
2710        ) {
2711            *task = queue.get(&task.id)?;
2712            anyhow::ensure!(
2713                current.status != crate::worker::Status::Failed,
2714                "task worker failed: {}",
2715                current.result.as_deref().unwrap_or("unknown failure")
2716            );
2717            return Ok(());
2718        }
2719        tokio::time::sleep(Duration::from_millis(200)).await;
2720    }
2721}
2722
2723async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2724    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2725        let _lease = loop {
2726            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2727                break lease;
2728            }
2729            tokio::time::sleep(Duration::from_millis(10)).await;
2730        };
2731        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2732            let path = home.join("task-quota-cooldown.json");
2733            let temporary = path.with_extension("json.tmp");
2734            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2735            std::fs::rename(temporary, path)?;
2736        }
2737    }
2738    Ok(())
2739}
2740
2741fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2742    match std::fs::read(home.join("task-quota-cooldown.json")) {
2743        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2744        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2745        Err(error) => Err(error.into()),
2746    }
2747}
2748
2749/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2750///
2751/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2752/// sets, so there is one loop body rather than two that drift apart the first
2753/// time the retry policy changes on only one of them.
2754pub async fn serve(opts: Opts) -> Result<()> {
2755    tracing::info!(
2756        "automatic update and restart requires magi web; standalone serve does not restart"
2757    );
2758    serve_until(opts, Stop::new()).await
2759}
2760
2761/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2762///
2763/// A stop retires dispatch promptly, including while a worker launch is being
2764/// acknowledged. Already reserved workers own their attempts independently and
2765/// finish with their started executable. Explicit park additionally forwards
2766/// durable park requests; neither scheduler retirement nor update does so.
2767///
2768/// While the queue is empty the stop is honoured within one wakeup rather than
2769/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2770/// caller that taps stop does not sit through the remainder of a sleep.
2771pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2772    let opts = opts.absolute()?;
2773    let home = crate::run::home();
2774    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2775        .context("another scheduler already owns this home")?;
2776    if let Some(reading) = read_status(&home)
2777        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2778    {
2779        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2780    }
2781    if !crate::worker::active(&home)?
2782        .iter()
2783        .any(|job| job.kind == "scheduler")
2784    {
2785        crate::worker::clear_control(&home, "scheduler")?;
2786    }
2787    std::fs::write(
2788        home.join("scheduler-options.json"),
2789        serde_json::to_vec(&opts)?,
2790    )?;
2791    let control = {
2792        let home = home.clone();
2793        let stop = stop.clone();
2794        tokio::spawn(async move {
2795            loop {
2796                match crate::worker::control(&home, "scheduler").ok().flatten() {
2797                    Some(crate::worker::Control::Park) => {
2798                        let _ = request_control(&home, crate::worker::Control::Park);
2799                        stop.park(crate::run::ParkCause::Operator);
2800                        break;
2801                    }
2802                    Some(crate::worker::Control::Stop) => {
2803                        stop.stop();
2804                        break;
2805                    }
2806                    None => {}
2807                }
2808                tokio::time::sleep(Duration::from_millis(100)).await;
2809            }
2810        })
2811    };
2812    let signal = {
2813        let stop = stop.clone();
2814        tokio::spawn(async move {
2815            if tokio::signal::ctrl_c().await.is_ok() {
2816                stop.stop();
2817                tracing::info!("scheduler shutdown requested; independent workers continue");
2818            }
2819        })
2820    };
2821
2822    let worktrees_root = opts
2823        .worktrees_root
2824        .clone()
2825        .unwrap_or_else(crate::run::default_worktree_root);
2826    let outcome = drive(
2827        &opts,
2828        &Queue::open(),
2829        &status_path(),
2830        &crate::run::home(),
2831        &worktrees_root,
2832        &stop,
2833    )
2834    .await;
2835
2836    signal.abort();
2837    control.abort();
2838    outcome
2839}
2840
2841/// The loop proper: setup, poll, teardown, with the queue and the status file
2842/// supplied rather than discovered.
2843///
2844/// All three of `home`, `worktrees_root` and the queue/status paths are
2845/// parameters rather than resolved here, for the same reason:
2846/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2847/// so a unit test that pinned it would fight every other test in the binary,
2848/// and a loop that resolved its own worktree bay could only be exercised
2849/// against the operator's real `~/wt/<repo>` - publishing over a live
2850/// daemon's status file, claiming tasks out of a live backlog, and, since
2851/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2852/// whatever the operator actually has on disk.
2853async fn drive(
2854    opts: &Opts,
2855    queue: &Queue,
2856    status_file: &Path,
2857    home: &Path,
2858    worktrees_root: &Path,
2859    stop: &Stop,
2860) -> Result<()> {
2861    // The status file is a *snapshot*, not a stream of events: a reader only
2862    // ever wants the latest values, and every tick rewrites the whole file
2863    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2864    // while an mpsc channel would force the loop to re-send unchanged fields on
2865    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2866    // for no gain. The lock is only ever held across a field assignment, never
2867    // across an await.
2868    let recovery_cfg = prepare(&opts.repo, opts).ok();
2869    let daemon_cfg = recovery_cfg
2870        .as_ref()
2871        .map(|c| c.daemon.clone())
2872        .unwrap_or_default();
2873    let reconciled = crate::driver::reconcile(home);
2874    if !reconciled.is_empty() {
2875        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2876    }
2877    let mut initial_status = Status::new();
2878    let owned = owned_task_jobs(home)?;
2879    initial_status.current = current_work(home, Timestamp::now())
2880        .into_iter()
2881        .filter(|current| {
2882            owned
2883                .iter()
2884                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2885        })
2886        .collect();
2887    initial_status.idle = initial_status.current.is_empty();
2888    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2889        recovery_cfg.as_ref(),
2890        daemon_cfg.max_deputies,
2891    ));
2892    let status = Arc::new(Mutex::new(initial_status));
2893    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2894    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2895
2896    // Read once at startup, not per task: how many runs this loop drives at
2897    // once is a property of the machine running it, not of whichever
2898    // repository a given task happens to name - see
2899    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
2900    // fact in the same sense the agent roster is.
2901    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2902
2903    tracing::info!(
2904        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2905        queue.root().display(),
2906        opts.poll.as_secs(),
2907        opts.max_attempts,
2908        concurrency,
2909        if daemon_cfg.pause_for_interrupts {
2910            ", interrupts enabled"
2911        } else {
2912            ""
2913        }
2914    );
2915
2916    let outcome = tokio::select! {
2917        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
2918            max_concurrent: concurrency,
2919            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2920            recovery_cfg,
2921        }) => outcome,
2922        () = async {
2923            while !stop.stopped() {
2924                tokio::time::sleep(Duration::from_millis(25)).await;
2925            }
2926        } => {
2927            if stop.parking() {
2928                request_control(home, crate::worker::Control::Park)?;
2929            }
2930            Ok(())
2931        }
2932    };
2933
2934    stop.busy.store(0, Ordering::SeqCst);
2935    beat.abort();
2936    clear_status_at(status_file);
2937    outcome
2938}
2939
2940/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
2941/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
2942pub(crate) fn release_watch_settings_from_config(
2943    home: &Path,
2944    repo: &Path,
2945    cfg: &Config,
2946) -> (Vec<PathBuf>, u64) {
2947    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2948        .into_iter()
2949        .map(|r| r.path)
2950        .collect();
2951    // Repositories the daemon has worked in, wherever they live: a task may
2952    // name one outside `[repos] roots`, and its release PR must be watched too.
2953    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
2954        .list()
2955        .into_iter()
2956        .map(|t| t.repo)
2957        .collect();
2958    let runs = home.join("runs");
2959    for id in crate::run::list_ids_in(&runs) {
2960        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2961            .ok()
2962            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2963            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2964        known.extend(repo);
2965    }
2966    for k in known {
2967        let k = k.canonicalize().unwrap_or(k);
2968        if k.join(".git").exists() && !paths.contains(&k) {
2969            paths.push(k);
2970        }
2971    }
2972    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2973    if !paths.contains(&own) {
2974        paths.push(own);
2975    }
2976    (paths, cfg.daemon.release_stall_minutes)
2977}
2978
2979/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
2980const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2981
2982/// Refresh the status file on a fixed tick.
2983///
2984/// Separate from the loop because a run takes tens of minutes: a status file
2985/// written only between tasks would look stale for the whole of every run, and
2986/// a reader would report the daemon dead exactly while it was busiest.
2987async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2988    loop {
2989        tokio::time::sleep(HEARTBEAT).await;
2990        let snapshot = {
2991            let mut guard = lock(&status);
2992            guard.updated_at = Timestamp::now();
2993            guard.clone()
2994        };
2995        if let Err(e) = write_status_to(&path, &snapshot) {
2996            // A failed heartbeat must not take the daemon down: the loop is the
2997            // product, the status file is only the window onto it.
2998            tracing::warn!("could not refresh the daemon status file: {e:#}");
2999        }
3000    }
3001}
3002
3003/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3004/// if so, whether that wait is over.
3005#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3006enum LandResume {
3007    /// The task's last run is not parked on a land approval; schedule it
3008    /// like any other candidate.
3009    NotLanding,
3010    /// Parked in `land`, waiting on a question nobody has answered yet.
3011    /// Left alone: attempting it now would only re-observe the same pull
3012    /// request and park again, spending a `gh` call on a decision that has
3013    /// not changed since the last time this was checked.
3014    StillWaiting,
3015    /// Parked in `land`, and the question is settled - answered or
3016    /// abandoned. Resuming this is the one kind of candidate that must not
3017    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3018    Ready,
3019}
3020
3021/// Classify a runnable candidate by whether it is parked on a land-merge
3022/// approval. Read-only - no claim taken, nothing written - so it is cheap
3023/// enough to call on every candidate, every poll.
3024fn land_resume_state(task: &Task) -> LandResume {
3025    let Some(run_id) = task.runs.last() else {
3026        return LandResume::NotLanding;
3027    };
3028    let Ok(state) = RunState::load(run_id) else {
3029        return LandResume::NotLanding;
3030    };
3031    if !state.parked {
3032        return LandResume::NotLanding;
3033    }
3034    if state.status == RunStatus::Landing
3035        && state.land_approval.as_ref().is_some_and(|binding| {
3036            ask::Questions::open()
3037                .get(&binding.question)
3038                .is_ok_and(|q| {
3039                    q.run == state.id
3040                        && q.resolution()
3041                            .as_deref()
3042                            .is_some_and(crate::merge_decision::stops)
3043                })
3044        })
3045    {
3046        return LandResume::Ready;
3047    }
3048    if !implementers_match(task, &state) {
3049        return LandResume::NotLanding;
3050    }
3051    // Parked in `land` on the merge approval, or at `merge` on the owner's
3052    // word about a title/body the posting gate withheld. Told apart by the
3053    // run's own record, not by a status both can share.
3054    let node = if state.status == RunStatus::Landing {
3055        land::APPROVAL_NODE
3056    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3057        crate::github_text::ASK_NODE
3058    } else {
3059        return LandResume::NotLanding;
3060    };
3061    let store = ask::Questions::open();
3062    let waiting = store
3063        .list()
3064        .into_iter()
3065        .filter(|q| &q.run == run_id && q.node == node)
3066        .max_by(|a, b| a.id.cmp(&b.id));
3067    let Some(mut q) = waiting else {
3068        return LandResume::Ready;
3069    };
3070    if !q.status.open() {
3071        // Repair spends agent resources and must obey concurrency and quota
3072        // waits; only a merge/hold decision may use the decision-only lane.
3073        if q.resolution().as_deref() == Some(land::REPAIR) {
3074            return if state.liveness(false) == Liveness::Live {
3075                LandResume::StillWaiting
3076            } else {
3077                LandResume::NotLanding
3078            };
3079        }
3080        return LandResume::Ready;
3081    }
3082    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3083    // nobody ever answered; land's approval bypasses that wait entirely (see
3084    // `land::approval_gate`), so the same deadline has to be enforced here
3085    // instead, or `graph.answer_timeout` silently stops meaning anything for
3086    // a land approval and a run can sit `StillWaiting` forever with nobody
3087    // told to look at it.
3088    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3089    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3090    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3091        q.abandon(format!(
3092            "no answer within {}s of asking",
3093            timeout.as_secs().max(1)
3094        ));
3095        // If this can't be persisted, do not treat the wait as settled on a
3096        // guess: fall through and try again next poll.
3097        if store.put(&mut q).is_ok() {
3098            return LandResume::Ready;
3099        }
3100    }
3101    LandResume::StillWaiting
3102}
3103
3104/// How often the loop rechecks for new work while something it already
3105/// started is still running, rather than sleeping out the whole
3106/// [`Opts::poll`] interval.
3107///
3108/// Short on purpose: this is what lets a land-merge approval that comes back
3109/// while another task is mid-competition be noticed and resumed within a
3110/// fraction of a second, not within the next multi-second poll.
3111const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3112
3113/// How often [`poll`] rechecks the shared build cache against its cap at a
3114/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3115/// waiting for the queue to run dry.
3116///
3117/// A queue that never empties means the `janitor` call at the bottom of this
3118/// loop's fully-idle branch can go unreached for as long as the backlog
3119/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3120/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3121/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3122/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3123/// backlog of short tasks does not pay for that walk on every poll.
3124const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3125
3126/// State of [`poll`]'s own interrupt-scheduling sequence - see
3127/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3128/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3129/// both kept free of `Task`'s non-identity fields on purpose: every decision
3130/// here turns only on task ids and which ones are in flight, so the "never
3131/// more than one run at once" and "exactly one resume" invariants can be
3132/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3133/// queue - which is exactly the coverage this feature's first two attempts
3134/// were missing.
3135///
3136/// Persisted after every transition, so scheduler replacement preserves the
3137/// interrupt's exclusive turn and the interrupted task's priority resume.
3138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3139enum Interrupt {
3140    /// No interrupt sequence in progress. Ordinary dispatch applies.
3141    Idle,
3142    /// `interrupt_task` is runnable and exactly one other run is in flight;
3143    /// `parked` names that one task's id. Dispatch is withheld from
3144    /// everyone, including `interrupt_task` itself, until it has left
3145    /// flight - only then is `interrupt_task` let through.
3146    ///
3147    /// `parked` is a `Vec` rather than a bare id for symmetry with
3148    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3149    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3150    /// when exactly one run is in flight, so it is guaranteed to hold
3151    /// exactly one entry in practice - see that branch's own doc for why
3152    /// more than one is deliberately never attempted.
3153    Parking {
3154        parked: Vec<String>,
3155        interrupt_task: String,
3156    },
3157    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3158    /// withheld from everyone until it leaves flight - merged, failed, held,
3159    /// it makes no difference - at which point the sequence moves to
3160    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3161    /// going straight to `Idle` would hand `parked` back to ordinary
3162    /// priority-order dispatch, where a higher-priority task filed in the
3163    /// meantime could start ahead of it.
3164    Running {
3165        parked: Vec<String>,
3166        interrupt_task: String,
3167    },
3168    /// `interrupt_task` left flight; `parked` still names the one run this
3169    /// sequence owes a resume. Dispatch is withheld from everyone except
3170    /// that task - see [`interrupt_gate`] - so the resume this feature
3171    /// promises is never raced by, or run alongside, an unrelated candidate.
3172    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3173    /// own doc on abandonment - the moment it is no longer runnable at all.
3174    Resuming { parked: Vec<String> },
3175}
3176
3177/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3178/// and `runnable` are read-only snapshots of this tick's reality, and the
3179/// only side effect the caller still owes the world is asking whichever
3180/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3181/// site.
3182///
3183/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3184/// accepted rather than a narrower type because that is what [`poll`] already
3185/// has on hand from [`runnable`], and building a second, smaller list on
3186/// every tick just to satisfy this signature would cost more than it proves.
3187///
3188/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3189/// back to a task they are waiting on no longer being [`runnable`] - held,
3190/// blocked, deleted, or finished by some other means entirely, all of which
3191/// an operator can do to a task sitting in the queue with no claim on it at
3192/// all, at any moment, interrupt sequence or not. Without this check the
3193/// sequence would wait forever for a dispatch that can never come, and
3194/// `interrupt_gate` would withhold every other task in the queue right along
3195/// with it - a single `magi task hold` on the wrong id turning into a
3196/// daemon that never dispatches anything again.
3197fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3198    match state {
3199        Interrupt::Idle => {
3200            // Not just "something to interrupt": exactly one thing. More
3201            // than one run in flight only happens above the default
3202            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3203            // one resume, never run alongside anything else" only because
3204            // it is only ever seeded with exactly one id - see
3205            // `Interrupt::Resuming`'s own doc on why releasing more than one
3206            // parked id back to ordinary dispatch cannot be made safe
3207            // against that same setting's own extra concurrency slots.
3208            // Waiting here for the herd to settle to one is the
3209            // simplification this feature's own constraints ask for rather
3210            // than a second concurrency model to reconcile with the first.
3211            if in_flight.len() != 1 {
3212                return Interrupt::Idle;
3213            }
3214            match runnable.iter().find(|t| t.interrupt) {
3215                Some(t) => Interrupt::Parking {
3216                    parked: in_flight.to_vec(),
3217                    interrupt_task: t.id.clone(),
3218                },
3219                None => Interrupt::Idle,
3220            }
3221        }
3222        Interrupt::Parking {
3223            parked,
3224            interrupt_task,
3225        } => {
3226            if in_flight.iter().any(|id| parked.contains(id)) {
3227                // Still waiting for what was in flight to actually stop.
3228                Interrupt::Parking {
3229                    parked,
3230                    interrupt_task,
3231                }
3232            } else if in_flight.contains(&interrupt_task) {
3233                Interrupt::Running {
3234                    parked,
3235                    interrupt_task,
3236                }
3237            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3238                // The parked run(s) are gone, but the interrupt task has not
3239                // been dispatched yet on this tick - `interrupt_gate` is
3240                // what lets it through next.
3241                Interrupt::Parking {
3242                    parked,
3243                    interrupt_task,
3244                }
3245            } else {
3246                // The interrupt task itself is no longer runnable - see this
3247                // function's own doc on abandonment. The parked run(s) still
3248                // get their guaranteed resume; there is simply no interrupt
3249                // to run ahead of them any longer.
3250                Interrupt::Resuming { parked }
3251            }
3252        }
3253        Interrupt::Running {
3254            parked,
3255            interrupt_task,
3256        } => {
3257            if in_flight.contains(&interrupt_task) {
3258                Interrupt::Running {
3259                    parked,
3260                    interrupt_task,
3261                }
3262            } else {
3263                // The interrupt task's own run reached a terminal status,
3264                // whichever one - this is the *only* trigger that moves the
3265                // sequence on, driven straight off the same in-flight
3266                // bookkeeping `poll` already reaps every tick, not a second,
3267                // independent poll of anything.
3268                Interrupt::Resuming { parked }
3269            }
3270        }
3271        Interrupt::Resuming { parked } => {
3272            if in_flight.iter().any(|id| parked.contains(id)) {
3273                // One of the parked runs has been dispatched - the resume
3274                // this sequence owed is fulfilled. Whatever else is left in
3275                // `parked` (ordinarily nothing, at the default concurrency
3276                // of one) rejoins ordinary priority-order dispatch, same as
3277                // any other runnable task.
3278                Interrupt::Idle
3279            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3280                Interrupt::Resuming { parked }
3281            } else {
3282                // Abandonment (see this function's own doc): nothing left in
3283                // `parked` is even runnable any longer.
3284                Interrupt::Idle
3285            }
3286        }
3287    }
3288}
3289
3290/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3291/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3292/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3293/// indistinguishable from any other runnable task - exactly the "off does
3294/// nothing" this feature promises.
3295fn advance_interrupt_tick(
3296    enabled: bool,
3297    state: Interrupt,
3298    in_flight: &[String],
3299    runnable: &[Task],
3300) -> Interrupt {
3301    if !enabled {
3302        return Interrupt::Idle;
3303    }
3304    advance_interrupt(state, in_flight, runnable)
3305}
3306
3307/// Which of this tick's runnable candidates the interrupt sequence actually
3308/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3309/// each half is assertable on its own: this is the half that keeps a
3310/// competition and an interrupt from ever running at the same moment.
3311fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3312    match state {
3313        Interrupt::Idle => candidates,
3314        Interrupt::Parking {
3315            parked,
3316            interrupt_task,
3317        } => {
3318            if in_flight.iter().any(|id| parked.contains(id)) {
3319                Vec::new()
3320            } else {
3321                candidates
3322                    .into_iter()
3323                    .filter(|t| &t.id == interrupt_task)
3324                    .collect()
3325            }
3326        }
3327        Interrupt::Running { .. } => Vec::new(),
3328        // At most one: even if `parked` names more than one id (more than
3329        // one run was in flight when the sequence began, only possible
3330        // above the default `max_concurrent_runs = 1`), only the first match
3331        // is offered. Capping this to a single candidate - not merely to
3332        // `parked`'s own ids - is what makes "exactly one resume, never two
3333        // dispatched together" true regardless of how many ordinary slots
3334        // happen to be free this tick.
3335        Interrupt::Resuming { parked } => candidates
3336            .into_iter()
3337            .find(|t| parked.contains(&t.id))
3338            .into_iter()
3339            .collect(),
3340    }
3341}
3342
3343/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3344/// bundled into one parameter so `poll`'s own signature stays readable -
3345/// see [`drive`]'s call site for where these are actually read.
3346struct DispatchLimits {
3347    /// How many *ordinary* candidates run at once. See
3348    /// [`crate::config::Daemon::max_concurrent_runs`].
3349    max_concurrent: usize,
3350    /// See [`crate::config::Daemon::pause_for_interrupts`].
3351    pause_for_interrupts: bool,
3352    recovery_cfg: Option<Config>,
3353}
3354
3355/// Which semaphore, if any, dispatching a candidate should draw its permit
3356/// from.
3357///
3358/// Pure and separate from [`poll`]'s loop body for the same reason
3359/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3360/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3361/// exactly the policy this feature adds, and a policy only exercisable by
3362/// running the whole loop is a policy nobody checks.
3363#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3364enum PermitKind {
3365    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3366    /// Checked first - a task can be both a land resume and marked
3367    /// [`Task::urgent`], and the resume's own "must not queue behind
3368    /// anything" guarantee takes precedence.
3369    None,
3370    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3371    /// (never in addition to trying) the ordinary pool. This is what lets
3372    /// an urgent task dispatch while every ordinary slot is already checked
3373    /// out, and what stops a second urgent task from opening a third run: it
3374    /// waits on this same one-slot semaphore rather than falling through to
3375    /// the ordinary one.
3376    Urgent,
3377    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3378    /// above.
3379    #[default]
3380    Ordinary,
3381}
3382
3383/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3384/// own boolean, already computed by the caller from [`land_resume_state`].
3385fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3386    if priority {
3387        PermitKind::None
3388    } else if urgent {
3389        PermitKind::Urgent
3390    } else {
3391        PermitKind::Ordinary
3392    }
3393}
3394
3395fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3396    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3397        (0usize, 0usize),
3398        |(ordinary, urgent), request| match request.lane {
3399            PermitKind::Ordinary => (ordinary + 1, urgent),
3400            PermitKind::Urgent => (ordinary, urgent + 1),
3401            PermitKind::None => (ordinary, urgent),
3402        },
3403    );
3404    (
3405        limit.saturating_sub(ordinary),
3406        1usize.saturating_sub(urgent),
3407    )
3408}
3409
3410struct DispatchClaim {
3411    task: Task,
3412    claim: crate::queue::Claim,
3413    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3414}
3415
3416/// Claim and re-read before choosing a lane: a queue listing may predate an
3417/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3418fn claim_dispatch(
3419    queue: &Queue,
3420    candidate: &Task,
3421    cooling_down: bool,
3422    ordinary: &Arc<tokio::sync::Semaphore>,
3423    urgent: &Arc<tokio::sync::Semaphore>,
3424) -> Option<DispatchClaim> {
3425    let Ok(claim) = queue.claim(&candidate.id) else {
3426        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3427        return None;
3428    };
3429    let task = match queue.get(&candidate.id) {
3430        Ok(t) if t.status.runnable() => t,
3431        Ok(_) => return None,
3432        Err(e) => {
3433            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3434            return None;
3435        }
3436    };
3437    let resume = land_resume_state(&task);
3438    if resume == LandResume::StillWaiting {
3439        return None;
3440    }
3441    let priority = resume == LandResume::Ready;
3442    if !priority && cooling_down {
3443        return None;
3444    }
3445    // Never borrow an ordinary slot when the single urgent slot is busy.
3446    // Keep scanning other candidates when either pool has no free slot.
3447    let permit = match permit_kind(priority, task.urgent) {
3448        PermitKind::None => None,
3449        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3450        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3451    };
3452    // Persist the dispatch order under the claim, before config discovery or
3453    // coordination waits can reorder concurrent starts.
3454    let stamp = Timestamp::now();
3455    let mut task = task;
3456    task.dispatched_at = Some(stamp);
3457    if let Err(e) = queue.modify(&task.id, |t| {
3458        t.dispatched_at = Some(stamp);
3459        true
3460    }) {
3461        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3462    }
3463    Some(DispatchClaim {
3464        task,
3465        claim,
3466        permit,
3467    })
3468}
3469
3470/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3471/// teardown and cannot skip the teardown on an early return.
3472///
3473/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3474/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3475/// land approval that has since been answered is dispatched outside that
3476/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3477/// the whole point of parking there is that it must not queue behind
3478/// whatever else the loop happens to be running, even at the default of one.
3479/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3480/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3481/// these exemptions is still subject to the interrupt gate below, urgent
3482/// included: a land-resume or urgent candidate is exactly as much "something
3483/// else running" as an ordinary one from the interrupt sequence's point of
3484/// view, and letting either slip through while a run is being parked, or
3485/// while the interrupt task itself has the floor, is precisely the second
3486/// run 75dd's own "at most one run, ever, at once" guarantee must never
3487/// allow - see [`Interrupt`]'s own doc.
3488#[derive(Serialize, Deserialize)]
3489struct ServiceWorker {
3490    opts: Opts,
3491    queue: PathBuf,
3492    worktrees_root: PathBuf,
3493    operation: String,
3494}
3495
3496fn load_conductor(home: &Path) -> Result<Conductor> {
3497    match std::fs::read(home.join("conductor-state.json")) {
3498        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3499        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3500        Err(error) => Err(error.into()),
3501    }
3502}
3503
3504fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3505    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3506        .into_iter()
3507        .map(|c| c.task)
3508        .collect();
3509    let stalled = stalled_tasks(queue, home, Timestamp::now());
3510    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3511    let finished = finished_tasks(queue)
3512        .into_iter()
3513        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3514        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3515        .collect();
3516    let queued = queued_tasks(queue)
3517        .into_iter()
3518        .filter(|t| !live.contains(&t.id))
3519        .collect();
3520    (queued, stalled, finished)
3521}
3522
3523async fn start_service(
3524    home: &Path,
3525    opts: &Opts,
3526    queue: &Queue,
3527    worktrees_root: &Path,
3528    operation: &str,
3529    cfg: Option<&Config>,
3530    busy: bool,
3531) -> Result<()> {
3532    // Fetch policy is live configuration, unlike question recovery capacity.
3533    // Reload before both cadence and eligibility, including disabled -> enabled.
3534    let fetch_cfg = if operation == "fetch" {
3535        match prepare(&opts.repo, opts) {
3536            Ok(cfg) => Some(cfg),
3537            Err(error) => {
3538                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3539                return Ok(());
3540            }
3541        }
3542    } else {
3543        None
3544    };
3545    let cfg = fetch_cfg.as_ref().or(cfg);
3546    let ticks = home.join("service-ticks");
3547    std::fs::create_dir_all(&ticks)?;
3548    let receipt = ticks.join(format!("daemon-{operation}"));
3549    let last = std::fs::read(&receipt)
3550        .ok()
3551        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3552    let interval = match operation {
3553        "disk-pressure" => 30,
3554        "cache" => CACHE_CHECK_INTERVAL_SECS,
3555        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3556        _ => opts.poll.as_secs().max(1),
3557    };
3558    let now = Timestamp::now();
3559    if !cache_check_due(last, now, interval) {
3560        return Ok(());
3561    }
3562    let key = format!("service:daemon-{operation}");
3563    if crate::worker::active(home)?
3564        .iter()
3565        .any(|job| job.key == key)
3566    {
3567        return Ok(());
3568    }
3569    let eligible = match operation {
3570        "conductor" => {
3571            let (queued, stalled, finished) = conductor_work(queue, home);
3572            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3573                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3574        }
3575        "maintenance" => Questions::at(home.join("questions"))
3576            .list()
3577            .iter()
3578            .any(|q| {
3579                q.chosen_action().is_some_and(|action| action.maintenance())
3580                    && !home
3581                        .join("choice-actions")
3582                        .join(format!("{}.json", q.id))
3583                        .exists()
3584            }),
3585        "housekeeping" => !busy && runnable(queue).is_empty(),
3586        "cache" => {
3587            !busy
3588                && !runnable(queue).is_empty()
3589                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3590        }
3591        "disk-pressure" => busy,
3592        "fetch" => {
3593            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3594        }
3595        _ => false,
3596    };
3597    if !eligible {
3598        return Ok(());
3599    }
3600    let request = ServiceWorker {
3601        opts: opts.absolute()?,
3602        queue: std::path::absolute(queue.root())?,
3603        worktrees_root: std::path::absolute(worktrees_root)?,
3604        operation: operation.to_owned(),
3605    };
3606    if let Err(error) =
3607        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3608    {
3609        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3610    }
3611    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3612    Ok(())
3613}
3614
3615/// Finite maintenance jobs survive scheduler replacement without duplicating
3616/// agent calls or cancelling an operation between its effect and receipt.
3617pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3618    let request: ServiceWorker = serde_json::from_value(payload)?;
3619    let opts = &request.opts;
3620    let queue = Queue::at(request.queue);
3621    let questions = Questions::at(home.join("questions"));
3622    match request.operation.as_str() {
3623        "maintenance" => apply_maintenance_choices(&queue, &questions, home).await,
3624        "conductor" => {
3625            let path = home.join("conductor-state.json");
3626            let mut conductor = load_conductor(home)?;
3627            let (queued, stalled, finished) = conductor_work(&queue, home);
3628            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3629                && conductor.worth_a_look(&queue, &stalled, &finished)
3630            {
3631                let cfg = prepare(&opts.repo, opts)?;
3632                conductor
3633                    .maybe_run(
3634                        &cfg,
3635                        &opts.repo,
3636                        &queue,
3637                        &questions,
3638                        home,
3639                        &queued,
3640                        &stalled,
3641                        &finished,
3642                        opts.max_attempts,
3643                    )
3644                    .await;
3645                let temporary = path.with_extension("json.tmp");
3646                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3647                std::fs::rename(temporary, path)?;
3648            }
3649        }
3650        "fetch" => {
3651            let cfg = prepare(&opts.repo, opts)?;
3652            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3653                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3654                tracing::debug!("fetch origins: {outcome:?}");
3655            }
3656        }
3657        "cache" => {
3658            if task_jobs(home)?.is_empty() {
3659                let mut checked = None;
3660                maybe_prune_cache_between_runs(
3661                    &opts.repo,
3662                    opts,
3663                    home,
3664                    &Stop::new(),
3665                    &mut checked,
3666                    Timestamp::now(),
3667                )
3668                .await;
3669            }
3670        }
3671        "disk-pressure" => {
3672            if let Ok(cfg) = prepare(&opts.repo, opts) {
3673                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3674                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3675                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3676                }
3677                for current in current_work(home, Timestamp::now()) {
3678                    if let Ok(state) = RunState::load_under(&current.run, home)
3679                        && let Some(reason) = disk_gate(&state.repo, &state.config)
3680                    {
3681                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
3682                            job.key.strip_prefix("task:") == Some(current.task.as_str())
3683                        }) {
3684                            request_task_park(
3685                                home,
3686                                &job,
3687                                crate::run::ParkCause::Interrupt {
3688                                    reason: reason.clone(),
3689                                },
3690                            )?;
3691                        }
3692                        notices::raise_in(
3693                            home,
3694                            Notice::warn(
3695                                "disk:pressure",
3696                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
3697                            ),
3698                        );
3699                    }
3700                }
3701            }
3702        }
3703        "housekeeping" => {
3704            if task_jobs(home)?.is_empty() {
3705                if let Ok(cfg) = prepare(&opts.repo, opts) {
3706                    crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3707                }
3708                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
3709                resweep_superseded_attempts(&queue, home);
3710                triage_held(&queue, home, opts).await;
3711            }
3712        }
3713        operation => bail!("unknown daemon service {operation}"),
3714    }
3715    Ok(())
3716}
3717
3718/// Only a different request under the same key is a dispatch handoff race.
3719/// Our own unacknowledged reservation is a startup failure, not competing work:
3720/// stop dispatch without fencing it, so an already detached child may still run.
3721fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
3722    let key = format!("task:{}", request.task);
3723    let payload = serde_json::to_value(request)?;
3724    if crate::worker::active(home)?
3725        .iter()
3726        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
3727    {
3728        tracing::warn!(
3729            "task {} acquired a competing worker reservation: {error:#}",
3730            crate::run::short_of(&request.task)
3731        );
3732        return Ok(());
3733    }
3734    tracing::error!("task worker startup stopped dispatch: {error:#}");
3735    notices::raise_in(
3736        home,
3737        Notice::error(
3738            "loop:worker-startup",
3739            // Startup diagnostics may contain private child-process details;
3740            // keep them in the local error/log rather than the chat or notifier.
3741            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),
3742        ).link(Link::Task { id: request.task.clone() }),
3743    );
3744    Err(error).with_context(|| {
3745        format!(
3746            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
3747            crate::run::short_of(&request.task)
3748        )
3749    })
3750}
3751
3752async fn poll(
3753    opts: &Opts,
3754    queue: &Queue,
3755    status: &Arc<Mutex<Status>>,
3756    home: &Path,
3757    worktrees_root: &Path,
3758    stop: &Stop,
3759    limits: DispatchLimits,
3760) -> Result<()> {
3761    let mut attempted = Vec::new();
3762    let mut settling_once_services = false;
3763    let interrupt_path = home.join("scheduler-interrupt.json");
3764    let mut interrupt = match std::fs::read(&interrupt_path) {
3765        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
3766        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
3767        Err(error) => return Err(error.into()),
3768    };
3769    let mut previous = std::collections::BTreeSet::<String>::new();
3770    while !stop.stopped() {
3771        let jobs: Vec<_> = crate::worker::active(home)?
3772            .into_iter()
3773            .filter(|job| job.kind == "task")
3774            .collect();
3775        let requests: Vec<_> = jobs
3776            .iter()
3777            .map(|job| {
3778                serde_json::from_value::<TaskWorker>(job.payload.clone())
3779                    .with_context(|| format!("read live task worker {}", job.id))
3780            })
3781            .collect::<Result<_>>()?;
3782        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
3783        let owned: std::collections::BTreeSet<_> = requests
3784            .iter()
3785            .filter(|r| !r.standalone)
3786            .map(|r| r.task.clone())
3787            .collect();
3788        let current: Vec<_> = requests
3789            .iter()
3790            .zip(&jobs)
3791            .filter(|(request, _)| !request.standalone)
3792            .map(|(request, job)| Current {
3793                worker: Some(job.id.clone()),
3794                task: request.task.clone(),
3795                run: queue
3796                    .get(&request.task)
3797                    .ok()
3798                    .and_then(|task| task.runs.last().cloned())
3799                    .unwrap_or_default(),
3800            })
3801            .collect();
3802        {
3803            let mut snapshot = lock(status);
3804            snapshot.polls += 1;
3805            snapshot.completed += previous.difference(&owned).count();
3806            snapshot.current = current;
3807            snapshot.idle = owned.is_empty();
3808        }
3809        previous = owned.clone();
3810        stop.busy.store(owned.len(), Ordering::SeqCst);
3811
3812        // Slots are reconstructed from durable reservations and OS-held worker
3813        // leases, not this scheduler's lifetime or mutable task urgency.
3814        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
3815        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
3816        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
3817        let mut permits = Vec::new();
3818        sweep_stale_claims(queue, STALE_CLAIM);
3819        reclaim_orphaned_running(queue, opts.max_attempts, &live);
3820        reclaim_abandoned_runs(home, Timestamp::now());
3821        let questions = Questions::at(home.join("questions"));
3822
3823        // Deterministic: no model, run before the conductor sees anything so
3824        // its input reflects the queue's current, already-resolved state.
3825        crate::task_chat::sweep(
3826            queue,
3827            &crate::talk::Talks::at(home.join("talks")),
3828            &questions,
3829            home,
3830        );
3831        repair_choice_offers(&questions);
3832        resolve_blockers(queue, &questions);
3833        apply_task_choice_actions(queue, &questions, home);
3834        triage::apply_answers(queue, &questions);
3835        reconcile_task_questions(queue, &questions);
3836        let talks = crate::talk::Talks::at(home.join("talks"));
3837        crate::chat_notify::sweep(queue, &talks, home);
3838        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
3839        crate::chat_watch::sweep(home, &talks);
3840        let mut turns = tokio::task::JoinSet::new();
3841        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
3842        // start_turns dispatches detached turns; no paid work lives in this set.
3843        while turns.join_next().await.is_some() {}
3844
3845        crate::consult::start_services(
3846            home,
3847            &opts.repo,
3848            limits.recovery_cfg.as_ref(),
3849            opts.config.as_deref(),
3850        )
3851        .await?;
3852        for operation in [
3853            "conductor",
3854            "maintenance",
3855            "housekeeping",
3856            "disk-pressure",
3857            "cache",
3858            "fetch",
3859        ] {
3860            // Once an idle --once drain starts settling services, subsequent
3861            // scans only consume their effects. An expired cadence receipt
3862            // must not start another service and keep the drain alive.
3863            if settling_once_services {
3864                break;
3865            }
3866            start_service(
3867                home,
3868                opts,
3869                queue,
3870                worktrees_root,
3871                operation,
3872                limits.recovery_cfg.as_ref(),
3873                !live.is_empty(),
3874            )
3875            .await?;
3876        }
3877        let latest = crate::worker::active(home)?;
3878        if latest.iter().any(|job| job.key == "service:daemon-cache")
3879            || latest
3880                .iter()
3881                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3882        {
3883            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3884            continue;
3885        }
3886        let candidates: Vec<Task> = runnable(queue)
3887            .into_iter()
3888            .filter(|task| !live.contains(&task.id))
3889            .filter(|task| !opts.once || !attempted.contains(&task.id))
3890            .collect();
3891        let in_flight: Vec<_> = owned.iter().cloned().collect();
3892        let prior_interrupt = std::mem::discriminant(&interrupt);
3893        interrupt = advance_interrupt_tick(
3894            limits.pause_for_interrupts,
3895            interrupt,
3896            &in_flight,
3897            &candidates,
3898        );
3899        // Same-variant transitions preserve their identities. Only an actual
3900        // transition needs a durable write, atomically before sending controls.
3901        if prior_interrupt != std::mem::discriminant(&interrupt) {
3902            let temporary = interrupt_path.with_extension("json.tmp");
3903            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
3904            std::fs::rename(temporary, &interrupt_path)?;
3905        }
3906        if let Interrupt::Parking {
3907            parked,
3908            interrupt_task,
3909        } = &interrupt
3910        {
3911            for job in jobs.iter().filter(|job| {
3912                parked
3913                    .iter()
3914                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
3915            }) {
3916                if crate::worker::control(home, &job.key)?.is_none() {
3917                    request_task_park(
3918                        home,
3919                        job,
3920                        crate::run::ParkCause::Interrupt {
3921                            reason: format!(
3922                                "task {} asked to run first",
3923                                crate::run::short_of(interrupt_task)
3924                            ),
3925                        },
3926                    )?;
3927                }
3928            }
3929        }
3930        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3931        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
3932        let mut started = false;
3933        let mut resync = false;
3934        for candidate in candidates {
3935            if stop.stopped() {
3936                break;
3937            }
3938            let Some(DispatchClaim {
3939                task,
3940                claim,
3941                permit,
3942            }) = claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem)
3943            else {
3944                continue;
3945            };
3946            if crate::worker::active(home)?
3947                .iter()
3948                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3949            {
3950                drop(claim);
3951                resync = true;
3952                break;
3953            }
3954            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
3955            let request = TaskWorker {
3956                opts: opts.absolute()?,
3957                queue: std::path::absolute(queue.root())?,
3958                task: task.id.clone(),
3959                lane,
3960                standalone: false,
3961            };
3962            // Keep the claim until spawn acknowledges the worker's durable
3963            // reservation. The worker then claims and re-reads before attempt.
3964            if let Err(error) = crate::worker::spawn(
3965                home,
3966                "task",
3967                &format!("task:{}", task.id),
3968                serde_json::to_value(&request)?,
3969            )
3970            .await
3971            {
3972                task_worker_spawn_error(home, &request, error)?;
3973                drop(claim);
3974                resync = true;
3975                break;
3976            }
3977            drop(claim);
3978            permits.extend(permit);
3979            attempted.push(task.id);
3980            started = true;
3981        }
3982        if started || resync {
3983            continue;
3984        }
3985        if owned.is_empty() && opts.once {
3986            settling_once_services = true;
3987            // These finite services can own queue claims or publish answers.
3988            // A skipped claim is not an idle queue until they have finished;
3989            // scan again afterwards so their changes are actually scheduled.
3990            if crate::worker::active(home)?.iter().any(|job| {
3991                job.kind == "daemon-service"
3992                    && matches!(
3993                        job.key.as_str(),
3994                        "service:daemon-housekeeping"
3995                            | "service:daemon-conductor"
3996                            | "service:daemon-maintenance"
3997                    )
3998            }) {
3999                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4000                continue;
4001            }
4002            break;
4003        }
4004        stop.idle(if live.is_empty() {
4005            opts.poll
4006        } else {
4007            RECHECK_WHILE_BUSY.min(opts.poll)
4008        })
4009        .await;
4010    }
4011    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4012    // every queue claim and Runner driver lease through outcome settlement.
4013    stop.busy.store(0, Ordering::SeqCst);
4014    Ok(())
4015}
4016
4017/// A maintenance pass may briefly own the same record while a worker starts.
4018/// Wait without blocking the executor or charging an agent attempt, then read
4019/// ownership again under the acquired lock. Other I/O failures still fail closed.
4020async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4021    let busy = |error: &anyhow::Error| {
4022        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4023            error.kind() == std::io::ErrorKind::WouldBlock
4024                || cfg!(windows) && error.raw_os_error() == Some(33)
4025        })
4026    };
4027    match crate::pr_head::owner_lock(home, id) {
4028        Ok(lock) => return Ok(lock),
4029        Err(error) if busy(&error) => {}
4030        Err(error) => return Err(error),
4031    }
4032    let wait = RunState::load_under(id, home)?
4033        .config
4034        .graph
4035        .timeout_resource_wait;
4036    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4037}
4038
4039/// Historical successors do not revoke a still-resumable public owner. Scan
4040/// under the same lock as publication/driver claims, and fail closed on unknown
4041/// history before spending another attempt.
4042async fn public_resume_owner(
4043    home: &Path,
4044    runs: &[String],
4045    repo: &Path,
4046) -> Result<Option<RunState>> {
4047    let mut owner = None;
4048    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4049        let _lock = resume_owner_lock(home, id).await?;
4050        let state = RunState::load_under(id, home)?;
4051        if state.released()
4052            || state.retired_to.is_some()
4053            || state.pr_taken_over_by.is_some()
4054            || !crate::handover::landing_checkpoint(&state)
4055        {
4056            continue;
4057        }
4058        anyhow::ensure!(
4059            crate::git::toplevel(&state.repo).await?.canonicalize()?
4060                == crate::git::toplevel(repo).await?.canonicalize()?,
4061            "public owner repository differs; inspect run lineage"
4062        );
4063        anyhow::ensure!(
4064            owner.is_none(),
4065            "multiple retained public owners; inspect run lineage"
4066        );
4067        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4068            anyhow::bail!(reason.diagnostic(&state));
4069        }
4070        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4071        anyhow::ensure!(
4072            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4073            "public owner's driver is live or unknown; wait before retrying"
4074        );
4075        owner = Some(state);
4076    }
4077    Ok(owner)
4078}
4079
4080/// Run one claimed task to a terminal status and record the outcome.
4081///
4082/// Every transition is flushed to the queue as it happens, so the state on disk
4083/// is what actually occurred rather than what this process still intends to
4084/// write.
4085async fn attempt(
4086    opts: &Opts,
4087    queue: &Queue,
4088    status: &Arc<Mutex<Status>>,
4089    stop: &Stop,
4090    interrupt_pause: crate::graph::Pause,
4091    task: &mut Task,
4092) -> Vec<QuotaLoss> {
4093    let repo = repo_for(task, &opts.repo);
4094    tracing::info!(
4095        "task {} — {} (repo {})",
4096        task.short(),
4097        task.title,
4098        repo.display()
4099    );
4100
4101    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4102        Ok(owner) => owner,
4103        Err(e) => {
4104            task.hold_machine(Some(format!(
4105                "Cannot verify existing public owner: {e:#}; no attempt started."
4106            )));
4107            record(queue, task);
4108            return Vec::new();
4109        }
4110    };
4111    let resume_runs = public_owner
4112        .as_ref()
4113        .map(|s| vec![s.id.clone()])
4114        .unwrap_or_else(|| task.runs.clone());
4115
4116    // A stop spends no agent resources and uses the saved landing owner.
4117    // Current roster edits, missing attachments or a failed config fetch must
4118    // never turn it into a new implementation, or prevent a PR from closing.
4119    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4120        && previous
4121            .merge_decision
4122            .as_ref()
4123            .is_some_and(|decision| !decision.closed)
4124        && previous.status != RunStatus::Landing
4125        && !crate::merge_decision::resumable_hold(&previous)
4126    {
4127        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)));
4128        record(queue, task);
4129        return Vec::new();
4130    }
4131    let stop_owner = resume_runs
4132        .last()
4133        .and_then(|id| RunState::load(id).ok())
4134        .filter(|state| {
4135            crate::merge_decision::resumable_hold(state)
4136                || state.status == RunStatus::Landing
4137                    && state.land_approval.as_ref().is_some_and(|binding| {
4138                        Questions::open().get(&binding.question).is_ok_and(|q| {
4139                            q.run == state.id
4140                                && q.resolution()
4141                                    .as_deref()
4142                                    .is_some_and(crate::merge_decision::stops)
4143                        })
4144                    })
4145        });
4146    if let Some(owner) = stop_owner {
4147        let mut runner = match Runner::resume(&owner.id) {
4148            Ok(runner) => runner,
4149            Err(e) => {
4150                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4151                record(queue, task);
4152                return Vec::new();
4153            }
4154        };
4155        runner.on_pause(stop.pause());
4156        runner.watch_interrupt(interrupt_pause);
4157        let quota_before = runner.state.quota.clone();
4158        task.start(owner.id.clone());
4159        record(queue, task);
4160        lock(status).current.push(Current {
4161            worker: None,
4162            task: task.id.clone(),
4163            run: owner.id,
4164        });
4165        runner.state.next_pass_task_entry = true;
4166        let result = runner.execute().await;
4167        return finish_attempt(
4168            opts.max_attempts,
4169            queue,
4170            task,
4171            &runner.state,
4172            &quota_before,
4173            result,
4174        );
4175    }
4176
4177    if let Some(owner) = &public_owner
4178        && (task.fresh_start || !may_resume_run(owner, task))
4179    {
4180        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)));
4181        record(queue, task);
4182        return Vec::new();
4183    }
4184
4185    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4186        && !task.fresh_start
4187        && task.review_branch.is_none()
4188        && task.pr_recovery.is_none()
4189    {
4190        // Authorization still takes the owner lock and execution lease and
4191        // rechecks liveness, retained HEAD and ownership before saving.
4192        let authorized = if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4193            let home = queue.root().parent().expect("queue has a home");
4194            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4195                Ok(()) => true,
4196                Err(error) => {
4197                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4198                    false
4199                }
4200            }
4201        } else {
4202            false
4203        };
4204        if !authorized {
4205            task.hold_machine(Some("Base synchronization remains stopped. Inspect the retained run; for movement exhaustion, explicitly use `magi run --resume <run> --recover-base`. A release without a new owner approval grants no additional rebase and starts no replacement competition.".into()));
4206            // Retain the existing stop identity when an old release reached the queue.
4207            task.base_sync_notice(&held);
4208            task.resume_override = None;
4209            record(queue, task);
4210            return Vec::new();
4211        }
4212    }
4213    let unfinished = (!task.fresh_start)
4214        .then(|| unfinished_run(&resume_runs, task.short()))
4215        .flatten()
4216        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4217    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4218    if !task.fresh_start
4219        && task.pr_recovery.is_none()
4220        && task.review_branch.is_none()
4221        && task.resume_override.is_none()
4222        && previous
4223            .as_ref()
4224            .is_some_and(|run| run.retired_to.is_some())
4225        && unfinished.is_none()
4226    {
4227        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()));
4228        record(queue, task);
4229        return Vec::new();
4230    }
4231
4232    let saved_recovery = previous.as_ref().filter(|run| {
4233        task.replacement.is_none()
4234            && task.pr_recovery.as_ref().is_some_and(|selected| {
4235                selected.check_task(&task.id, &task.instruction).is_ok()
4236                    && selected_starter(selected, Some(run), unfinished.as_deref())
4237                        == Starter::Resume(run.id.clone())
4238            })
4239    });
4240
4241    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4242    // failure here is the network's or the operator's, not the task's: hold
4243    // without spending an attempt, never fall back to a possibly stale copy.
4244    let explicit = match &task.overrides {
4245        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4246        Some(_) => opts.config.as_deref(),
4247        None => opts.config.as_deref(),
4248    };
4249    let (mut config, layers) = if let Some(run) = saved_recovery {
4250        // A matching resume owns its resolved configuration and evidence;
4251        // current layers and inherited overrides only configure new work.
4252        let mut saved = run.clone();
4253        if let Err(e) = saved.configure_recovery_resume() {
4254            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4255            record(queue, task);
4256            return Vec::new();
4257        }
4258        (saved.config, Vec::new())
4259    } else {
4260        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4261            Ok(loaded) => loaded,
4262            Err(e) => {
4263                let reason = format!("[config] {e:#}");
4264                record_config_failure(task, &e);
4265                task.last_error = Some(reason.clone());
4266                task.hold_machine(Some(reason));
4267                record(queue, task);
4268                return Vec::new();
4269            }
4270        };
4271        if let Err(e) = apply_options(&mut config, opts, task) {
4272            task.hold_manual(Some(format!(
4273                "[config] {e:#}; correct the merge override before releasing the task"
4274            )));
4275            record(queue, task);
4276            return Vec::new();
4277        }
4278        if let Some(selected) = &task.pr_recovery
4279            && let Err(e) = selected.configure(&mut config)
4280        {
4281            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4282            record(queue, task);
4283            return Vec::new();
4284        }
4285        (config, layers)
4286    };
4287    let config_evidence = crate::pr_recovery::ConfigEvidence {
4288        layers,
4289        overrides: task.overrides.clone(),
4290        daemon_merge: task
4291            .overrides
4292            .as_ref()
4293            .is_none_or(|o| o.inherit_daemon_options)
4294            .then(|| opts.merge.clone())
4295            .flatten(),
4296    };
4297    apply_task_implementers(&mut config, task);
4298    if let Some(replacement) = &task.replacement {
4299        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4300            old.liveness(false) == Liveness::Dead
4301                && old.merge_decision.as_ref().is_some_and(|d| {
4302                    d.closed
4303                        && d.question == replacement.question
4304                        && d.replacement_run.as_ref().is_none_or(|run| {
4305                            task.runs.last() == Some(run)
4306                                && RunState::load(run).is_ok_and(|current| {
4307                                    current.replaces.as_ref().is_some_and(|pin| {
4308                                        pin.question == replacement.question
4309                                            && pin.agent == replacement.agent
4310                                    })
4311                                })
4312                        })
4313                })
4314        });
4315        if !safe {
4316            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()));
4317            record(queue, task);
4318            return Vec::new();
4319        }
4320        match config.agent(&replacement.agent) {
4321            Ok(agent) if crate::agent::installed(agent) => {}
4322            _ => {
4323                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)));
4324                record(queue, task);
4325                return Vec::new();
4326            }
4327        }
4328        config.graph.implementers = 1;
4329        config.graph.land_approval = true;
4330        config.merge.mode = MergeMode::Pr;
4331        config.graph.selected_implementer = Some(replacement.agent.clone());
4332    }
4333    let p = phrases(&config.graph.language);
4334    let start_failed = p.could_not_start;
4335    // Resolve once for both admission and settlement. The inputs are the
4336    // task's explicit sources (never prose), plus an explicit review source's
4337    // current head; review-only runs may rebase later, and neither fact can
4338    // refund a failed automatic generation.
4339    if let Ok(base) =
4340        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4341            .await
4342        && let Ok(head) =
4343            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4344    {
4345        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4346        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4347            let source = crate::git::rev_parse(&repo, branch)
4348                .await
4349                .unwrap_or_default();
4350            inputs.push_str(&format!(";review:{branch}:{source}"));
4351        }
4352        if let Some(reason) = task.recovery_exhausted(
4353            &head,
4354            &inputs,
4355            task.attempt_limit
4356                .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4357        ) {
4358            task.hold_unrequested_retry(Some(reason));
4359            record(queue, task);
4360            return Vec::new();
4361        }
4362        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4363    }
4364
4365    // The free-space gate, checked *before* anything is minted: a task that
4366    // waits out a full disk costs nothing yet, and must not spend an attempt
4367    // or start a run the machine cannot finish. Held tasks stay in the list
4368    // for the human to see, and `magi task release` re-queues them when space
4369    // comes back - the same recovery as any other hold. A volume whose free
4370    // space cannot be measured closes the gate too: starting a run blind on a
4371    // disk that may be full is how the machine ends up with 6.7 GB free.
4372    if let Some(reason) = disk_gate(&repo, &config) {
4373        task.notice_cause("disk-space", None, None);
4374        task.last_error = Some(reason.clone());
4375        task.hold_machine(Some(reason.clone()));
4376        record(queue, task);
4377        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4378        // Stable wording - the free-space figures live in the task's hold
4379        // reason, and changing numbers would relight the bell every poll.
4380        notices::raise(
4381            Notice::warn(
4382                &format!("disk:{}", repo.display()),
4383                format!("Task {} held for want of free disk space: {reason}. Free some, then release it from the queue.", task.id),
4384            )
4385            .link(Link::Task {
4386                id: task.id.clone(),
4387            }),
4388        );
4389        return Vec::new();
4390    }
4391
4392    // A resumable run of this task is carried on, never re-competed. The
4393    // candidates are built and paid for, and a fresh competition races a
4394    // second implementation against them.
4395    //
4396    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4397    // started 3cbf on the same task a moment later, duplicating two and a
4398    // half hours of agent work. Then b25f stalled on a judge that timed out
4399    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4400    // was to blame for - and 4043 started **one second** later, buying three
4401    // fresh implementations to reach the same panel. `RunStatus::resumable`
4402    // rather than `!done()` is what catches the second case: a stall is
4403    // terminal, and its cheap recovery re-asks only the absent seats.
4404    //
4405    // A load failure is warned about rather than silently read as "not
4406    // resumable": the alternative is exactly what let a schema mismatch on
4407    // run `eba2` fall through to a full re-competition with nobody told why.
4408    // `crate::conduct` is what actually offers a better answer than
4409    // `Runner::start` here (see `Recovery::Review`), once this task's next
4410    // failure shows it up as `held`/`failed` with the run state unreadable.
4411    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
4412    // branch survived, and this reopens exactly that branch as a
4413    // review-only pass rather than resuming or competing again. Consumed
4414    // (cleared) here whichever way this goes, so it never outlives this one
4415    // attempt - see `queue::Task::review_branch`.
4416    let review_branch = take_review_branch(task, previous.as_ref());
4417    let branch_exists = match &review_branch {
4418        Some(branch) => crate::git::branch_exists(&repo, branch)
4419            .await
4420            .unwrap_or(false),
4421        None => false,
4422    };
4423    // An explicit `magi review <branch>` is reviewed whatever happens to the
4424    // branch unless an explicit implementer change requires fresh work. An
4425    // unfinished run of the same task still wins, so a retry resumes.
4426    let proposed = review_retry_starter(
4427        task,
4428        previous.as_ref(),
4429        review_branch.as_deref(),
4430        branch_exists,
4431        unfinished.as_deref(),
4432    );
4433    let retry_selected = task.replacement.is_some()
4434        && task.resumption.is_some()
4435        && !task.fresh_start
4436        && previous.as_ref().is_some_and(|run| {
4437            run.replaces.is_some()
4438                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4439                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4440        });
4441    let stop_pin = task
4442        .resume_override
4443        .as_ref()
4444        .filter(|pin| {
4445            Questions::open().get(&pin.question_id).is_ok_and(|q| {
4446                q.node == land::APPROVAL_NODE
4447                    && q.resolution()
4448                        .as_deref()
4449                        .is_some_and(crate::merge_decision::stops)
4450            })
4451        })
4452        .and_then(|pin| pin.pinned_run.clone());
4453    let starter = if let Some(owner) = &public_owner {
4454        Starter::Resume(owner.id.clone())
4455    } else if let Some(run) = stop_pin {
4456        // Stop actions resume their exact owner even after seat-count edits;
4457        // they must never fall through to implementation or a takeover.
4458        Starter::Resume(run)
4459    } else if retry_selected {
4460        Starter::Resume(previous.as_ref().unwrap().id.clone())
4461    } else if let Some(selected) = &task.pr_recovery {
4462        if selected.check_task(&task.id, &task.instruction).is_ok() {
4463            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4464        } else {
4465            Starter::Review(selected.branch.clone())
4466        }
4467    } else {
4468        starter_with_implementers(task, previous.as_ref(), proposed)
4469    };
4470    // An explicit resume pin must never degrade into a new competition or
4471    // takeover, including when its run stops being eligible after the answer.
4472    if let Some(pin) = &task.resume_override
4473        && let Some(run) = &pin.pinned_run
4474        && starter != Starter::Resume(run.clone())
4475    {
4476        let run = run.clone();
4477        task.notice_cause("resume-owner", Some(&run), None);
4478        task.hold_machine(Some(format!(
4479            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4480            task.id
4481        )));
4482        record(queue, task);
4483        return Vec::new();
4484    }
4485    if task.replacement.is_some()
4486        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4487        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4488    {
4489        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()));
4490        record(queue, task);
4491        return Vec::new();
4492    }
4493    if let Some(reason) = retained_attempt_hold(
4494        task,
4495        &starter,
4496        config.disk.retained_attempt_limit,
4497        RunState::load,
4498    ) {
4499        // The review choice was consumed above. Preserve it across this hold
4500        // so a later release cannot silently become a fresh implementation.
4501        if let Starter::Review(branch) = &starter {
4502            task.review_branch = Some(branch.clone());
4503        }
4504        task.hold_unrequested_retry(Some(reason));
4505        record(queue, task);
4506        return Vec::new();
4507    }
4508    // Absolute paths of the files the task was filed with, re-read from the
4509    // task now so a file attached while it was held reaches a resumed run
4510    // too. A stored name whose file has gone is an error before any agent is
4511    // paid for, never a silent omission the implementer cannot notice.
4512    let attachments = match task_attachments(queue, task) {
4513        Ok(a) => a,
4514        Err(e) => {
4515            task.attempts += 1;
4516            task.fail_startup_target(
4517                "startup-attachments",
4518                e.name.clone(),
4519                format!("{start_failed}{e:#}"),
4520                opts.max_attempts,
4521            );
4522            record(queue, task);
4523            return Vec::new();
4524        }
4525    };
4526    let startup_pause = stop.pause();
4527    let startup_interrupt = interrupt_pause.clone();
4528    let wait = crate::repo_lock::WaitPolicy::new(
4529        Duration::from_secs(config.graph.timeout_resource_wait),
4530        move || startup_pause.parked() || startup_interrupt.parked(),
4531    );
4532    // Startup includes review takeover and recovery. Do not embed its large
4533    // future in both the wait scope and the surrounding attempt stack frame.
4534    let started = wait.scope(Box::pin(async { match &starter {
4535        Starter::Review(_) if task.pr_recovery.is_some() => {
4536            let selected = task.pr_recovery.clone().expect("selected recovery");
4537            match selected.check_task(&task.id, &task.instruction) {
4538                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4539                    .await
4540                    .map(|mut r| {
4541                        r.state.attachments = attachments.clone();
4542                        r
4543                    }),
4544                Err(e) => Err(e),
4545            }
4546        }
4547        Starter::Review(branch) => {
4548            tracing::info!(
4549                "task {} reopens `{branch}` as a review-only pass",
4550                task.short()
4551            );
4552            // Every earlier attempt is superseded by the one being minted
4553            // now, so a branch one of them still holds may be taken over.
4554            let takeover = crate::handover::Takeover {
4555                earlier: task.earlier_attempts().to_vec(),
4556                home: crate::run::home(),
4557                choice: take_divergence_answer(branch, &config.merge.remote, task),
4558                task_instruction: Some(instruction_for(task)),
4559            };
4560            Runner::review_taking_over(
4561                &repo,
4562                branch,
4563                config,
4564                Some(takeover),
4565                crate::run::Origin::queue(&task.id),
4566            )
4567            .await
4568        }
4569        Starter::Resume(id) => {
4570            tracing::info!("resuming run {id} rather than competing again");
4571            Runner::resume(id).and_then(|mut r| {
4572                if retry_selected {
4573                    // The explicit queue release retries this same pinned
4574                    // implementation, preserving the attempt and worktrees.
4575                    for candidate in &mut r.state.candidates {
4576                        candidate.failed = None;
4577                        candidate.empty = false;
4578                        candidate.commits = 0;
4579                    }
4580                    r.state.status = RunStatus::Implementing;
4581                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4582                }
4583                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4584                    r.state.sources = task.sources.clone();
4585                }
4586                if r.state.prep_failure.is_some() {
4587                    let approval = task
4588                        .resumption
4589                        .as_ref()
4590                        .context("preparation retry requires an explicit task release")?;
4591                    r.retry_preparation(approval.at)?;
4592                }
4593                if let Some(instruction) =
4594                    prepare_instruction(&starter, Some(&r.state.instruction), task)
4595                {
4596                    r.state.instruction = instruction;
4597                }
4598                r.state.attachments = attachments.clone();
4599                if task.replacement.is_some() {
4600                    r.state.config.merge.mode = MergeMode::Pr;
4601                    r.state.config.graph.land_approval = true;
4602                }
4603                // Replacements publish a new PR and ask again. Selected PR
4604                // recoveries keep their saved disposition; ordinary runs can
4605                // retain the task's merge override.
4606                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4607                    .overrides
4608                    .as_ref()
4609                    .and_then(|o| o.merge.as_deref())
4610                    .and_then(|m| merge_mode(m).ok())
4611                {
4612                    r.state.config.merge.mode = mode;
4613                }
4614                Ok(r)
4615            })
4616        }
4617        Starter::Start => {
4618            if let Some(branch) = &review_branch {
4619                tracing::warn!(
4620                    "conductor chose review for task {} but branch `{branch}` no longer \
4621                     exists; requeuing as a fresh competition instead",
4622                    task.short()
4623                );
4624            }
4625            let instruction = prepare_instruction(&starter, None, task)
4626                .unwrap_or_else(|| task.instruction.clone());
4627            Runner::start_naming(
4628                &repo,
4629                instruction,
4630                &task.title,
4631                config,
4632                crate::run::Origin::queue(&task.id),
4633            )
4634            .await
4635            .map(|mut r| {
4636                r.state.attachments = attachments.clone();
4637                r.state.sources = task.sources.clone();
4638                r
4639            })
4640        }
4641    }})).await;
4642    if let Err(error) = &started
4643        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
4644    {
4645        task.record_startup_failure(failure.clone());
4646    }
4647    let mut runner = match started {
4648        Ok(r) => r,
4649        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4650            task.last_error = Some(e.to_string());
4651            if stop.parking() || interrupt_pause.parked() {
4652                let attempts = task.attempts;
4653                task.park(e.to_string());
4654                // Startup has not spent an attempt to refund.
4655                task.attempts = attempts;
4656            } else {
4657                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4658            }
4659            record(queue, task);
4660            return Vec::new();
4661        }
4662        // A branch an earlier attempt still holds and magi will not release
4663        // by itself is the operator's call, not a failed attempt: hold the
4664        // task with the reason, spend nothing, and say so on the bell.
4665        Err(e) if task.pr_recovery.is_some() => {
4666            task.startup_notice_cause("startup-public-head");
4667            task.attempts += 1;
4668            task.last_error = Some(format!("{start_failed}{e:#}"));
4669            task.hold_unrequested_retry(Some(format!(
4670                "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."
4671            )));
4672            record(queue, task);
4673            return Vec::new();
4674        }
4675        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4676            let detail = match e.downcast_ref::<crate::handover::Refused>() {
4677                Some(r) => (p.handover_refused)(r),
4678                None => format!("{e:#}"),
4679            };
4680            task.startup_notice_cause("startup-handover");
4681            let reason = format!("{start_failed}{detail}");
4682            task.last_error = Some(reason.clone());
4683            // Consumed above by `take`; keep it so the released task retries
4684            // as a review of this same branch.
4685            let branch = match &starter {
4686                Starter::Review(branch) => Some(branch.clone()),
4687                _ => None,
4688            };
4689            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
4690            // one page; the guidance rides in the reason, fixed per state so a
4691            // re-put never changes the wording and relights it.
4692            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4693            record(queue, task);
4694            tracing::warn!(
4695                "holding {} for a branch it cannot take over: {e:#}",
4696                task.short()
4697            );
4698            return Vec::new();
4699        }
4700        // A branch that differs between here and the remote in ways magi
4701        // cannot prove are the same change is a decision for the owner, not a
4702        // failed attempt: ask with both sides laid out, spend no attempt, and
4703        // let the answer requeue the task.
4704        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4705            let d = e
4706                .downcast_ref::<crate::reconcile::Diverged>()
4707                .expect("checked by the guard");
4708            let mut q = ask::Question::new(
4709                task.id.clone(),
4710                crate::reconcile::NODE.to_owned(),
4711                crate::reconcile::SEAT.to_owned(),
4712                d.summary(),
4713                d.detail(),
4714                d.choices(),
4715            );
4716            match Questions::open().put(&mut q) {
4717                Ok(()) => {
4718                    task.last_error = Some(format!("{e:#}"));
4719                    // Consumed above by `take`; the answer has to reach a review
4720                    // of this same branch, so keep pointing the task at it.
4721                    task.review_branch = Some(d.branch.clone());
4722                    task.review_instruction = Some(task.instruction.clone());
4723                    task.block(vec![q.id.clone()], Some(d.summary()));
4724                }
4725                Err(put) => {
4726                    tracing::warn!("could not file the divergence question: {put:#}");
4727                    task.attempts += 1;
4728                    task.fail_startup(
4729                        "startup-question-store",
4730                        format!("{start_failed}{e:#}"),
4731                        opts.max_attempts,
4732                    );
4733                }
4734            }
4735            record(queue, task);
4736            return Vec::new();
4737        }
4738        Err(e) => {
4739            // The answer was stale and nothing was applied: keep pointing at
4740            // the branch so the next attempt asks again against its new tips.
4741            // Nothing went wrong with the task, so no attempt is spent: a
4742            // budget one short of its limit must not hold it instead of
4743            // letting the question be asked again.
4744            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4745                && let Starter::Review(branch) = &starter
4746            {
4747                task.review_branch = Some(branch.clone());
4748                task.review_instruction = Some(task.instruction.clone());
4749                task.last_error = Some(format!("{start_failed}{e:#}"));
4750                task.status = crate::queue::TaskStatus::Failed;
4751                record(queue, task);
4752                return Vec::new();
4753            }
4754            task.attempts += 1;
4755            task.last_error = Some(format!("{start_failed}{e:#}"));
4756            task.startup_notice_cause("startup-source");
4757            task.hold_unrequested_retry(Some(format!(
4758                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4759            )));
4760            record(queue, task);
4761            return Vec::new();
4762        }
4763    };
4764    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4765        runner.state.recovery_config = Some(config_evidence);
4766    }
4767    if let Some(replacement) = &task.replacement {
4768        if matches!(starter, Starter::Start) {
4769            runner.state.instruction.push_str(&format!(
4770                "\n\n# Replacement review context\n{}",
4771                replacement.context
4772            ));
4773        }
4774        runner.state.replaces = Some(replacement.clone());
4775        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4776        if let Ok(mut old) = RunState::load(&replacement.run)
4777            && let Some(d) = &mut old.merge_decision
4778        {
4779            d.replacement_run = Some(runner.state.id.clone());
4780            old.event(
4781                "replacement",
4782                format!(
4783                    "replacement run {} owns the next attempt; old PR remains closed",
4784                    runner.state.id
4785                ),
4786            );
4787            if let Err(e) = old.save() {
4788                let error = runner.fail_startup("replacement-history", e);
4789                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4790                    task.record_startup_failure(failure.clone());
4791                }
4792                task.hold_manual(Some(format!(
4793                    "Could not link replacement history: {error:#}; no agents dispatched"
4794                )));
4795                record(queue, task);
4796                return Vec::new();
4797            }
4798        }
4799    }
4800    runner.state.task_instruction = Some(task.instruction.clone());
4801    // The follow-up depth is fixed now, while the task certainly exists:
4802    // deleting it later must not reset the cap (`crate::followup`).
4803    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4804    if runner.state.origin_chat.is_none() {
4805        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4806    }
4807    // A stop that means "park" reaches the graph through this handle.
4808    runner.on_pause(stop.pause());
4809    // `poll`'s interrupt scheduler reaches this one run - and no other -
4810    // through this handle. See `Pause`'s own doc for why these are never
4811    // the same one.
4812    runner.watch_interrupt(interrupt_pause);
4813
4814    // `start` has minted the run, so the task can now point at it. Persisting
4815    // `Running` before `execute` is what makes a crash mid-run legible.
4816    let run = runner.state.id.clone();
4817    let before_start = task.clone();
4818    task.start(run.clone());
4819    if let Err(error) = queue.put(task) {
4820        *task = before_start;
4821        let error = runner.fail_startup("task-start", error);
4822        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4823            task.record_startup_failure(failure.clone());
4824        }
4825        task.hold_manual(Some(format!(
4826            "Could not persist task start; no agents dispatched: {error:#}"
4827        )));
4828        record(queue, task);
4829        return Vec::new();
4830    }
4831    lock(status).current.push(Current {
4832        worker: None,
4833        task: task.id.clone(),
4834        run,
4835    });
4836
4837    // `RunState::quota` is the run's whole history across every resume, so
4838    // only what this execution added may arm the cooldown or earn a refund.
4839    let quota_before = runner.state.quota.clone();
4840    runner.state.next_pass_task_entry = true;
4841    let result = runner.execute().await;
4842    finish_attempt(
4843        opts.max_attempts,
4844        queue,
4845        task,
4846        &runner.state,
4847        &quota_before,
4848        result,
4849    )
4850}
4851
4852/// Settle `task` after its run executed: the verdict, the diagnosis, the
4853/// supersession of earlier attempts and the save. Shared by the loop and by
4854/// `magi run --resume`, so an attempt is counted one way wherever it ran.
4855/// Returns the quota losses this execution added to the run.
4856pub fn finish_attempt(
4857    max_attempts: usize,
4858    queue: &Queue,
4859    task: &mut Task,
4860    state: &RunState,
4861    quota_before: &[QuotaLoss],
4862    result: Result<()>,
4863) -> Vec<QuotaLoss> {
4864    let detail = match result {
4865        Ok(()) => describe(state),
4866        Err(e) => format!("{e:#}"),
4867    };
4868    let fresh = losses_this_attempt(quota_before, &state.quota);
4869    let verdict = Verdict {
4870        status: state.status,
4871        // A run that opened a pull request handed its work over, whatever the
4872        // gate then decided about merging it.
4873        left_pr: state.pr.is_some(),
4874        // Only a rate limit earns the task its attempt back - and only one
4875        // suffered now: a refund justified by a previous session's loss is
4876        // the same mistake as re-arming the cooldown from it. A stalled run
4877        // resumed without hitting quota again therefore spends its attempt,
4878        // like any other failure of the task's own.
4879        quota_hit: !fresh.is_empty(),
4880        // A run that parked was asked to stop; that is not a failure and must
4881        // not spend an attempt, or replacing the binary a few times would
4882        // exhaust a task's budget without an agent ever misbehaving.
4883        parked: state.parked,
4884        // A quota loss that left nothing viable is the same machine fact as a
4885        // `Stalled` quota loss; see `settle`'s doc table.
4886        no_viable_candidates: state.viable().is_empty(),
4887    };
4888    if let Some(replacement) = &state.replaces
4889        && let Some(pr) = &state.pr
4890        && let Ok(mut old) = RunState::load(&replacement.run)
4891        && let Some(d) = &mut old.merge_decision
4892    {
4893        d.replacement_pr = Some(pr.url.clone());
4894        let _ = old.save();
4895    }
4896    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4897    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4898        task.hold_unrequested_retry(Some(format!(
4899            "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.",
4900            task.short()
4901        )));
4902    }
4903    if task.status == TaskStatus::Done {
4904        supersede_prior_runs(task, &crate::run::home());
4905    }
4906    record(queue, task);
4907    tracing::info!(
4908        "task {} is {} after run {} ({})",
4909        task.short(),
4910        task.status.as_str(),
4911        state.short(),
4912        label(state.status)
4913    );
4914    fresh
4915}
4916
4917/// A task a hand-started run leaves runnable (failed with attempts to spare,
4918/// or requeued) is **held**: nobody asked for a retry, and a loop starting
4919/// later must not spend agent calls on it. `magi task release` retries.
4920pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4921    // Parked work (including legacy Failed records with a parked run) is a
4922    // checkpoint or owner handoff, not an unrequested retry.
4923    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
4924        && !awaiting_resume_with(task, RunState::load)
4925        // A run parked on the owner's word about a withheld PR title/body
4926        // resumes via `land_resume_state`, including review-only tasks that
4927        // `awaiting_resume_with` does not consider.
4928        && withheld_text_wait(task).is_none()
4929        && !(task.fresh_start && task.replacement.is_some())
4930    {
4931        let why = task.last_error.clone().map_or_else(
4932            || "the run did not finish".to_owned(),
4933            |e| format!("the run did not finish: {e}"),
4934        );
4935        task.hold_unrequested_retry(Some(format!(
4936            "{why}. It was started by hand, so it is not retried \
4937             automatically; `magi task release` retries it."
4938        )));
4939        record(queue, task);
4940    }
4941}
4942
4943/// Whether an attempt at a task whose newest run is `run` would resume that
4944/// run rather than start a fresh competition. `magi run --resume` hands a run
4945/// to a live loop only when this holds.
4946#[must_use]
4947pub fn loop_would_resume(run: &str) -> bool {
4948    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4949}
4950
4951/// A loop in another process that is alive right now: a fresh heartbeat in
4952/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
4953/// carries the pid it published (`None` inside when it published none - a
4954/// fresh heartbeat is still evidence of a live loop).
4955///
4956/// The one judgement of "is somebody else serving this queue", shared by the
4957/// web UI's refusal to start a second loop and by `magi run` / `magi review`
4958/// deciding whether to hand a task to the loop. A claim file proves nothing
4959/// here: whether a claim succeeds says nothing about whether its owner lives.
4960#[must_use]
4961pub fn foreign_loop(
4962    reading: Option<&Reading>,
4963    now: Timestamp,
4964    own_pid: u32,
4965) -> Option<Option<u32>> {
4966    let reading = reading.filter(|r| r.running(now))?;
4967    match reading.pid {
4968        Some(pid) if pid == own_pid => None,
4969        pid => Some(pid),
4970    }
4971}
4972
4973fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
4974    reading.worker_protocol != Some(1)
4975        && (foreign_loop(Some(reading), now, own_pid).is_some()
4976            || reading
4977                .pid
4978                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
4979}
4980
4981/// Low-level claimed-task execution shared by the detached standalone worker
4982/// and focused lifecycle fixtures. The caller must retain the queue claim for
4983/// this entire call. CLI callers transfer ownership through
4984/// [`run_detached_claimed`] instead of executing inside their own runtime.
4985///
4986/// The one deliberate difference from the loop: a task the attempt leaves
4987/// runnable (failed with attempts to spare, or requeued) is **held** instead.
4988/// Nobody asked for a retry, and a daemon starting later must not spend agent
4989/// calls re-running a hand-started task behind the operator's back;
4990/// `magi task release` is the explicit retry.
4991pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4992    run_claimed_until(opts, queue, task, &Stop::new()).await;
4993}
4994
4995async fn run_claimed_until(
4996    opts: &Opts,
4997    queue: &Queue,
4998    task: &mut Task,
4999    stop: &Stop,
5000) -> Vec<QuotaLoss> {
5001    let status = Arc::new(Mutex::new(Status::new()));
5002    // An attempt embeds startup and graph futures. Keep it off the standalone
5003    // caller's stack, on both the initial execution and withheld-text resume.
5004    let mut quota = Box::pin(attempt(
5005        opts,
5006        queue,
5007        &status,
5008        stop,
5009        crate::graph::Pause::new(),
5010        task,
5011    ))
5012    .await;
5013    // A run parked on the owner's word about a withheld PR title/body has no
5014    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5015    // here with the claim still held, and resume once the question is settled
5016    // (answered, or abandoned at its deadline -> the neutral text).
5017    // A rejected reply files one more question (the gate asks at most twice),
5018    // so after a resume the run may be waiting again: keep going, with a fresh
5019    // limit for the new question. `resumes` bounds it even if a resume parks
5020    // without asking anything new.
5021    let mut resumes = 0;
5022    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5023        let Some(timeout) = withheld_text_wait(task) else {
5024            break;
5025        };
5026        eprintln!(
5027            "waiting for the owner's answer on a withheld pull request text \
5028             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5029        );
5030        // The deadline abandons the question itself; the extra margin only
5031        // covers an abandon that could not be saved.
5032        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5033        let ready = loop {
5034            match land_resume_state(task) {
5035                LandResume::StillWaiting
5036                    if !stop.parking() && std::time::Instant::now() < limit =>
5037                {
5038                    tokio::time::sleep(WITHHELD_POLL).await;
5039                }
5040                LandResume::Ready => break true,
5041                _ => break false,
5042            }
5043        };
5044        if !ready || stop.parking() {
5045            break;
5046        }
5047        resumes += 1;
5048        quota.extend(
5049            Box::pin(attempt(
5050                opts,
5051                queue,
5052                &status,
5053                stop,
5054                crate::graph::Pause::new(),
5055                task,
5056            ))
5057            .await,
5058        );
5059    }
5060    hold_if_runnable(queue, task);
5061    quota
5062}
5063
5064/// Resumes an in-process run makes for withheld-text questions: the gate asks
5065/// at most twice, plus one for a resume that asks nothing new.
5066const MAX_WITHHELD_RESUMES: u32 = 3;
5067
5068/// How often an in-process run rechecks its withheld-text question.
5069const WITHHELD_POLL: Duration = Duration::from_secs(15);
5070
5071/// The `answer_timeout` (seconds) of the task's last run when that run is
5072/// parked on an unresolved withheld-text question; `None` otherwise.
5073fn withheld_text_wait(task: &Task) -> Option<u64> {
5074    let id = task.runs.last()?;
5075    let s = RunState::load(id).ok()?;
5076    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5077        .then_some(s.config.graph.answer_timeout)
5078}
5079
5080/// The quota losses `after` holds that `before` did not: what one execution
5081/// suffered, as opposed to the run's history.
5082///
5083/// Compared by value rather than by length or position because
5084/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5085/// the vector can shrink and shift under a resume. A retried seat that hits
5086/// quota again is a `push` with a new `at`, so it shows up as new here.
5087/// Crash recovery uses the recorded pass start as its boundary when available;
5088/// legacy records without passes retain their original history-based policy.
5089fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5090    after
5091        .iter()
5092        .filter(|q| !before.contains(q))
5093        .cloned()
5094        .collect()
5095}
5096
5097/// When the loop-wide quota cooldown should end, given this attempt's losses;
5098/// `None` when there were none. Reset-hint parsing and the cap live here.
5099fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5100    let quota: Vec<_> = quota
5101        .iter()
5102        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5103        .collect();
5104    if quota.is_empty() {
5105        return None;
5106    }
5107    let with_hint = quota.iter().find(|q| q.reset.is_some());
5108    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5109    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5110    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5111    Some(
5112        now.checked_add(jiff::SignedDuration::from_secs(secs))
5113            .unwrap_or(Timestamp::MAX),
5114    )
5115}
5116
5117/// An explicit task count must agree with a run before any resume.
5118fn implementers_match(task: &Task, state: &RunState) -> bool {
5119    task.replacement.as_ref().map_or_else(
5120        || {
5121            task.implementers()
5122                .is_none_or(|n| n == state.config.graph.implementers)
5123        },
5124        |replacement| {
5125            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5126                && state.config.graph.implementers == 1
5127        },
5128    )
5129}
5130
5131/// Never resume or take over candidate work built for a different seat count.
5132fn starter_with_implementers(
5133    task: &Task,
5134    previous: Option<&RunState>,
5135    proposed: Starter,
5136) -> Starter {
5137    if previous.is_some_and(|s| !implementers_match(task, s)) {
5138        task.review_of
5139            .as_ref()
5140            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5141    } else {
5142        proposed
5143    }
5144}
5145
5146/// Apply this task's explicit count to the new attempt, without changing defaults.
5147fn apply_task_implementers(config: &mut Config, task: &Task) {
5148    if let Some(n) = task.implementers() {
5149        config.graph.implementers = n;
5150    }
5151}
5152
5153/// [`prepare`] for one task: its own `--config` and command-line overrides
5154/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5155/// over the loop's, so handing a hand-started task to a daemon changes nothing
5156/// about what it does.
5157#[cfg(test)]
5158fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5159    let explicit = match &task.overrides {
5160        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5161        _ => opts.config.as_deref(),
5162    };
5163    let (mut config, _) = Config::discover(repo, explicit)?;
5164    apply_options(&mut config, opts, task)?;
5165    Ok(config)
5166}
5167
5168fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5169    if task
5170        .overrides
5171        .as_ref()
5172        .is_none_or(|o| o.inherit_daemon_options)
5173        && let Some(mode) = opts.merge.as_deref()
5174    {
5175        config.merge.mode = merge_mode(mode)?;
5176    }
5177    if let Some(o) = &task.overrides {
5178        o.apply(config);
5179    }
5180    Ok(())
5181}
5182
5183/// Load the config for a task's repository, with the merge override applied.
5184fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5185    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5186    if let Some(mode) = &opts.merge {
5187        config.merge.mode = merge_mode(mode)?;
5188    }
5189    Ok(config)
5190}
5191
5192/// Prune the shared build cache at a between-runs boundary. The detached cache
5193/// service checks authoritative task jobs first; dispatch waits for that finite
5194/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5195/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5196async fn maybe_prune_cache_between_runs(
5197    repo: &Path,
5198    opts: &Opts,
5199    home: &Path,
5200    stop: &Stop,
5201    last_checked: &mut Option<Timestamp>,
5202    now: Timestamp,
5203) {
5204    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5205        return;
5206    }
5207    *last_checked = Some(now);
5208    let cfg = match prepare(repo, opts) {
5209        Ok(cfg) => cfg,
5210        Err(e) => {
5211            tracing::warn!("cache check: no config: {e:#}");
5212            return;
5213        }
5214    };
5215    match clean::prune_cache_if_over_limit(&cfg, home) {
5216        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5217            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5218            pruned.files,
5219            pruned.freed
5220        ),
5221        Ok(_) => {}
5222        Err(e) => {
5223            tracing::warn!("housekeep: prune cache: {e:#}");
5224            notices::raise_in(
5225                home,
5226                Notice::warn(
5227                    "housekeep:cache",
5228                    format!(
5229                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5230                        e.to_string()
5231                            .lines()
5232                            .next()
5233                            .unwrap_or("unknown cleanup error")
5234                    ),
5235                ),
5236            );
5237        }
5238    }
5239}
5240
5241/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5242/// now, given when it last did (if ever). Pure, so the cadence is asserted
5243/// directly rather than by waiting out real minutes in a test.
5244fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5245    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5246}
5247
5248/// The disk janitor, with its housekeeping logged rather than fatal.
5249///
5250/// Called only at the loop's idle points, for the reason the caller documents:
5251/// a prune racing a live compile would delete files mid-build. The config is
5252/// re-read on every call because the repository that just ran may not be the
5253/// daemon's own default, and the cache directory is a repository fact.
5254///
5255/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5256/// and [`crate::run::default_worktree_root`] read here, for the same reason
5257/// [`drive`] takes its queue and status file rather than resolving them: a
5258/// test driving the loop must not reach through to the operator's real home
5259/// or worktree bay just because the janitor runs on every idle tick.
5260/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5261/// to get wrong silently - a test's `home` was already isolated, but nothing
5262/// exercised the parameter next to it, so a real worktree bay stayed wired in
5263/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5264/// it for real, every test in this file that drives the loop at all started
5265/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5266async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5267    let cfg = match prepare(repo, opts) {
5268        Ok(cfg) => cfg,
5269        Err(e) => {
5270            tracing::warn!("housekeep: no config: {e:#}");
5271            return;
5272        }
5273    };
5274    // A run's own worktree lives under `config.graph.worktree_root` when the
5275    // repository sets one - the same precedence `RunState::worktree_root`
5276    // uses - and `worktrees_root` only stands in for the *default* an
5277    // unconfigured repository resolves to (see this function's own
5278    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5279    // that always swept the default regardless of this override would never
5280    // see, and so never reclaim, a single worktree for a repository that
5281    // relocated them elsewhere.
5282    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5283    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5284    // Reported whenever there is anything to say, not only when `folded > 0`:
5285    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5286    // folded, on every single pass, for months - a report gated on `folded`
5287    // would have stayed silent through every one of them.
5288    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5289        let mut extra = Vec::new();
5290        if out.unreadable > 0 {
5291            extra.push(format!("{} unreadable", out.unreadable));
5292        }
5293        if out.orphaned_worktrees > 0 {
5294            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5295        }
5296        let detail = if extra.is_empty() {
5297            String::new()
5298        } else {
5299            format!(" ({})", extra.join(", "))
5300        };
5301        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5302    }
5303    if out.external_merges_recorded > 0 {
5304        tracing::info!(
5305            "housekeep: recorded {} run(s) as merged externally",
5306            out.external_merges_recorded
5307        );
5308    }
5309    if out.stale_pr_states_repaired > 0 {
5310        tracing::info!(
5311            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5312            out.stale_pr_states_repaired
5313        );
5314    }
5315    if out.cache_files > 0 {
5316        tracing::info!(
5317            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5318            out.cache_files,
5319            out.cache_freed
5320        );
5321    }
5322    if out.questions_abandoned > 0 {
5323        tracing::info!(
5324            "housekeep: abandoned {} question(s) left open by a finished run",
5325            out.questions_abandoned
5326        );
5327    }
5328}
5329
5330/// Run [`triage::run_once`] and log whatever it did, the same "only when
5331/// there is something to say" rule [`janitor`] follows for its own report.
5332///
5333/// Called at the same idle points as [`janitor`] - once per full poll
5334/// interval, never mid-attempt - for the same reason: it is not liveness
5335/// critical, and a task's own `hold_reason` string is the one thing this
5336/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5337/// tick for no benefit.
5338async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5339    let questions = Questions::at(home.join("questions"));
5340    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5341    if report.is_empty() {
5342        return;
5343    }
5344    if !report.quarantined.is_empty() {
5345        tracing::info!(
5346            "triage: held {} blocked task(s) whose blocked-on task or \
5347             question no longer exists: {}",
5348            report.quarantined.len(),
5349            report.quarantined.join(", ")
5350        );
5351    }
5352    if !report.resumed.is_empty() {
5353        tracing::info!(
5354            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5355            report.resumed.len(),
5356            report.resumed.join(", ")
5357        );
5358    }
5359    if !report.asked.is_empty() {
5360        tracing::info!(
5361            "triage: asked about {} held task(s): {}",
5362            report.asked.len(),
5363            report.asked.join(", ")
5364        );
5365    }
5366    if !report.answered.is_empty() {
5367        tracing::info!(
5368            "triage: applied {} operator answer(s): {}",
5369            report.answered.len(),
5370            report.answered.join(", ")
5371        );
5372    }
5373}
5374
5375/// The free-space gate: what stands between this task and a new run, if
5376/// anything. `Some(reason)` holds the task; `None` lets it start.
5377///
5378/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5379/// the operator opted out. A measurement failure is a gate, not a pass: both
5380/// sides of "cannot tell" are served by not starting.
5381pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5382    disk_gate_with(repo, config, crate::disk::free_bytes)
5383}
5384
5385/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
5386/// test can assert the exact wiring `attempt` runs - config's threshold in,
5387/// task-holding reason out - without asking the real machine's disk anything.
5388fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5389    repo: &Path,
5390    config: &Config,
5391    free_bytes: F,
5392) -> Option<String> {
5393    let min = config.disk.min_free_bytes;
5394    if min == 0 {
5395        return None;
5396    }
5397    let mut paths = vec![repo.to_owned()];
5398    if let Some(cache) = config.cache_dir() {
5399        paths.push(cache);
5400    }
5401    if let Some(root) = &config.graph.worktree_root {
5402        paths.push(root.clone());
5403    }
5404    for path in paths {
5405        let probe = if path == repo {
5406            path.as_path()
5407        } else {
5408            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5409        };
5410        let reason = match free_bytes(probe) {
5411            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5412            Err(e) => Some(crate::disk::unmeasured_in(
5413                probe,
5414                &e,
5415                &config.graph.language,
5416            )),
5417        };
5418        if reason.is_some() {
5419            return reason;
5420        }
5421    }
5422    None
5423}
5424
5425/// How long to wait before offering another task when a run lost a seat to a
5426/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
5427/// could read, or carried nothing at all. Long enough that a quota outage
5428/// cannot burn through a whole backlog in the few seconds each doomed attempt
5429/// takes to fail; short enough that a quota which clears early is not left
5430/// idle for the fallback's sake.
5431const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5432
5433/// Longest a parsed reset hint may push the wait out to. The hint comes from
5434/// the CLI's own words, not a contract, so a parsing slip that lands a day
5435/// away must not leave the loop asleep for a day.
5436const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5437
5438/// How long [`poll`] should wait before offering the next task, after a run
5439/// lost at least one seat to a rate limit.
5440///
5441/// Pure and separate from the loop so the policy can be exercised without a
5442/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
5443/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
5444/// nothing to parse, or the parsed time has already passed; `cap` bounds how
5445/// far a parsed hint is trusted to push the wait out.
5446fn quota_wait(
5447    reset_at: Option<Timestamp>,
5448    now: Timestamp,
5449    fallback: Duration,
5450    cap: Duration,
5451) -> Duration {
5452    match reset_at {
5453        Some(at) if at > now => {
5454            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5455            Duration::from_secs(secs).min(cap)
5456        }
5457        _ => fallback,
5458    }
5459}
5460
5461/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
5462///
5463/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
5464/// explains why parsing it exactly "would be a bug factory" — so this only
5465/// recognises the shapes actually observed in the wild, and returns `None`
5466/// for anything else rather than guess at a format nobody has seen.
5467///
5468/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
5469/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
5470/// said it, not from whenever this loop happens to read it: anchoring on `now`
5471/// would push the reset later on every read and would read an already-elapsed
5472/// reset as still in the future. (A long hint is still clamped by
5473/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
5474fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5475    parse_reset_hint_zoned(text, now)
5476        .or_else(|| parse_reset_hint_dated(text))
5477        .or_else(|| parse_reset_hint_relative(text, recorded))
5478}
5479
5480/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
5481/// optional but at least one required, in that order. A bare number or any
5482/// unknown unit is refused.
5483fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5484    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5485    let mut rest = rest.trim();
5486    if rest.is_empty() {
5487        return None;
5488    }
5489    let mut total: i64 = 0;
5490    let mut matched = false;
5491    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5492        if let Some((digits, tail)) = rest.split_once(unit)
5493            && !digits.is_empty()
5494            && digits.bytes().all(|b| b.is_ascii_digit())
5495        {
5496            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5497            rest = tail;
5498            matched = true;
5499        }
5500    }
5501    if !rest.is_empty() || !matched {
5502        return None;
5503    }
5504    recorded
5505        .checked_add(jiff::SignedDuration::from_secs(total))
5506        .ok()
5507}
5508
5509/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
5510/// case-insensitive) into a 24-hour hour and minute. Shared by every
5511/// reset-hint shape below.
5512fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5513    let clock = clock.trim().to_lowercase();
5514    let (digits, pm) = clock
5515        .strip_suffix("am")
5516        .map(|d| (d, false))
5517        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5518    let (h, m) = digits.trim().split_once(':')?;
5519    let mut hour: i8 = h.trim().parse().ok()?;
5520    let minute: i8 = m.trim().parse().ok()?;
5521    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5522        return None;
5523    }
5524    if pm && hour != 12 {
5525        hour += 12;
5526    } else if !pm && hour == 12 {
5527        hour = 0;
5528    }
5529    Some((hour, minute))
5530}
5531
5532/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
5533/// and a zone, never a date. A clock reading already past today is read as
5534/// tomorrow's: a CLI naming a same-day reset that has already gone by means
5535/// the window rolled over while nothing was watching.
5536fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5537    let open = text.find('(')?;
5538    let close = text.rfind(')')?;
5539    if close <= open {
5540        return None;
5541    }
5542    let zone = text[open + 1..close].trim();
5543    let (hour, minute) = parse_12h_clock(&text[..open])?;
5544    let tz = jiff::tz::TimeZone::get(zone).ok()?;
5545    let candidate = now
5546        .to_zoned(tz)
5547        .with()
5548        .hour(hour)
5549        .minute(minute)
5550        .second(0)
5551        .millisecond(0)
5552        .microsecond(0)
5553        .nanosecond(0)
5554        .build()
5555        .ok()?;
5556    let mut at = candidate.timestamp();
5557    if at <= now {
5558        at += jiff::SignedDuration::from_hours(24);
5559    }
5560    Some(at)
5561}
5562
5563/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
5564/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
5565/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
5566/// "already past today" correction to make: the year already disambiguates
5567/// it. Scanned as a five-word window so it can be pulled out of the middle
5568/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
5569/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
5570/// any other timestamp with no zone attached.
5571fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5572    let words: Vec<&str> = text.split_whitespace().collect();
5573    if words.len() < 5 {
5574        return None;
5575    }
5576    (0..=words.len() - 5)
5577        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5578}
5579
5580/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
5581/// parenthesis right after the window is refused rather than ignored — it
5582/// reads as an explicit zone annotation on a shape that otherwise carries
5583/// none, and guessing UTC anyway would be exactly the silent misread this
5584/// module's parsing otherwise avoids.
5585fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5586    if trailing.is_some_and(|next| next.starts_with('(')) {
5587        return None;
5588    }
5589    let month = month_number(window[0])?;
5590    let day_token = window[1].strip_suffix(',')?.to_lowercase();
5591    let day_digits = ["st", "nd", "rd", "th"]
5592        .iter()
5593        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5594    let day: i8 = day_digits.parse().ok()?;
5595    let year_token = window[2];
5596    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5597        return None;
5598    }
5599    let year: i16 = year_token.parse().ok()?;
5600    // The am/pm word carries the sentence's own trailing punctuation, e.g.
5601    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
5602    // reusing the same 12-hour clock reader the bracketed shape uses.
5603    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5604    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5605    let date = jiff::civil::Date::new(year, month, day).ok()?;
5606    let candidate = date
5607        .at(hour, minute, 0, 0)
5608        .to_zoned(jiff::tz::TimeZone::UTC)
5609        .ok()?;
5610    Some(candidate.timestamp())
5611}
5612
5613/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
5614/// case-insensitively, into a 1-based month number.
5615fn month_number(name: &str) -> Option<i8> {
5616    const NAMES: [&str; 12] = [
5617        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5618    ];
5619    let lower = name.to_lowercase();
5620    NAMES
5621        .iter()
5622        .position(|n| *n == lower.as_str())
5623        .map(|i| i as i8 + 1)
5624}
5625
5626/// Test probe for the shared resume policy's review-budget exclusion.
5627#[cfg(test)]
5628fn exhausted_review_budget(state: &RunState) -> bool {
5629    // A run whose task-head publication failed has nothing left to review:
5630    // resuming it only retries the publication, so it is never "exhausted".
5631    !crate::handover::can_resume(state)
5632        && state.status == RunStatus::Blocked
5633        && !state.released()
5634        && state.retired_to.is_none()
5635}
5636
5637/// This task's *most recent* run, if resuming it would actually make
5638/// progress. `short` is only for the warning's own message.
5639///
5640/// Only ever `runs.last()` — never a search back through older history.
5641/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
5642/// mint, oldest first, and every entry before the last one was already
5643/// superseded at the moment it was minted: the daemon only ever starts a new
5644/// run when the previous one was not worth resuming (unresumable, exhausted,
5645/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
5646/// opens a fresh review-only run alongside an older, already-failed
5647/// competition. Searching further back would let an old run that merely
5648/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
5649/// behind, say — get resumed instead of the fresh competition
5650/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
5651/// nothing asked to revisit.
5652///
5653/// Two runs paid for the "prefer resuming over restarting" half of this
5654/// lesson, which is why this still checks `runs.last()` rather than always
5655/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
5656/// task a moment later, duplicating two and a half hours of agent work. Then
5657/// b25f stalled on a judge that timed out and one that answered with no JSON
5658/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
5659/// **one second** later, buying three fresh implementations to reach the
5660/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
5661/// the second case: a stall is terminal, and its cheap recovery re-asks only
5662/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
5663/// that is technically `resumable()` but provably cannot progress must not
5664/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
5665/// no-op instead of the fresh competition it promises.
5666///
5667/// A load failure is warned about rather than silently read as "not
5668/// resumable": the alternative is exactly what let a schema mismatch on run
5669/// `eba2` fall through to a full re-competition with nobody told why.
5670/// `crate::conduct` is what actually offers a better answer than
5671/// `Runner::start` here (see `Recovery::Review`), once this task's next
5672/// failure shows it up as `held`/`failed` with the run state unreadable.
5673fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5674    unfinished_run_with(runs, short, RunState::load)
5675}
5676
5677/// [`unfinished_run`] with an injected state reader. Tests provide their
5678/// fixtures directly rather than touching the process-global run home.
5679pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5680where
5681    F: FnMut(&str) -> Result<RunState>,
5682{
5683    let mut id = runs.last()?.clone();
5684    let mut visited = std::collections::BTreeSet::new();
5685    let mut repo = None;
5686    loop {
5687        if !runs.contains(&id) || !visited.insert(id.clone()) {
5688            tracing::warn!("invalid or cyclic recovery authority for task {short}");
5689            return None;
5690        }
5691        let state = match load(&id) {
5692            Ok(state) if state.id == id => state,
5693            Ok(_) => return None,
5694            Err(e) => {
5695                tracing::warn!("could not read run {id} for task {short}: {e:#}");
5696                return None;
5697            }
5698        };
5699        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5700            return None;
5701        }
5702        repo = Some(state.repo.clone());
5703        if let Some(authority) = state.retired_to {
5704            id = authority;
5705            continue;
5706        }
5707        return (crate::handover::can_resume(&state)
5708            && state.liveness(false) != crate::run::Liveness::Live)
5709            .then_some(id);
5710    }
5711}
5712
5713/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
5714/// that [`attempt`] will resume it on its own?
5715///
5716/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
5717/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
5718/// injected reader like its sibling. An unreadable run is not awaiting
5719/// anything: it keeps going to the conductor as before.
5720fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5721where
5722    F: FnOnce(&str) -> Result<RunState>,
5723{
5724    // `Failed` stays: a record an older build wrote for a parked run.
5725    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5726        || task.fresh_start
5727        || task.review_branch.is_some()
5728    {
5729        return false;
5730    }
5731    let Some(id) = task.runs.last() else {
5732        return false;
5733    };
5734    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
5735}
5736
5737/// Which of the three ways [`attempt`] can mint or continue a run this task
5738/// should use.
5739#[derive(Debug, Clone, PartialEq, Eq)]
5740enum Starter {
5741    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
5742    /// and that still exists.
5743    Review(String),
5744    /// `crate::graph::Runner::resume` on an unfinished run of this task.
5745    Resume(String),
5746    /// `crate::graph::Runner::start`: a fresh competition.
5747    Start,
5748}
5749
5750/// A second bound independent of inputs and the resettable failure counter.
5751/// Count execution and failed-startup recovery records once per run. Startup
5752/// failures can retain unrecorded preparation assets without an execution pass.
5753/// Unknown history is not evidence that a new set of worktrees is affordable.
5754fn retained_attempt_hold(
5755    task: &Task,
5756    starter: &Starter,
5757    limit: usize,
5758    mut load: impl FnMut(&str) -> Result<RunState>,
5759) -> Option<String> {
5760    if limit == 0 || matches!(starter, Starter::Resume(_)) {
5761        return None;
5762    }
5763    let mut retained = 0;
5764    for id in task
5765        .runs
5766        .iter()
5767        .chain(task.startup_failures.iter().map(|failure| &failure.run))
5768        .collect::<std::collections::BTreeSet<_>>()
5769    {
5770        let state = match load(id) {
5771            Ok(state) if state.id == *id => state,
5772            _ => {
5773                return Some(format!(
5774                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5775                ));
5776            }
5777        };
5778        if state.retired_to.is_some() || state.released() {
5779            continue;
5780        }
5781        // Neither a completed status nor an empty candidate array proves that
5782        // all recovery sources (including unrecorded preparation) were retired.
5783        retained += 1;
5784    }
5785    (retained >= limit).then(|| format!(
5786        "[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."
5787    ))
5788}
5789
5790/// A selected public implementation overrides every historical candidate and pin.
5791fn selected_starter(
5792    selected: &crate::pr_recovery::Selection,
5793    previous: Option<&RunState>,
5794    unfinished: Option<&str>,
5795) -> Starter {
5796    if let Some(id) = unfinished
5797        && previous.is_some_and(|r| {
5798            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5799        })
5800    {
5801        Starter::Resume(id.to_owned())
5802    } else {
5803        Starter::Review(selected.branch.clone())
5804    }
5805}
5806
5807/// The owner's answer to this branch's divergence question, consumed from the
5808/// task so a later, different divergence asks again. The runner applies it
5809/// (see `Runner::review_taking_over`), after the earlier worktree is released.
5810fn take_divergence_answer(
5811    branch: &str,
5812    remote: &str,
5813    task: &mut Task,
5814) -> Option<crate::reconcile::Choice> {
5815    let summary = crate::reconcile::summary_for(branch, remote);
5816    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5817        (a.question == summary)
5818            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5819            .flatten()
5820            .map(|c| (i, c))
5821    })?;
5822    task.answers.remove(idx);
5823    Some(choice)
5824}
5825
5826/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
5827/// this attempt should use. Pure, and separate from [`attempt`], so the
5828/// routing itself is assertable without spawning a real graph or a git
5829/// process: `attempt`'s own `crate::git::branch_exists` call has already
5830/// happened by the time this is called.
5831///
5832/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
5833/// whose branch is gone falls all the way through to [`Starter::Start`], not
5834/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
5835/// old (likely `Blocked`) run in the first place, and a branch that vanished
5836/// out from under that choice is not evidence resuming it would fare better.
5837fn choose_starter(
5838    review_branch: Option<&str>,
5839    branch_exists: bool,
5840    unfinished: Option<&str>,
5841) -> Starter {
5842    match review_branch {
5843        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5844        Some(_) => Starter::Start,
5845        None => match unfinished {
5846            Some(id) => Starter::Resume(id.to_owned()),
5847            None => Starter::Start,
5848        },
5849    }
5850}
5851
5852/// Reuse a compatible latest review owner instead of taking its checked-out
5853/// branch into a new run. Different branches and changed criteria still use
5854/// the ordinary review/takeover policy.
5855fn review_retry_starter(
5856    task: &Task,
5857    previous: Option<&RunState>,
5858    branch: Option<&str>,
5859    exists: bool,
5860    unfinished: Option<&str>,
5861) -> Starter {
5862    if let Some(run) = previous
5863        && unfinished == Some(run.id.as_str())
5864        && run.reviewed_commits.is_some()
5865        && branch.is_some_and(|branch| {
5866            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
5867        })
5868        && may_resume_run(run, task)
5869    {
5870        return Starter::Resume(run.id.clone());
5871    }
5872    match (branch, unfinished, &task.review_of) {
5873        (None, None, Some(branch)) => Starter::Review(branch.clone()),
5874        _ => choose_starter(branch, exists, unfinished),
5875    }
5876}
5877
5878/// Consume a retained review only while its authored criteria still match.
5879fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5880    let branch = task.review_branch.take();
5881    let instruction = task.review_instruction.take();
5882    branch.filter(|branch| match &instruction {
5883        Some(authored) => *authored == task.instruction,
5884        // Legacy retained branches must agree with their prior run; only an
5885        // explicitly pinned review can proceed without recoverable provenance.
5886        None => previous.map_or_else(
5887            || task.review_of.as_ref() == Some(branch),
5888            |run| compatible_run_instruction(run, task),
5889        ),
5890    })
5891}
5892
5893/// A current explicit pin can select an otherwise incompatible run. Edits
5894/// and subsequent approvals invalidate pins selected for earlier criteria.
5895fn may_resume_run(run: &RunState, task: &Task) -> bool {
5896    task.resume_override
5897        .as_ref()
5898        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5899        || compatible_run_instruction(run, task)
5900}
5901
5902/// Review scaffolding is execution context, not evidence of an operator edit.
5903pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5904    if let Some(authored) = &run.task_instruction {
5905        return compatible_instruction(authored, task);
5906    }
5907    if compatible_instruction(&run.instruction, task) {
5908        return true;
5909    }
5910    // Recognize only the existing generated review shapes on legacy runs.
5911    // Ordinary authored text with a similar heading is left intact.
5912    if run.reviewed_commits.is_some() {
5913        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5914            return strip_answers_block(authored, task).trim() == task.instruction.trim();
5915        }
5916        if let Some(branch) = &task.review_of {
5917            let canonical = format!(
5918                "Review the branch `{branch}` (review-only: no implementation, no judging)."
5919            );
5920            let generated = format!(
5921                "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"
5922            );
5923            return task.instruction == canonical && run.instruction.starts_with(&generated);
5924        }
5925    }
5926    false
5927}
5928
5929/// Compare authored instructions, excluding answer blocks appended by the daemon.
5930pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5931    strip_answers_block(old, task) == task.instruction
5932}
5933
5934/// Which repository a task runs in. A task that names none — the normal case
5935/// for one filed from a phone — runs in the daemon's own default.
5936fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5937    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5938        return fallback.to_path_buf();
5939    }
5940    task.repo.clone()
5941}
5942
5943/// The header [`append_answers`] appends operator answers under. Shared with
5944/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
5945/// rather than grown a new block on every resume.
5946const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5947
5948/// Render the first `count` answers in the block appended to an instruction.
5949fn answers_block(task: &Task, count: usize) -> String {
5950    let mut s = ANSWERS_HEADER.to_owned();
5951    for a in &task.answers[..count] {
5952        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5953    }
5954    s
5955}
5956
5957/// Render the approval independently of transient task state, so historical
5958/// suffixes remain recognizable after another explicit release.
5959fn resumption_block(r: &crate::queue::Resumption) -> String {
5960    format!(
5961        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5962         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5963        r.generation, r.at, r.instruction, r.answers_through,
5964    )
5965}
5966
5967/// Append audit answers and the latest explicit approval to the instruction.
5968fn append_answers(base: &str, task: &Task) -> String {
5969    let mut s = base.to_owned();
5970    if !task.answers.is_empty() {
5971        s.push_str(&answers_block(task, task.answers.len()));
5972    }
5973    if let Some(r) = &task.resumption {
5974        s.push_str(&resumption_block(r));
5975    }
5976    s
5977}
5978
5979/// Drop the prior answer block only when it is exactly the suffix this task
5980/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
5981/// the task author is ordinary instruction text, not a block to remove.
5982fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5983    let mut instruction = instruction;
5984    for approval in task
5985        .resumption
5986        .iter()
5987        .chain(task.resumption_history.iter().rev())
5988    {
5989        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5990            instruction = base;
5991            break;
5992        }
5993    }
5994    for count in (1..=task.answers.len()).rev() {
5995        let block = answers_block(task, count);
5996        if let Some(base) = instruction.strip_suffix(&block) {
5997            return base;
5998        }
5999    }
6000    instruction
6001}
6002
6003/// The instruction handed to `Runner::start`: the task's own text, plus any
6004/// operator answers `crate::conduct` collected for it (see
6005/// [`Task::answers`]), so a decision the operator actually made reaches the
6006/// implementers rather than only clearing the block that was waiting on it.
6007///
6008/// Appended rather than merged into [`Task::instruction`] itself, so the
6009/// task's own record stays exactly what its author wrote.
6010fn instruction_for(task: &Task) -> String {
6011    append_answers(&task.instruction, task)
6012}
6013
6014/// The instruction a resumed run should carry on with: whatever it already
6015/// had, refreshed with the task's *current* operator answers.
6016///
6017/// A resumable run's own `RunState::instruction` predates any answer
6018/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6019/// the behaviour before this function existed — silently drops the very
6020/// decision the operator made to unblock it. Re-stripping any block this
6021/// function appended on an earlier resume before re-appending the current
6022/// list (rather than blindly appending again) is what keeps a task resumed
6023/// three times over three answered questions from carrying the same answer
6024/// three times.
6025fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6026    append_answers(strip_answers_block(old_instruction, task), task)
6027}
6028
6029/// Preserve the producer's verified boundary and target, independent of prose.
6030fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6031    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6032    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6033    if let Some(cause) = task.hold_notice_cause.as_mut() {
6034        cause.target = failure.map(|f| f.target.clone());
6035    }
6036}
6037
6038#[derive(Debug, thiserror::Error)]
6039#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6040struct MissingAttachment {
6041    name: String,
6042    path: PathBuf,
6043}
6044
6045/// The task's attachments as absolute paths, each checked to still exist.
6046fn task_attachments(
6047    queue: &Queue,
6048    task: &Task,
6049) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6050    let paths = queue.attachment_paths(task);
6051    for (name, path) in task.attachments.iter().zip(&paths) {
6052        if !path.is_file() {
6053            return Err(MissingAttachment {
6054                name: name.clone(),
6055                path: path.clone(),
6056            });
6057        }
6058    }
6059    Ok(paths)
6060}
6061
6062/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6063/// answers before handing it to `Runner` — the actual boundary between
6064/// [`choose_starter`]'s routing and the graph, factored out so it is
6065/// assertable without a real repository, git branch, or agent CLI.
6066///
6067/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6068/// instruction from the reviewed branch's own commit log because there is no
6069/// task statement to speak of for hand-written work, and splicing operator
6070/// answers into that text would contradict the very message it sends
6071/// reviewers ("there is no task statement").
6072fn prepare_instruction(
6073    starter: &Starter,
6074    old_instruction: Option<&str>,
6075    task: &Task,
6076) -> Option<String> {
6077    match starter {
6078        Starter::Start => Some(instruction_for(task)),
6079        Starter::Resume(_) => Some(resumed_instruction(
6080            old_instruction.expect("a resumed run always has a prior instruction"),
6081            task,
6082        )),
6083        Starter::Review(_) => None,
6084    }
6085}
6086
6087/// Persist a transition. A queue write failure is logged rather than fatal: the
6088/// run already happened, and taking the daemon down would only add a lost
6089/// backlog to a full disk.
6090fn record(queue: &Queue, task: &mut Task) {
6091    if let Err(e) = queue.put(task) {
6092        tracing::error!("could not record task {}: {e:#}", task.short());
6093        let notice = Notice::error(
6094            "loop:record",
6095            format!(
6096                "Task {} state could not be saved: {}. Check the disk.",
6097                task.id,
6098                e.to_string().lines().next().unwrap_or("unknown save error")
6099            ),
6100        )
6101        .link(Link::Task {
6102            id: task.id.clone(),
6103        });
6104        // The queue lives at `<home>/queue`, so its parent is the home.
6105        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6106            Some(home) => notices::raise_in(home, notice),
6107            None => notices::raise(notice),
6108        }
6109    }
6110}
6111
6112/// Every runnable task, in the order the loop should try them.
6113///
6114/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6115/// tail exists so that a claim somebody else holds costs the loop the next
6116/// candidate rather than a whole poll interval of idleness.
6117fn runnable(queue: &Queue) -> Vec<Task> {
6118    let mut tasks: Vec<Task> = queue
6119        .list()
6120        .into_iter()
6121        .filter(|t| t.status.runnable())
6122        .collect();
6123    tasks.sort_unstable_by(crate::queue::dispatch_order);
6124    tasks
6125}
6126
6127/// Why a run ended where it did, in one line, for [`Task::last_error`].
6128///
6129/// A stalled run names the seats the quota took out: "out of quota" is not
6130/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6131/// agent to replace or which plan to top up.
6132///
6133/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6134/// purpose: unlike `label`'s other callers (an internal log line, an
6135/// already-a-bug fallback message), this string becomes `Task::last_error`
6136/// verbatim, which the phone renders in the same alarm-styled box an
6137/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6138/// `.err` styling. A bare `verified_noop` there would read exactly like the
6139/// failure this whole feature exists to tell apart from one.
6140fn describe(state: &RunState) -> String {
6141    let p = phrases(&state.config.graph.language);
6142    let mut detail = if state.status == RunStatus::Stalled {
6143        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6144        seats.sort_unstable();
6145        seats.dedup();
6146        if seats.is_empty() {
6147            p.quorum_lost.to_owned()
6148        } else {
6149            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6150        }
6151    } else {
6152        format!("{}{}", p.run_ended, state.status.display_label())
6153    };
6154    if let Some(cause) = state.verification_blocking_cause() {
6155        detail.push_str(&format!(" ({cause})"));
6156    } else if let Some(last) = state.events.last() {
6157        // The review loop's "never answered" stop is the one event worth
6158        // translating; it is recognised from structured state, not by
6159        // matching the English event text (which stays as recorded).
6160        let unanswered = state
6161            .reviews
6162            .last()
6163            .filter(|r| {
6164                state.status == RunStatus::Blocked
6165                    && last.node == "review"
6166                    && r.incomplete()
6167                    && r.blocking == 0
6168                    && r.round == state.config.graph.review_rounds
6169                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6170            })
6171            .map(|r| (r.expected - r.answered, r.round));
6172        match unanswered {
6173            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6174                detail.push_str(&format!(
6175                    " ({}: {})",
6176                    last.node,
6177                    (p.reviewers_never_answered)(missing, rounds)
6178                ));
6179            }
6180            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6181        }
6182    }
6183    detail.push_str(&format!(" [run {}]", state.id));
6184    detail
6185}
6186
6187/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6188///
6189/// The task file lives in the backlog indefinitely; a diagnostic is an
6190/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6191/// stay small regardless of how much a gate command or a candidate printed.
6192const DIAGNOSTIC_MAX: usize = 4_000;
6193
6194/// Tail kept from a single failing command's output inside a diagnostic.
6195/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6196/// pointer for a human deciding whether to go read the full artifact by hand,
6197/// not a replacement for reading it.
6198const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6199
6200/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6201/// `magi task show` says more than the one-line reason in [`describe`].
6202///
6203/// The one-liner answers "where did the run stop"; this answers "what would a
6204/// human have found opening `artifacts/` by hand" — the point of the whole
6205/// feature is the case that one-liner actively misleads on: a run held as "no
6206/// candidate produced a change" can mean the implementer actually finished
6207/// the task (opened a PR, merged it, tagged a release) and only left a clean
6208/// local worktree behind, which reads as "nothing happened" unless someone
6209/// goes and reads what the agent actually said. `None` when the run carries
6210/// none of the three shapes this recognises — an ordinary run held for
6211/// something not diagnosable from `RunState` alone still explains itself
6212/// through `Task::last_error`.
6213fn diagnostic(state: &RunState) -> Option<String> {
6214    let mut parts: Vec<String> = Vec::new();
6215
6216    // Gate failure: which check(s), and the tail of what each printed.
6217    for o in state.gate.iter().filter(|o| !o.ok()) {
6218        parts.push(format!(
6219            "gate `{}` failed ({}):\n{}",
6220            o.command,
6221            notices::exit_status(o.code),
6222            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6223        ));
6224    }
6225
6226    // The land loop gave up because the fixer declined while checks were
6227    // still red: the message already names them (see `land::run`).
6228    if let Some(last) = state
6229        .events
6230        .iter()
6231        .rev()
6232        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6233    {
6234        parts.push(last.message.clone());
6235    }
6236
6237    // No viable candidate: every implementer's own final word, sanitized the
6238    // same way a judge would have read it, so a run that actually finished
6239    // the job does not read as an unexplained failure. A verified no-op is
6240    // called out ahead of its own summary and apart from an ordinary
6241    // failure's `why` — this is the one candidate shape whose diagnostic a
6242    // human is expected to actually judge, not just skim.
6243    if state.viable().is_empty() {
6244        for c in &state.candidates {
6245            if let Some(evidence) = &c.verified_noop {
6246                parts.push(format!(
6247                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6248                    c.label
6249                ));
6250            } else if !c.summary.trim().is_empty() {
6251                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6252            } else if let Some(why) = &c.failed {
6253                parts.push(format!("candidate {}: {why}", c.label));
6254            }
6255        }
6256    }
6257
6258    if parts.is_empty() {
6259        return None;
6260    }
6261    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6262    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6263    // back slightly over. Leave it enough room to always land under the
6264    // limit.
6265    Some(crate::run::tail(
6266        &parts.join("\n\n"),
6267        DIAGNOSTIC_MAX.saturating_sub(100),
6268    ))
6269}
6270
6271/// Stable lower-case name for a run status, for an internal log line and the
6272/// "graph stopped without reaching a terminal status" bug message in
6273/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6274/// doc for why that one reads [`RunStatus::display_label`] instead. One
6275/// definition of a status's name, on the type that owns it: this table used
6276/// to live here as a second copy, and a status renamed in one place would
6277/// have gone on reading correctly in the other.
6278fn label(status: RunStatus) -> &'static str {
6279    status.as_str()
6280}
6281
6282/// Parse a merge mode override.
6283pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6284    match mode {
6285        "none" => Ok(MergeMode::None),
6286        "local" => Ok(MergeMode::Local),
6287        "pr" => Ok(MergeMode::Pr),
6288        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6289    }
6290}
6291
6292/// Take the status lock, recovering from a poisoned one.
6293///
6294/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6295/// data, and the worst a poisoned lock can hold is a stale timestamp.
6296fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6297    mutex
6298        .lock()
6299        .unwrap_or_else(std::sync::PoisonError::into_inner)
6300}
6301
6302#[cfg(test)]
6303mod tests {
6304    use super::*;
6305    use crate::queue::{Source, TaskStatus};
6306    use crate::run::{Candidate, CommandOutcome};
6307    use pretty_assertions::assert_eq;
6308
6309    fn task() -> Task {
6310        Task::new(
6311            "add retries".to_owned(),
6312            "add retries".to_owned(),
6313            PathBuf::from("/repo"),
6314            Source::Human,
6315        )
6316    }
6317
6318    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6319        let job = crate::worker::Job {
6320            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6321            sequence: 1,
6322            kind: "task".into(),
6323            key: format!("task:{}", request.task),
6324            payload: serde_json::to_value(request).unwrap(),
6325            generation: "a".repeat(64),
6326            version: None,
6327            status: crate::worker::Status::Starting,
6328            result: None,
6329            pid: None,
6330            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6331            finished_at: None,
6332        };
6333        let dir = home.join("workers/jobs").join(&job.id);
6334        std::fs::create_dir_all(&dir).unwrap();
6335        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6336        job
6337    }
6338
6339    #[test]
6340    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6341        let home = tempfile::tempdir().unwrap();
6342        let request = TaskWorker {
6343            opts: Opts::default(),
6344            queue: home.path().join("queue"),
6345            task: "startup".into(),
6346            lane: PermitKind::Ordinary,
6347            standalone: false,
6348        };
6349        let job = starting_task_reservation(home.path(), &request);
6350        let error = task_worker_spawn_error(
6351            home.path(),
6352            &request,
6353            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6354        )
6355        .expect_err("our own reservation must not turn a failed spawn into a resync");
6356        let active = crate::worker::active(home.path()).unwrap();
6357        assert_eq!(active.len(), 1);
6358        assert_eq!(active[0].id, job.id);
6359        assert_eq!(active[0].status, crate::worker::Status::Starting);
6360        assert!(
6361            crate::worker::control(home.path(), &job.key)
6362                .unwrap()
6363                .is_none()
6364        );
6365        let notices = notices::Notices::at(home.path().join("notifications")).list();
6366        assert_eq!(notices.len(), 1);
6367        assert_eq!(notices[0].key, "loop:worker-startup");
6368        assert!(!notices[0].message.contains("private-error-detail"));
6369        assert!(notices[0].message.contains(&request.task));
6370        assert!(
6371            notices[0]
6372                .message
6373                .contains("could not be started or acknowledged")
6374        );
6375        assert!(notices[0].message.contains("worker.log"));
6376        assert_eq!(
6377            notices[0].link,
6378            Some(Link::Task {
6379                id: request.task.clone()
6380            })
6381        );
6382        assert!(format!("{error:#}").contains("private-error-detail"));
6383    }
6384
6385    #[test]
6386    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6387        let home = tempfile::tempdir().unwrap();
6388        let mut request = TaskWorker {
6389            opts: Opts::default(),
6390            queue: home.path().join("queue"),
6391            task: "handoff".into(),
6392            lane: PermitKind::Ordinary,
6393            standalone: true,
6394        };
6395        let job = starting_task_reservation(home.path(), &request);
6396        request.standalone = false;
6397        task_worker_spawn_error(
6398            home.path(),
6399            &request,
6400            anyhow::anyhow!("operation key is already reserved for a different request"),
6401        )
6402        .expect("a different standalone request is the handoff race, not our startup failure");
6403        let active = crate::worker::active(home.path()).unwrap();
6404        assert_eq!(active.len(), 1);
6405        assert_eq!(active[0].id, job.id);
6406        assert_eq!(active[0].payload, job.payload);
6407        assert!(
6408            notices::Notices::at(home.path().join("notifications"))
6409                .list()
6410                .is_empty()
6411        );
6412    }
6413
6414    #[test]
6415    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6416        let home = tempfile::tempdir().unwrap();
6417        let queue = Queue::at(home.path().join("queue"));
6418        let mut task = task();
6419        task.runs = vec!["previous".into()];
6420        queue.put(&mut task).unwrap();
6421        let request = TaskWorker {
6422            opts: Opts::default(),
6423            queue: home.path().join("queue"),
6424            task: task.id.clone(),
6425            lane: PermitKind::Ordinary,
6426            standalone: false,
6427        };
6428        let job = starting_task_reservation(home.path(), &request);
6429        let claims = current_work(home.path(), Timestamp::now());
6430        assert_eq!(claims.len(), 1);
6431        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6432        assert_eq!(claims[0].run, "previous");
6433        assert!(other_claims_run(&claims, "previous", None));
6434        // Only after confirming the executing caller may admission ignore
6435        // this exact projection. Cleanup continues to observe it as live.
6436        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6437        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6438    }
6439
6440    #[test]
6441    fn admission_excludes_only_the_callers_exact_reservation() {
6442        let own = Current {
6443            worker: Some("own".into()),
6444            task: "same-task".into(),
6445            run: "previous".into(),
6446        };
6447        assert!(!other_claims_run(
6448            std::slice::from_ref(&own),
6449            "previous",
6450            Some("own")
6451        ));
6452        assert!(other_claims_run(
6453            std::slice::from_ref(&own),
6454            "previous",
6455            None
6456        ));
6457        for worker in [None, Some("other".into())] {
6458            let other = Current {
6459                worker,
6460                ..own.clone()
6461            };
6462            assert!(other_claims_run(
6463                &[own.clone(), other],
6464                "previous",
6465                Some("own")
6466            ));
6467        }
6468        let legacy: Current =
6469            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6470        assert!(other_claims_run(&[legacy], "previous", Some("own")));
6471    }
6472
6473    #[test]
6474    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6475        let mut task = task();
6476        let mut run = run_state(RunStatus::Reviewing);
6477        run.task_instruction = Some(task.instruction.clone());
6478        run.reviewed_commits = Some(vec!["committed-fix".into()]);
6479        let branch = "magi/test/B";
6480        run.candidates.push(crate::run::Candidate {
6481            branch: branch.into(),
6482            ..candidate('B', "preserved work", false, None)
6483        });
6484        task.runs = vec![run.id.clone()];
6485        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6486        assert_eq!(
6487            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6488            Starter::Resume(run.id.clone())
6489        );
6490        assert!(matches!(
6491            review_retry_starter(
6492                &task,
6493                Some(&run),
6494                Some("different"),
6495                true,
6496                unfinished.as_deref()
6497            ),
6498            Starter::Review(_)
6499        ));
6500        assert_eq!(
6501            review_retry_starter(
6502                &task,
6503                Some(&run),
6504                Some(branch),
6505                false,
6506                unfinished.as_deref()
6507            ),
6508            Starter::Start
6509        );
6510        task.instruction.push_str(" changed criteria");
6511        assert!(matches!(
6512            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6513            Starter::Review(_)
6514        ));
6515        assert!(matches!(
6516            review_retry_starter(&task, Some(&run), Some(branch), true, None),
6517            Starter::Review(_)
6518        ));
6519    }
6520
6521    #[test]
6522    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6523        let dir = tempfile::tempdir().unwrap();
6524        let queue = Queue::at(dir.path().join("queue"));
6525        let mut task = task();
6526        task.status = TaskStatus::Running;
6527        task.attempts = 1;
6528        queue.put(&mut task).unwrap();
6529        let live = std::collections::BTreeSet::from([task.id.clone()]);
6530        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6531        drop(queue.claim(&task.id).unwrap());
6532        let saved = queue.get(&task.id).unwrap();
6533        assert_eq!(saved.status, TaskStatus::Running);
6534        assert_eq!(saved.attempts, 1);
6535        assert!(saved.last_error.is_none());
6536    }
6537
6538    #[test]
6539    fn standalone_workers_do_not_consume_scheduler_lanes() {
6540        let request = |task: &str, lane, standalone| TaskWorker {
6541            opts: Opts::default(),
6542            queue: PathBuf::from("/queue"),
6543            task: task.to_owned(),
6544            lane,
6545            standalone,
6546        };
6547        let mut jobs = vec![
6548            request("ordinary", PermitKind::Ordinary, false),
6549            request("standalone-urgent", PermitKind::Urgent, true),
6550            request("standalone-ordinary", PermitKind::Ordinary, true),
6551            request("decision", PermitKind::None, false),
6552        ];
6553        assert_eq!(available_slots(&jobs, 2), (1, 1));
6554        jobs.push(request("urgent", PermitKind::Urgent, false));
6555        assert_eq!(available_slots(&jobs, 2), (1, 0));
6556        assert_eq!(available_slots(&jobs, 0), (0, 0));
6557    }
6558
6559    #[test]
6560    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6561        let now = Timestamp::now();
6562        let mut reading = Reading {
6563            pid: Some(std::process::id()),
6564            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6565            ..Reading::default()
6566        };
6567        assert!(!reading.running(now));
6568        assert!(legacy_scheduler_running(&reading, now, 0));
6569        reading.worker_protocol = Some(1);
6570        assert!(!legacy_scheduler_running(&reading, now, 0));
6571    }
6572
6573    #[test]
6574    fn selected_public_head_overrides_historical_resume_and_pin() {
6575        let mut t = task();
6576        let mut old = run_state(RunStatus::Blocked);
6577        let selection = crate::pr_recovery::Selection {
6578            url: "url".into(),
6579            branch: format!("magi/task-{}", t.id),
6580            head: "a".repeat(40),
6581            source_head: None,
6582            source_run: None,
6583            source_proof: None,
6584            disposition: Some(crate::pr_recovery::Disposition::Review),
6585            instruction: t.instruction.clone(),
6586            approved_at: Timestamp::now(),
6587        };
6588        t.resume_override = Some(crate::queue::OperatorResume {
6589            pinned_run: Some(old.id.clone()),
6590            question_id: "choice".into(),
6591            at: Timestamp::now(),
6592            conductor_rehold: None,
6593            forced: false,
6594        });
6595        assert_eq!(
6596            selected_starter(&selection, Some(&old), Some(&old.id)),
6597            Starter::Review(selection.branch.clone())
6598        );
6599        old.pr_recovery = Some(selection.clone());
6600        assert_eq!(
6601            selected_starter(&selection, Some(&old), Some(&old.id)),
6602            Starter::Review(selection.branch.clone())
6603        );
6604        old.reviewed_commits = Some(vec!["implementation".into()]);
6605        assert_eq!(
6606            selected_starter(&selection, Some(&old), Some(&old.id)),
6607            Starter::Resume(old.id.clone())
6608        );
6609        let mut changed = selection.clone();
6610        changed.head = "b".repeat(40);
6611        assert_eq!(
6612            selected_starter(&changed, Some(&old), Some(&old.id)),
6613            Starter::Review(changed.branch)
6614        );
6615    }
6616
6617    #[test]
6618    fn candidate_transplant_failure_is_one_actionable_hold() {
6619        let dir = tempfile::tempdir().unwrap();
6620        let q = Queue::at(dir.path().join("queue"));
6621        let mut t = task();
6622        let mut state = run_state(RunStatus::Blocked);
6623        state.event("prep", "cannot apply referenced commit: conflict");
6624        state.prep_failure = Some("conflict".into());
6625        t.start(state.id.clone());
6626        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6627        assert_eq!(t.attempts, 1);
6628        assert_eq!(t.status, TaskStatus::Held);
6629        assert!(t.operator_held());
6630        assert!(!t.status.runnable());
6631        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6632        let first = t.chat_notice_key().unwrap();
6633        t.chat_notices.push(first.clone());
6634        t.release_operator("test", None);
6635        state.id = "another-unprepared-run".into();
6636        t.start(state.id.clone());
6637        finish_attempt(
6638            3,
6639            &q,
6640            &mut t,
6641            &state,
6642            &[],
6643            Err(anyhow::anyhow!("still conflicts")),
6644        );
6645        assert_eq!(
6646            t.chat_notice_key().as_ref(),
6647            Some(&first),
6648            "no work happened"
6649        );
6650        t.release_operator("test", None);
6651        state.prep_failure = None;
6652        state.status = RunStatus::Failed;
6653        state.begin_pass();
6654        t.start(state.id.clone());
6655        finish_attempt(
6656            1,
6657            &q,
6658            &mut t,
6659            &state,
6660            &[],
6661            Err(anyhow::anyhow!("new gate failure")),
6662        );
6663        let failure = t.chat_notice_key().unwrap();
6664        assert_ne!(failure, first, "approved recovery reached a real failure");
6665        t.release_operator("test", None);
6666        state.begin_pass();
6667        t.start(state.id.clone());
6668        finish_attempt(
6669            1,
6670            &q,
6671            &mut t,
6672            &state,
6673            &[],
6674            Err(anyhow::anyhow!("new failure on resume")),
6675        );
6676        assert_ne!(
6677            t.chat_notice_key().as_ref(),
6678            Some(&failure),
6679            "a new settled pass"
6680        );
6681    }
6682
6683    #[test]
6684    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6685        for source in ["cli", "web"] {
6686            let mut t = task();
6687            let mut run = run_state(RunStatus::Blocked);
6688            run.instruction = "Run A original criteria".into();
6689            run.task_instruction = Some(run.instruction.clone());
6690            t.start(run.id.clone());
6691            t.release_operator("choice", Some("resume-question"));
6692            t.resume_override = Some(crate::queue::OperatorResume {
6693                question_id: "resume-question".into(),
6694                at: Timestamp::now(),
6695                conductor_rehold: None,
6696                forced: true,
6697                pinned_run: Some(run.id.clone()),
6698            });
6699            t.hold_machine(Some("not enough free space to start a run".into()));
6700            let mut unchanged = t.clone();
6701            unchanged
6702                .edit("title changed".into(), unchanged.instruction.clone())
6703                .unwrap();
6704            unchanged.release_operator(source, None);
6705            assert_eq!(
6706                unchanged
6707                    .resume_override
6708                    .as_ref()
6709                    .unwrap()
6710                    .pinned_run
6711                    .as_deref(),
6712                Some(run.id.as_str())
6713            );
6714            assert!(!compatible_run_instruction(&run, &unchanged));
6715            assert!(may_resume_run(&run, &unchanged));
6716
6717            t.edit(
6718                "approved recovery".into(),
6719                "Reuse measured PR head B; fix Clippy; review".into(),
6720            )
6721            .unwrap();
6722            assert!(t.resume_override.is_none());
6723            t.release_operator(source, None);
6724            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6725            assert!(reloaded.resume_override.is_none());
6726            assert!(!may_resume_run(&run, &reloaded));
6727            let unfinished =
6728                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6729                    .filter(|_| may_resume_run(&run, &reloaded));
6730            assert_eq!(
6731                choose_starter(None, false, unfinished.as_deref()),
6732                Starter::Start
6733            );
6734            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
6735            assert_eq!(
6736                reloaded.resumption_history[0].question_id.as_deref(),
6737                Some("resume-question")
6738            );
6739
6740            // A revision already persisted with the old approval/pin is also
6741            // invalidated when the new operator release is recorded.
6742            unchanged.instruction = "Reuse measured PR head B".into();
6743            unchanged.hold_machine(Some("disk hold".into()));
6744            unchanged.release_operator(source, None);
6745            assert!(unchanged.resume_override.is_none());
6746            assert!(!may_resume_run(&run, &unchanged));
6747        }
6748    }
6749
6750    #[test]
6751    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
6752        let mut t = task();
6753        let mut run = run_state(RunStatus::Blocked);
6754        t.review_of = Some("approved-head".into());
6755        t.instruction =
6756            "Review the branch `approved-head` (review-only: no implementation, no judging)."
6757                .into();
6758        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();
6759        run.reviewed_commits = Some(vec!["Commit log".into()]);
6760        t.start(run.id.clone());
6761        t.hold_machine(Some("interrupted review".into()));
6762        t.release_operator("cli", None);
6763        assert!(
6764            compatible_run_instruction(&run, &t),
6765            "legacy explicit review remains resumable"
6766        );
6767        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
6768            .filter(|_| compatible_run_instruction(&run, &t));
6769        assert_eq!(
6770            choose_starter(None, false, unfinished.as_deref()),
6771            Starter::Resume(run.id.clone())
6772        );
6773        run.task_instruction = Some(t.instruction.clone());
6774        assert!(compatible_run_instruction(&run, &t));
6775        let reloaded: RunState =
6776            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
6777        assert!(compatible_run_instruction(&reloaded, &t));
6778        t.edit(
6779            "new approved head".into(),
6780            "Reuse measured PR head B".into(),
6781        )
6782        .unwrap();
6783        assert!(!compatible_run_instruction(&run, &t));
6784
6785        // Legacy recovery reviews retain the task criteria ahead of the log.
6786        t.review_of = None;
6787        t.instruction = "Fix Clippy on approved head".into();
6788        run.task_instruction = None;
6789        run.instruction = format!(
6790            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
6791            t.instruction
6792        );
6793        assert!(compatible_run_instruction(&run, &t));
6794        t.instruction.push('\n');
6795        assert!(
6796            compatible_run_instruction(&run, &t),
6797            "legacy generated review trimmed the original criteria"
6798        );
6799        t.hold_for_handover(Some("approved-head".into()), "refused".into());
6800        let mut unchanged = t.clone();
6801        assert_eq!(
6802            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
6803            Some("approved-head")
6804        );
6805        t.edit("new plan".into(), "Reuse measured PR head B".into())
6806            .unwrap();
6807        assert!(take_review_branch(&mut t, Some(&run)).is_none());
6808        assert!(!compatible_run_instruction(&run, &t));
6809        t.review_branch = Some("approved-head".into());
6810        t.review_instruction = None;
6811        assert!(
6812            take_review_branch(&mut t, Some(&run)).is_none(),
6813            "legacy retained candidate cannot replace a revised approved head"
6814        );
6815    }
6816
6817    #[test]
6818    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
6819        let home = crate::run::test_home();
6820        crate::run::pin_test_home();
6821        let dir = tempfile::tempdir().unwrap();
6822        let queue = Queue::at(dir.path().join("queue"));
6823        for resume in [true, false] {
6824            let state = run_state(RunStatus::Blocked);
6825            let mut t = task();
6826            t.start(state.id.clone());
6827            let action = if resume {
6828                ask::ChoiceAction::Resume {
6829                    run: state.id.clone(),
6830                }
6831            } else {
6832                ask::ChoiceAction::Requeue
6833            };
6834            let mut q = action_question(&state.id, action);
6835            q.status = ask::QuestionStatus::Open;
6836            q.answer = None;
6837            q.answered_at = None;
6838            t.fail("run stopped with a question", 3);
6839            hold_if_runnable(&queue, &mut t);
6840            assert!(t.operator_decided_at.is_none());
6841            assert!(t.operator_held());
6842            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
6843            let expected = if resume {
6844                ActionDecision::Resume(state.id.clone())
6845            } else {
6846                ActionDecision::Requeue
6847            };
6848            assert_eq!(
6849                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
6850                expected
6851            );
6852            t.hold_manual(Some("later explicit hold".into()));
6853            assert_eq!(
6854                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
6855                ActionDecision::Stale
6856            );
6857        }
6858    }
6859
6860    #[test]
6861    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
6862        let mut t = task();
6863        t.answers.push(crate::queue::AnsweredQuestion {
6864            question: "Inspect the remote?".into(),
6865            answer: "Inspect then wait".into(),
6866        });
6867        let old = instruction_for(&t);
6868        assert!(compatible_instruction(&old, &t));
6869        t.instruction = "Reuse approved PR head and review".into();
6870        t.release_operator("cli", None);
6871        assert!(!compatible_instruction(&old, &t));
6872        let approved = instruction_for(&t);
6873        assert!(approved.contains("waiting premises are superseded"));
6874        assert!(compatible_instruction(&approved, &t));
6875        assert_eq!(resumed_instruction(&approved, &t), approved);
6876        t.release_operator("web", None);
6877        assert!(compatible_instruction(&approved, &t));
6878        assert_eq!(t.resumption_history.len(), 1);
6879        t.start("run".into());
6880        assert!(instruction_for(&t).contains("Explicit operator resumption"));
6881    }
6882
6883    /// A run that stopped on an infrastructure wait asked no agent anything:
6884    /// the task is held by the machine under a `[resource]` reason (resumable,
6885    /// re-checked by triage), and the attempt it started is given back.
6886    #[test]
6887    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
6888        let mut state = RunState::new(
6889            PathBuf::from("/repo"),
6890            "main".into(),
6891            "base".into(),
6892            "task".into(),
6893            Config::default(),
6894        );
6895        state.status = RunStatus::Landing;
6896        state.parked = true;
6897        state.pr_pushed_head = Some("head".into());
6898        state.land_unrelated = Some(
6899            serde_json::from_value(serde_json::json!({
6900                "head": "head", "question": "ci-question",
6901                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
6902            }))
6903            .unwrap(),
6904        );
6905        let mut t = task();
6906        t.start(state.id.clone());
6907        let verdict = Verdict {
6908            status: RunStatus::Landing,
6909            left_pr: true,
6910            quota_hit: false,
6911            parked: true,
6912            no_viable_candidates: false,
6913        };
6914        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6915        assert_eq!(t.attempts, 0);
6916        assert_eq!(t.status, TaskStatus::Held);
6917        assert!(!t.operator_held());
6918        assert!(
6919            t.hold_reason
6920                .as_deref()
6921                .unwrap()
6922                .starts_with("[ci-unrelated]")
6923        );
6924        // A second settlement must not refund an earlier task attempt.
6925        t.attempts = 1;
6926        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6927        assert_eq!(t.attempts, 1);
6928        assert_eq!(t.passes.len(), 1);
6929        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6930        state.pr_pushed_head = Some("new-head".into());
6931        state.parked = false;
6932        state.status = RunStatus::Blocked;
6933        let stale = Verdict {
6934            status: RunStatus::Blocked,
6935            parked: false,
6936            ..verdict
6937        };
6938        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
6939        assert_eq!(t.attempts, 1);
6940        // A new execution pass can refund its own newly charged attempt.
6941        state.begin_pass();
6942        state.begin_pass();
6943        state.status = RunStatus::Landing;
6944        state.parked = true;
6945        state.pr_pushed_head = Some("head".into());
6946        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
6947        assert_eq!(t.attempts, 0);
6948        assert_eq!(t.passes.len(), 2);
6949    }
6950
6951    #[test]
6952    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
6953        let mut state = run_state(RunStatus::Failed);
6954        state
6955            .quota
6956            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
6957        state.begin_pass();
6958        let mut t = task();
6959        t.start(state.id.clone());
6960        reclaim(&mut t, Some(state), 2, "en");
6961        assert_eq!(t.attempts, 1);
6962    }
6963
6964    #[test]
6965    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
6966        let mut state = run_state(RunStatus::Blocked);
6967        let losses: Vec<_> = ["alpha", "beta"]
6968            .into_iter()
6969            .enumerate()
6970            .map(|(i, agent)| {
6971                QuotaLoss::from_report(
6972                    format!("advisor-{i}"),
6973                    "advise",
6974                    Some(&crate::agent::Quota {
6975                        cause: crate::agent::QuotaCause::Authentication,
6976                        agent: agent.to_owned(),
6977                        reset: None,
6978                    }),
6979                )
6980            })
6981            .collect();
6982        crate::graph::block_machine_outage(&mut state, "advise", &losses);
6983        state.quota = losses;
6984        let mut t = task();
6985        t.start(state.id.clone());
6986        let verdict = Verdict {
6987            status: state.status,
6988            left_pr: false,
6989            quota_hit: true,
6990            parked: false,
6991            no_viable_candidates: true,
6992        };
6993        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
6994        assert_eq!(t.attempts, 0);
6995        assert_eq!(t.status, TaskStatus::Held);
6996        assert!(!t.operator_held());
6997        let reason = t.hold_reason.as_deref().unwrap();
6998        assert!(reason.starts_with("[authentication]"));
6999        assert!(
7000            reason.contains("alpha")
7001                && reason.contains("beta")
7002                && reason.contains("re-authenticate")
7003        );
7004        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7005        // Orphan recovery uses the same settlement and cannot spend an attempt.
7006        let mut orphan = task();
7007        orphan.start(state.id.clone());
7008        reclaim(&mut orphan, Some(state), 2, "en");
7009        assert_eq!(orphan.attempts, 0);
7010        assert_eq!(orphan.status, TaskStatus::Held);
7011    }
7012
7013    #[test]
7014    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7015        let mut state = RunState::new(
7016            PathBuf::from("/repo"),
7017            "main".to_owned(),
7018            "abc1234".to_owned(),
7019            "task".to_owned(),
7020            Config::default(),
7021        );
7022        state.status = RunStatus::Blocked;
7023        state.resource_block = Some(crate::run::ResourceBlock {
7024            cause: crate::run::ResourceBlockCause::Other,
7025            node: "graft".to_owned(),
7026            kind: "shared build cache".to_owned(),
7027            detail: "timed out".to_owned(),
7028            at: jiff::Timestamp::now(),
7029        });
7030        let mut t = task();
7031        t.start("20260902-000000-aaaa".to_owned());
7032        assert_eq!(t.attempts, 1);
7033        let verdict = Verdict {
7034            status: RunStatus::Blocked,
7035            left_pr: false,
7036            quota_hit: false,
7037            parked: false,
7038            no_viable_candidates: false,
7039        };
7040        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7041        assert_eq!(t.status, TaskStatus::Held);
7042        assert_eq!(t.attempts, 0, "the attempt is refunded");
7043        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7044        assert!(
7045            !t.operator_held(),
7046            "a machine hold, released without a human"
7047        );
7048
7049        let mut selected = task();
7050        selected.start("20260902-000000-cccc".into());
7051        selected.replacement = Some(crate::merge_decision::Replacement {
7052            question: "fixture".into(),
7053            run: "earlier".into(),
7054            pr: "https://example.invalid/pr/1".into(),
7055            agent: "selected".into(),
7056            context: "fixture".into(),
7057        });
7058        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7059        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7060        assert_eq!(selected.attempts, 0);
7061        assert!(
7062            !selected.operator_held(),
7063            "a selected agent also retains a machine resource hold"
7064        );
7065        assert!(
7066            selected
7067                .hold_reason
7068                .as_deref()
7069                .unwrap()
7070                .starts_with("[resource] ")
7071        );
7072
7073        // A park request outranks it: still the operator's doing.
7074        let mut p = task();
7075        p.start("20260902-000000-bbbb".to_owned());
7076        settle_and_diagnose(
7077            &mut p,
7078            Verdict {
7079                parked: true,
7080                ..verdict
7081            },
7082            "parked",
7083            2,
7084            &state,
7085        );
7086        assert_eq!(p.status, TaskStatus::Parked);
7087        assert_eq!(
7088            p.attempts, 0,
7089            "parking refunds once rather than also settling the resource hold"
7090        );
7091    }
7092
7093    #[test]
7094    fn record_failure_notice_links_the_task() {
7095        let dir = tempfile::tempdir().unwrap();
7096        // A regular file where the queue directory should be makes every
7097        // `put` fail, on every platform and whoever runs the test.
7098        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7099        let queue = Queue::at(dir.path().join("queue"));
7100        let mut t = interrupt_task("rec-fail-1");
7101        record(&queue, &mut t);
7102
7103        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7104        assert_eq!(found.len(), 1);
7105        assert_eq!(found[0].key, "loop:record");
7106        assert_eq!(
7107            found[0].link,
7108            Some(Link::Task {
7109                id: "rec-fail-1".to_owned()
7110            })
7111        );
7112    }
7113
7114    /// A runnable task marked to interrupt, with an id fixed for assertions
7115    /// rather than the random one [`Task::new`] mints.
7116    fn interrupt_task(id: &str) -> Task {
7117        let mut t = task();
7118        t.id = id.to_owned();
7119        t.interrupt = true;
7120        t
7121    }
7122
7123    /// An ordinary runnable task with an id fixed for assertions.
7124    fn task_with_id(id: &str) -> Task {
7125        let mut t = task();
7126        t.id = id.to_owned();
7127        t
7128    }
7129
7130    /// A runnable task marked `--urgent`, with an id fixed for assertions.
7131    fn urgent_task(id: &str) -> Task {
7132        let mut t = task();
7133        t.id = id.to_owned();
7134        t.urgent = true;
7135        t
7136    }
7137
7138    #[test]
7139    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7140        let dir = tempfile::tempdir().unwrap();
7141        let queue = Queue::at(dir.path().join("queue"));
7142        let mut parked = task_with_id("parked");
7143        parked.start("run".into());
7144        parked.park("upgrade");
7145        parked.record_pass_at(
7146            "run",
7147            0,
7148            Some(Timestamp::now()),
7149            1,
7150            Some(crate::run::ParkCause::Upgrade {
7151                from: "old".into(),
7152                to: None,
7153            }),
7154        );
7155        let mut fresh = task_with_id("fresh");
7156        fresh.priority = 100;
7157        let mut urgent_task = urgent_task("urgent");
7158        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7159            queue.put(t).unwrap();
7160        }
7161        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7162        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7163        let candidates = runnable(&queue);
7164        assert_eq!(candidates[0].id, parked.id);
7165        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7166        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7167        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7168        drop(first);
7169        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7170        let next = runnable(&queue)
7171            .into_iter()
7172            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7173            .unwrap();
7174        assert_eq!(next.task.id, fresh.id);
7175        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7176        drop(claimed_elsewhere);
7177        drop(next);
7178        assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7179    }
7180
7181    #[test]
7182    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7183        let dir = tempfile::tempdir().unwrap();
7184        let queue = Queue::at(dir.path().join("queue"));
7185        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7186        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7187        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7188        let mut first = task();
7189        queue.put(&mut first).unwrap();
7190        let stale_plain = queue.get(&first.id).unwrap();
7191        first.set_urgent(true).unwrap();
7192        queue.put(&mut first).unwrap();
7193        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7194        let mut second = urgent_task("second");
7195        queue.put(&mut second).unwrap();
7196        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7197        drop(queue.claim(&second.id).unwrap());
7198        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7199        drop(dispatched);
7200        let stale_urgent = queue.get(&first.id).unwrap();
7201        first.set_urgent(false).unwrap();
7202        queue.put(&mut first).unwrap();
7203        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7204        assert_eq!(urgent.available_permits(), 1);
7205        drop(queue.claim(&first.id).unwrap());
7206        drop(occupied);
7207    }
7208
7209    #[test]
7210    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7211        let dir = tempfile::tempdir().unwrap();
7212        let queue = Queue::at(dir.path().join("queue"));
7213        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7214        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7215        let mut t = task();
7216        queue.put(&mut t).unwrap();
7217        for enabled in [true, false] {
7218            let stale = queue.get(&t.id).unwrap();
7219            t.set_urgent(enabled).unwrap();
7220            queue.put(&mut t).unwrap();
7221            assert_ne!(stale.urgent, enabled);
7222            let DispatchClaim {
7223                task: fresh,
7224                claim,
7225                permit,
7226            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7227            assert_eq!(fresh.urgent, enabled);
7228            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7229            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7230            assert!(queue.claim(&t.id).is_err());
7231            assert_eq!(fresh.attempts, stale.attempts);
7232            drop((claim, permit));
7233            assert_eq!(ordinary.available_permits(), 1);
7234            assert_eq!(urgent.available_permits(), 1);
7235        }
7236        t.set_urgent(true).unwrap();
7237        queue.put(&mut t).unwrap();
7238        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7239        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7240        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7241        drop(queue.claim(&t.id).unwrap());
7242        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7243        drop(occupied);
7244        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7245        drop(queue.claim(&t.id).unwrap());
7246        let held = queue.claim(&t.id).unwrap();
7247        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7248        drop(held);
7249        t.status = TaskStatus::Held;
7250        queue.put(&mut t).unwrap();
7251        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7252        drop(queue.claim(&t.id).unwrap());
7253        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7254        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7255        drop(queue.claim(&t.id).unwrap());
7256        assert_eq!(urgent.available_permits(), 1);
7257    }
7258
7259    /// The land-resume exemption wins outright, whether or not the candidate
7260    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7261    /// queue behind anything" guarantee cannot be weaker just because the
7262    /// same task was also filed with `--urgent`.
7263    #[test]
7264    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7265        assert_eq!(permit_kind(true, false), PermitKind::None);
7266        assert_eq!(permit_kind(true, true), PermitKind::None);
7267    }
7268
7269    /// The one property this whole feature exists for: `--urgent` draws from
7270    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7271    /// ordinary candidate draws from the ordinary pool exactly as before,
7272    /// untouched by the urgent slot's existence.
7273    #[test]
7274    fn permit_kind_separates_urgent_from_ordinary() {
7275        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7276        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7277    }
7278
7279    /// The exact wiring `attempt` runs before minting anything: a config's
7280    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7281    /// Free space is injected rather than asked of the real disk - the point
7282    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7283    /// is deterministic on every machine this test runs on, never dependent
7284    /// on how full the CI runner's own disk happens to be.
7285    #[test]
7286    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7287        let cfg = Config::default();
7288        let repo = Path::new("/any/repo/path");
7289
7290        let reason =
7291            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7292        assert!(reason.contains("1024"), "{reason}");
7293        assert!(
7294            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7295            "{reason}"
7296        );
7297
7298        assert_eq!(
7299            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7300            None,
7301            "exactly at the floor is open"
7302        );
7303        assert_eq!(
7304            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7305            None,
7306            "comfortably above the floor is open"
7307        );
7308    }
7309
7310    #[test]
7311    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7312        let mut cfg = Config::default();
7313        cfg.disk.min_free_bytes = 0;
7314        let repo = Path::new("/any/repo/path");
7315        assert_eq!(
7316            disk_gate_with(repo, &cfg, |_| Ok(0)),
7317            None,
7318            "a zero floor never measures at all"
7319        );
7320    }
7321
7322    #[test]
7323    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7324        let cfg = Config::default();
7325        let repo = Path::new("/any/repo/path");
7326        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7327            .expect("a measurement failure must close the gate, not open it");
7328        assert!(reason.contains("could not measure"), "{reason}");
7329    }
7330
7331    #[test]
7332    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7333        let ordinary = task();
7334        let next = advance_interrupt(
7335            Interrupt::Idle,
7336            std::slice::from_ref(&ordinary.id),
7337            std::slice::from_ref(&ordinary),
7338        );
7339        assert_eq!(next, Interrupt::Idle);
7340    }
7341
7342    #[test]
7343    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7344        // Nothing to interrupt - this is just an ordinary candidate, and the
7345        // loop's normal dispatch will pick it up like any other.
7346        let marked = interrupt_task("marked");
7347        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7348        assert_eq!(next, Interrupt::Idle);
7349    }
7350
7351    #[test]
7352    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7353        let marked = interrupt_task("marked");
7354        let next = advance_interrupt(
7355            Interrupt::Idle,
7356            &["running".to_owned()],
7357            std::slice::from_ref(&marked),
7358        );
7359        assert_eq!(
7360            next,
7361            Interrupt::Parking {
7362                parked: vec!["running".to_owned()],
7363                interrupt_task: "marked".to_owned(),
7364            }
7365        );
7366    }
7367
7368    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
7369    /// one run can be in flight when a task becomes runnable and marked.
7370    /// Parking all of them would mean `Resuming` later has more than one id
7371    /// to release back to ordinary dispatch, which cannot be made safe
7372    /// against that same setting's own extra concurrency slots letting two
7373    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
7374    /// The simplification the task's own constraints ask for: do not begin
7375    /// a sequence at all until the herd settles back to exactly one.
7376    #[test]
7377    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7378        let marked = interrupt_task("marked");
7379
7380        let two = advance_interrupt(
7381            Interrupt::Idle,
7382            &["a".to_owned(), "b".to_owned()],
7383            std::slice::from_ref(&marked),
7384        );
7385        assert_eq!(two, Interrupt::Idle);
7386
7387        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7388        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7389    }
7390
7391    #[test]
7392    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7393        let state = Interrupt::Parking {
7394            parked: vec!["running".to_owned()],
7395            interrupt_task: "marked".to_owned(),
7396        };
7397        // Still in flight: no change.
7398        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7399        assert_eq!(still_going, state);
7400
7401        // Left flight, but the interrupt task has not been dispatched yet on
7402        // this tick - stays `Parking` so `interrupt_gate` can let it through,
7403        // as long as it is still runnable.
7404        let stopped_but_not_yet_dispatched =
7405            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7406        assert_eq!(stopped_but_not_yet_dispatched, state);
7407
7408        // Left flight, and the interrupt task is now in flight itself.
7409        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7410        assert_eq!(
7411            dispatched,
7412            Interrupt::Running {
7413                parked: vec!["running".to_owned()],
7414                interrupt_task: "marked".to_owned(),
7415            }
7416        );
7417    }
7418
7419    #[test]
7420    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7421        let state = Interrupt::Running {
7422            parked: vec!["running".to_owned()],
7423            interrupt_task: "marked".to_owned(),
7424        };
7425        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7426        assert_eq!(still_running, state);
7427
7428        // Whatever it ended as - merged, failed, held - is not this
7429        // function's concern: leaving flight is the only trigger, driven
7430        // straight off the same in-flight list `poll` already reaps. It does
7431        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
7432        // why that would let an unrelated task start ahead of, or alongside,
7433        // the guaranteed resume.
7434        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7435        assert_eq!(
7436            ended,
7437            Interrupt::Resuming {
7438                parked: vec!["running".to_owned()]
7439            }
7440        );
7441    }
7442
7443    #[test]
7444    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7445        let state = Interrupt::Resuming {
7446            parked: vec!["running".to_owned()],
7447        };
7448        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7449        assert_eq!(still_waiting, state);
7450
7451        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7452        assert_eq!(dispatched, Interrupt::Idle);
7453    }
7454
7455    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
7456    /// or otherwise moved on by an operator with no claim standing in the
7457    /// way - must not wedge the sequence (and so the whole loop's dispatch,
7458    /// via `interrupt_gate`) waiting forever for a dispatch that can never
7459    /// come. The parked run still gets its resume.
7460    #[test]
7461    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7462    {
7463        let state = Interrupt::Parking {
7464            parked: vec!["running".to_owned()],
7465            interrupt_task: "marked".to_owned(),
7466        };
7467        // `marked` has been held/blocked/deleted since the sequence began:
7468        // it no longer appears in `runnable` at all.
7469        let next = advance_interrupt(state, &[], &[]);
7470        assert_eq!(
7471            next,
7472            Interrupt::Resuming {
7473                parked: vec!["running".to_owned()]
7474            },
7475            "abandoning the interrupt must not abandon the resume it owes"
7476        );
7477    }
7478
7479    /// The same abandonment, one step later: `Resuming` itself must not wait
7480    /// forever for a parked task that has since become unrunnable.
7481    #[test]
7482    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7483        let state = Interrupt::Resuming {
7484            parked: vec!["running".to_owned()],
7485        };
7486        let next = advance_interrupt(state, &[], &[]);
7487        assert_eq!(
7488            next,
7489            Interrupt::Idle,
7490            "nothing is left to wait for; the loop must not stay wedged"
7491        );
7492    }
7493
7494    #[test]
7495    fn disabled_by_config_the_sequence_can_never_leave_idle() {
7496        let marked = interrupt_task("marked");
7497        let next = advance_interrupt_tick(
7498            false,
7499            Interrupt::Idle,
7500            &["running".to_owned()],
7501            std::slice::from_ref(&marked),
7502        );
7503        assert_eq!(
7504            next,
7505            Interrupt::Idle,
7506            "an unmarked, unconfigured daemon must behave exactly as before"
7507        );
7508    }
7509
7510    #[test]
7511    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7512        let state = Interrupt::Parking {
7513            parked: vec!["running".to_owned()],
7514            interrupt_task: "marked".to_owned(),
7515        };
7516        let candidates = vec![interrupt_task("marked"), task()];
7517        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7518        assert!(
7519            allowed.is_empty(),
7520            "nothing may dispatch - not even the interrupt task itself - \
7521             until the parked run has actually stopped"
7522        );
7523    }
7524
7525    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
7526    /// grow a special case for it: an urgent candidate that is not the
7527    /// interrupt task withholds exactly like an ordinary one for as long as
7528    /// the parked run it is racing has not actually left flight. A version
7529    /// of this feature once bypassed the gate for urgent candidates, on the
7530    /// theory that a genuinely separate concurrency lane could not collide
7531    /// with 75dd's own; it could, and did - the bypassed task dispatched
7532    /// alongside a run 75dd's own state machine had only *asked* to park,
7533    /// not yet confirmed gone, which is exactly the second run
7534    /// `Interrupt::Parking`'s own doc says must never happen. There is no
7535    /// tick during Parking/Running/Resuming where letting an extra
7536    /// candidate through is safe, urgent or not - the parked run may still
7537    /// be genuinely mid-call.
7538    #[test]
7539    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7540        for state in [
7541            Interrupt::Parking {
7542                parked: vec!["running".to_owned()],
7543                interrupt_task: "marked".to_owned(),
7544            },
7545            Interrupt::Running {
7546                parked: vec!["running".to_owned()],
7547                interrupt_task: "marked".to_owned(),
7548            },
7549            Interrupt::Resuming {
7550                parked: vec!["running".to_owned()],
7551            },
7552        ] {
7553            let candidates = vec![
7554                interrupt_task("marked"),
7555                urgent_task("hot"),
7556                task_with_id("ordinary"),
7557            ];
7558            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7559            assert!(
7560                !allowed.iter().any(|t| t.id == "hot"),
7561                "an urgent candidate must wait out the same gate as anything \
7562                 else while the run it would run alongside has not actually \
7563                 left flight, for state {state:?}: {allowed:?}"
7564            );
7565        }
7566    }
7567
7568    /// The one case where marking a task `--urgent` and `interrupt` at once
7569    /// is not redundant: once the interrupt sequence's own guaranteed
7570    /// resume/dispatch actually admits the task, it is unaffected by also
7571    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
7572    /// never on the urgent flag.
7573    #[test]
7574    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7575        let state = Interrupt::Resuming {
7576            parked: vec!["hot".to_owned()],
7577        };
7578        let candidates = vec![urgent_task("hot"), task()];
7579        let allowed = interrupt_gate(&state, &[], candidates);
7580        assert_eq!(
7581            allowed.iter().filter(|t| t.id == "hot").count(),
7582            1,
7583            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7584        );
7585    }
7586
7587    #[test]
7588    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7589        let state = Interrupt::Parking {
7590            parked: vec!["running".to_owned()],
7591            interrupt_task: "marked".to_owned(),
7592        };
7593        let other = task();
7594        let candidates = vec![interrupt_task("marked"), other.clone()];
7595        let allowed = interrupt_gate(&state, &[], candidates);
7596        assert_eq!(allowed.len(), 1);
7597        assert_eq!(allowed[0].id, "marked");
7598    }
7599
7600    #[test]
7601    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7602        let state = Interrupt::Running {
7603            parked: vec!["running".to_owned()],
7604            interrupt_task: "marked".to_owned(),
7605        };
7606        let candidates = vec![task(), task()];
7607        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7608        assert!(allowed.is_empty());
7609    }
7610
7611    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
7612    /// sequence began (only reachable above the default
7613    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
7614    /// never both in the same tick, which is what "exactly one resume, no
7615    /// simultaneous run" actually requires structurally rather than by
7616    /// coincidence of how many ordinary slots happen to be free.
7617    #[test]
7618    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7619        let state = Interrupt::Resuming {
7620            parked: vec!["a".to_owned(), "c".to_owned()],
7621        };
7622        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7623        let allowed = interrupt_gate(&state, &[], candidates);
7624        assert_eq!(
7625            allowed.len(),
7626            1,
7627            "at most one candidate may be offered while resuming: {allowed:?}"
7628        );
7629        assert_eq!(allowed[0].id, "a");
7630    }
7631
7632    #[test]
7633    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7634        let state = Interrupt::Resuming {
7635            parked: vec!["a".to_owned()],
7636        };
7637        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7638        assert!(allowed.is_empty());
7639    }
7640
7641    /// The invariant the completion criteria ask for by name: across a whole
7642    /// simulated sequence, there is never a tick where the gate would let
7643    /// through both the parked run's resume and the interrupt task, and
7644    /// exactly one candidate resumes the instant the interrupt task's run
7645    /// ends - never zero, never more than one.
7646    #[test]
7647    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7648        let running = task(); // id: whatever `Task::new` minted
7649        let marked = interrupt_task("marked");
7650
7651        let mut state = Interrupt::Idle;
7652        // Tick 1: `running` is in flight, `marked` becomes runnable.
7653        let in_flight = vec![running.id.clone()];
7654        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7655        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7656        assert!(gated.is_empty(), "still waiting on `running` to park");
7657
7658        // Tick 2: `running` parked and left flight; nothing dispatched yet.
7659        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7660        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7661        assert_eq!(
7662            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7663            vec!["marked"],
7664            "only the interrupt task may be offered to the dispatcher now"
7665        );
7666
7667        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
7668        state = advance_interrupt_tick(
7669            true,
7670            state,
7671            &["marked".to_owned()],
7672            std::slice::from_ref(&running),
7673        );
7674        let gated = interrupt_gate(
7675            &state,
7676            &["marked".to_owned()],
7677            vec![marked.clone(), running.clone()],
7678        );
7679        assert!(
7680            gated.is_empty(),
7681            "the parked run must not be offered back while the interrupt \
7682             task is still running"
7683        );
7684
7685        // Tick 4: `marked`'s run reached a terminal status and left flight.
7686        // A higher-priority ordinary task `other` is also runnable now - it
7687        // must not be let through instead of, or alongside, `running`.
7688        let other = task_with_id("other");
7689        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7690        assert_eq!(
7691            state,
7692            Interrupt::Resuming {
7693                parked: vec![running.id.clone()]
7694            }
7695        );
7696        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7697        assert_eq!(
7698            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7699            vec![running.id.as_str()],
7700            "exactly the parked run resumes - not the unrelated task, even \
7701             though it was offered first"
7702        );
7703
7704        // Tick 5: `running` is now in flight (dispatched from tick 4's
7705        // gate). Only now does the sequence end and ordinary dispatch fully
7706        // resume.
7707        state = advance_interrupt_tick(
7708            true,
7709            state,
7710            std::slice::from_ref(&running.id),
7711            std::slice::from_ref(&other),
7712        );
7713        assert_eq!(state, Interrupt::Idle);
7714        let gated = interrupt_gate(
7715            &state,
7716            std::slice::from_ref(&running.id),
7717            vec![other.clone()],
7718        );
7719        assert_eq!(
7720            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7721            vec![other.id.as_str()],
7722            "ordinary dispatch is unrestricted again"
7723        );
7724    }
7725
7726    #[test]
7727    fn every_run_status_settles_the_task_it_came_from() {
7728        // run status, resulting task status, attempts still standing after one
7729        let table = [
7730            (RunStatus::Merged, TaskStatus::Done, 1),
7731            (RunStatus::Ready, TaskStatus::Done, 1),
7732            (RunStatus::Stalled, TaskStatus::Failed, 0),
7733            (RunStatus::Blocked, TaskStatus::Failed, 1),
7734            (RunStatus::Failed, TaskStatus::Failed, 1),
7735            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
7736            (RunStatus::Prep, TaskStatus::Failed, 1),
7737            (RunStatus::Implementing, TaskStatus::Failed, 1),
7738            (RunStatus::Judging, TaskStatus::Failed, 1),
7739            (RunStatus::Deliberating, TaskStatus::Failed, 1),
7740            (RunStatus::Voting, TaskStatus::Failed, 1),
7741            (RunStatus::Reviewing, TaskStatus::Failed, 1),
7742            (RunStatus::Gating, TaskStatus::Failed, 1),
7743        ];
7744        for (run, want, attempts) in table {
7745            let mut t = task();
7746            t.start("20260902-000000-aaaa".to_owned());
7747            settle(
7748                &mut t,
7749                Verdict {
7750                    status: run,
7751                    left_pr: false,
7752                    parked: false,
7753                    quota_hit: matches!(run, RunStatus::Stalled),
7754                    no_viable_candidates: false,
7755                },
7756                "why",
7757                2,
7758            );
7759            assert_eq!(t.status, want, "task status after {}", label(run));
7760            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
7761        }
7762    }
7763
7764    #[test]
7765    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
7766        let mut stalled = task();
7767        stalled.start("20260902-000000-aaaa".to_owned());
7768        settle(
7769            &mut stalled,
7770            Verdict {
7771                status: RunStatus::Stalled,
7772                left_pr: false,
7773                parked: false,
7774                quota_hit: true,
7775                no_viable_candidates: false,
7776            },
7777            "quota",
7778            1,
7779        );
7780        assert_eq!(stalled.attempts, 0);
7781        assert!(
7782            stalled.status.runnable(),
7783            "a machine problem must leave the task in line"
7784        );
7785
7786        let mut blocked = task();
7787        blocked.start("20260902-000000-aaaa".to_owned());
7788        settle(
7789            &mut blocked,
7790            Verdict {
7791                status: RunStatus::Blocked,
7792                left_pr: false,
7793                parked: false,
7794                quota_hit: false,
7795                no_viable_candidates: false,
7796            },
7797            "findings open",
7798            1,
7799        );
7800        assert_eq!(blocked.attempts, 1);
7801        assert_eq!(
7802            blocked.status,
7803            TaskStatus::Held,
7804            "the last attempt hands the task to a human"
7805        );
7806    }
7807
7808    #[test]
7809    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
7810        // Attempts to spare: without the pull request this task would go
7811        // straight back in line and run the whole competition again.
7812        let mut delivered = task();
7813        delivered.start("20260903-080619-01c2".to_owned());
7814        settle(
7815            &mut delivered,
7816            Verdict {
7817                status: RunStatus::Blocked,
7818                left_pr: true,
7819                parked: false,
7820                quota_hit: false,
7821                no_viable_candidates: false,
7822            },
7823            "no check status",
7824            4,
7825        );
7826        assert_eq!(
7827            delivered.status,
7828            TaskStatus::Held,
7829            "a pull request waiting on CI or a person is not a retryable failure"
7830        );
7831        assert!(
7832            !delivered.status.runnable(),
7833            "the loop must not pick this task up again"
7834        );
7835        assert_eq!(
7836            delivered.last_error.as_deref(),
7837            Some("no check status"),
7838            "the operator needs to be told what the gate was waiting for"
7839        );
7840
7841        // The same status without a pull request is a plain failure, and with
7842        // attempts left it is retried.
7843        let mut empty_handed = task();
7844        empty_handed.start("20260903-080619-01c2".to_owned());
7845        settle(
7846            &mut empty_handed,
7847            Verdict {
7848                status: RunStatus::Blocked,
7849                left_pr: false,
7850                parked: false,
7851                quota_hit: false,
7852                no_viable_candidates: false,
7853            },
7854            "findings open",
7855            4,
7856        );
7857        assert_eq!(empty_handed.status, TaskStatus::Failed);
7858        assert!(empty_handed.status.runnable());
7859    }
7860
7861    #[test]
7862    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
7863        // Every candidate agreed, with evidence, that nothing belonged in the
7864        // worktree. That is not a confirmed success to close automatically -
7865        // a human still has to check the claim - and it is not an ordinary
7866        // failure either, so this settles exactly like a pull request nobody
7867        // merged yet: `Held`, same as `Blocked` with a PR.
7868        let mut noop = task();
7869        noop.start("20260912-131304-391f".to_owned());
7870        settle(
7871            &mut noop,
7872            Verdict {
7873                status: RunStatus::VerifiedNoop,
7874                left_pr: false,
7875                parked: false,
7876                quota_hit: false,
7877                no_viable_candidates: true,
7878            },
7879            "candidate A: already fixed by b32cfc4, on main",
7880            4,
7881        );
7882        assert_eq!(
7883            noop.status,
7884            TaskStatus::Held,
7885            "an unverified claim is a request for a human, not a failure"
7886        );
7887        assert!(
7888            !noop.status.runnable(),
7889            "the loop must not requeue this on the same unverified claim"
7890        );
7891        // `Task::release` resets attempts to zero the moment a human looks at
7892        // the evidence and lets it run again, so it does not matter here
7893        // whether the one attempt already spent stays spent - what matters is
7894        // that nothing retries this task unattended in the meantime.
7895        assert_eq!(noop.attempts, 1);
7896    }
7897
7898    #[test]
7899    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
7900        // Parking is the operator asking for the process back - to replace the
7901        // binary, most of all. The run's work is intact on disk, so this is
7902        // not a failed attempt, and charging for it would mean a few upgrades
7903        // could exhaust a budget meant for agents that misbehaved.
7904        let mut parked = task();
7905        parked.start("20260903-183634-2d98".to_owned());
7906        settle(
7907            &mut parked,
7908            Verdict {
7909                status: RunStatus::Implementing,
7910                left_pr: false,
7911                quota_hit: false,
7912                parked: true,
7913                no_viable_candidates: false,
7914            },
7915            "parked after `implementing`",
7916            2,
7917        );
7918        assert_eq!(parked.attempts, 0, "a park is refunded");
7919        assert!(
7920            parked.status.runnable(),
7921            "and the task stays in line so the next loop resumes its run"
7922        );
7923        assert_eq!(parked.status, TaskStatus::Parked);
7924        assert_eq!(
7925            parked.park_reason.as_deref(),
7926            Some("parked after `implementing`"),
7927            "the card says where it stopped"
7928        );
7929        assert_eq!(parked.last_error, None, "nothing failed");
7930
7931        // Without the park flag the same non-terminal status is what it always
7932        // was: `execute` returning mid-flight, which is a bug and spends an
7933        // attempt so a task cannot loop on it forever.
7934        let mut broken = task();
7935        broken.start("20260903-183634-2d98".to_owned());
7936        settle(
7937            &mut broken,
7938            Verdict {
7939                status: RunStatus::Implementing,
7940                left_pr: false,
7941                quota_hit: false,
7942                parked: false,
7943                no_viable_candidates: false,
7944            },
7945            "returned mid-flight",
7946            2,
7947        );
7948        assert_eq!(broken.attempts, 1);
7949    }
7950
7951    #[test]
7952    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
7953        // Run e633: quorum lost because two judges answered with the wrong
7954        // JSON shape, `quota: []`. Refunding that takes the bound off the
7955        // retry loop, and each retry pays for a fresh hour-long implement
7956        // wave before it can fail the same way.
7957        let mut flaky = task();
7958        flaky.start("20260903-123023-e633".to_owned());
7959        settle(
7960            &mut flaky,
7961            Verdict {
7962                status: RunStatus::Stalled,
7963                left_pr: false,
7964                parked: false,
7965                quota_hit: false,
7966                no_viable_candidates: false,
7967            },
7968            "verdict rests on 1 of 3 judges",
7969            2,
7970        );
7971        assert_eq!(
7972            flaky.attempts, 1,
7973            "flakiness spends an attempt, so `max_attempts` still bounds it"
7974        );
7975        assert!(flaky.status.runnable(), "and it is still worth retrying");
7976
7977        // The same status, lost to a rate limit, is the machine's fault.
7978        let mut limited = task();
7979        limited.start("20260903-123023-e633".to_owned());
7980        settle(
7981            &mut limited,
7982            Verdict {
7983                status: RunStatus::Stalled,
7984                left_pr: false,
7985                parked: false,
7986                quota_hit: true,
7987                no_viable_candidates: false,
7988            },
7989            "judge-2, judge-3 out of quota",
7990            2,
7991        );
7992        assert_eq!(limited.attempts, 0, "a quota window is refunded");
7993        assert!(limited.status.runnable());
7994
7995        // And the bound really binds: a task that keeps stalling on flakiness
7996        // reaches a human instead of running the roster forever.
7997        let mut worn = task();
7998        for _ in 0..2 {
7999            worn.release();
8000        }
8001        worn.start("20260903-123023-e633".to_owned());
8002        worn.attempts = 2;
8003        settle(
8004            &mut worn,
8005            Verdict {
8006                status: RunStatus::Stalled,
8007                left_pr: false,
8008                parked: false,
8009                quota_hit: false,
8010                no_viable_candidates: false,
8011            },
8012            "no quorum again",
8013            2,
8014        );
8015        assert_eq!(worn.status, TaskStatus::Held);
8016        assert!(!worn.status.runnable());
8017    }
8018
8019    #[test]
8020    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8021        // The implement wave loses every seat to the same rate limit and
8022        // `after_implement` bails with nothing viable, which surfaces as
8023        // `Failed` rather than `Stalled`. That is the same machine fact the
8024        // `Stalled`-quota row already refunds, and must be refunded the same
8025        // way, or a quota outage quietly holds every task it touches instead
8026        // of leaving them in line for the reset.
8027        let mut wiped_out = task();
8028        wiped_out.start("20260907-025000-a1b2".to_owned());
8029        settle(
8030            &mut wiped_out,
8031            Verdict {
8032                status: RunStatus::Failed,
8033                left_pr: false,
8034                parked: false,
8035                quota_hit: true,
8036                no_viable_candidates: true,
8037            },
8038            "no candidate produced a change; nothing to judge",
8039            2,
8040        );
8041        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8042        assert!(
8043            wiped_out.status.runnable(),
8044            "a machine problem must leave the task in line"
8045        );
8046
8047        // This is the exemption that must stay narrow: a candidate that did
8048        // produce a change, and then failed for some other reason, still
8049        // spends the attempt even though a seat elsewhere hit its quota.
8050        // Otherwise every ordinary failure that happens to share a run with
8051        // an unrelated rate limit would be refunded for free.
8052        let mut partial_progress = task();
8053        partial_progress.start("20260907-025500-c3d4".to_owned());
8054        settle(
8055            &mut partial_progress,
8056            Verdict {
8057                status: RunStatus::Failed,
8058                left_pr: false,
8059                parked: false,
8060                quota_hit: true,
8061                no_viable_candidates: false,
8062            },
8063            "gate failed on the winning candidate",
8064            2,
8065        );
8066        assert_eq!(
8067            partial_progress.attempts, 1,
8068            "a candidate that actually produced a change spends the attempt \
8069             even though some other seat hit its quota"
8070        );
8071        assert!(partial_progress.status.runnable());
8072    }
8073
8074    #[test]
8075    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8076        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
8077        // disk, and that construction must reach the same conclusion as the
8078        // one `attempt` builds from a live run, or a crash at exactly the
8079        // wrong moment gives a recovered task a different policy than one a
8080        // daemon finished settling itself.
8081        let mut t = task();
8082        t.start("20260907-025000-a1b2".to_owned());
8083        let mut state = run_state(RunStatus::Failed);
8084        state.quota.push(QuotaLoss {
8085            cause: crate::agent::QuotaCause::UsageLimit,
8086            agent: String::new(),
8087            seat: "cand-a".to_owned(),
8088            node: "implement".to_owned(),
8089            at: Timestamp::now(),
8090            reset: None,
8091        });
8092        assert!(
8093            state.viable().is_empty(),
8094            "no candidate was added, so nothing is viable"
8095        );
8096        reclaim(&mut t, Some(state), 2, "en");
8097        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8098        assert!(t.status.runnable());
8099    }
8100
8101    #[test]
8102    fn a_held_task_is_never_offered_to_the_loop() {
8103        let dir = tempfile::tempdir().unwrap();
8104        let queue = Queue::at(dir.path().to_path_buf());
8105        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8106            let mut t = task();
8107            t.id = format!("2026090{n}-000000-000{n}");
8108            t.priority = priority;
8109            queue.put(&mut t).unwrap();
8110        }
8111        let mut held = task();
8112        held.id = "20260909-000000-9999".to_owned();
8113        held.priority = 99;
8114        held.hold_machine(None);
8115        queue.put(&mut held).unwrap();
8116
8117        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8118        assert_eq!(order.len(), 3);
8119        assert!(!order.contains(&held.id));
8120        assert_eq!(
8121            order.first().cloned(),
8122            queue.next_runnable().map(|t| t.id),
8123            "the loop's first candidate is exactly what the queue offers"
8124        );
8125        assert_eq!(
8126            order,
8127            vec![
8128                "20260902-000000-0002".to_owned(),
8129                "20260903-000000-0003".to_owned(),
8130                "20260901-000000-0001".to_owned(),
8131            ],
8132            "priority first, then oldest, so nothing starves"
8133        );
8134    }
8135
8136    #[test]
8137    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8138        let dir = tempfile::tempdir().unwrap();
8139        let queue = Queue::at(dir.path().to_path_buf());
8140        let mut old = task();
8141        old.id = "20260101-000000-old0".to_owned();
8142        queue.put(&mut old).unwrap();
8143        let mut fresh = task();
8144        fresh.id = "20260101-000000-new0".to_owned();
8145        queue.put(&mut fresh).unwrap();
8146
8147        // No parseable pid at all, so age is the only signal there is to
8148        // check - unlike a real `Queue::claim`, which always names a real,
8149        // and therefore alive, pid this test cannot fake as dead.
8150        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8151        std::thread::sleep(Duration::from_millis(60));
8152        let live = queue.claim(&fresh.id).unwrap();
8153
8154        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8155        assert_eq!(swept, vec![old.id.clone()]);
8156        assert!(
8157            queue.claim(&old.id).is_ok(),
8158            "an unparseable lock older than the threshold is swept"
8159        );
8160        assert!(
8161            queue.claim(&fresh.id).is_err(),
8162            "a live pid protects its lock regardless of age"
8163        );
8164        drop(live);
8165    }
8166
8167    #[test]
8168    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8169        // A live worker's claim remains authoritative even beyond the sweep's
8170        // age limit. Sweeping it would permit a second competing attempt.
8171        let dir = tempfile::tempdir().unwrap();
8172        let queue = Queue::at(dir.path().to_path_buf());
8173        let mut t = task();
8174        t.id = "20260101-000000-live".to_owned();
8175        queue.put(&mut t).unwrap();
8176
8177        let claim = queue.claim(&t.id).unwrap();
8178        std::thread::sleep(Duration::from_millis(60));
8179
8180        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8181        assert!(
8182            swept.is_empty(),
8183            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8184        );
8185        assert!(
8186            queue.claim(&t.id).is_err(),
8187            "the lock still protects its task"
8188        );
8189        drop(claim);
8190    }
8191
8192    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8193    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8194    fn injected_dead_pid() -> u32 {
8195        std::process::id().checked_add(1).unwrap_or(1)
8196    }
8197
8198    #[test]
8199    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8200        let dir = tempfile::tempdir().unwrap();
8201        let queue = Queue::at(dir.path().to_path_buf());
8202        let mut t = task();
8203        t.id = "20260101-000000-dead".to_owned();
8204        queue.put(&mut t).unwrap();
8205        let dead_pid = injected_dead_pid();
8206
8207        // Written directly rather than through `Queue::claim`, which would
8208        // stamp this test process's own very much alive pid and defeat the
8209        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8210        // like moments after it died, not six hours later.
8211        std::fs::write(
8212            dir.path().join(format!("{}.lock", t.id)),
8213            dead_pid.to_string(),
8214        )
8215        .unwrap();
8216
8217        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8218            pid != dead_pid
8219        });
8220        assert_eq!(
8221            swept,
8222            vec![t.id.clone()],
8223            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8224        );
8225        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8226    }
8227
8228    #[test]
8229    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8230        let dir = tempfile::tempdir().unwrap();
8231        let queue = Queue::at(dir.path().to_path_buf());
8232        let mut t = task();
8233        t.id = "20260101-000000-late".to_owned();
8234        queue.put(&mut t).unwrap();
8235        let dead_pid = injected_dead_pid();
8236
8237        // Tick one, standing in for the sweep `poll` already runs at
8238        // startup: nothing to find yet.
8239        assert!(
8240            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8241            "nothing has claimed the task yet"
8242        );
8243
8244        // A second daemon claims the task and dies before it ever writes
8245        // `running`, well after this loop's own startup sweep already ran.
8246        std::fs::write(
8247            dir.path().join(format!("{}.lock", t.id)),
8248            dead_pid.to_string(),
8249        )
8250        .unwrap();
8251
8252        // Tick two, standing in for a poll long into this daemon's uptime:
8253        // the same function, called again, notices what only just appeared -
8254        // proving the sweep is not a one-shot startup check.
8255        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8256            pid != dead_pid
8257        });
8258        assert_eq!(swept, vec![t.id.clone()]);
8259    }
8260
8261    #[test]
8262    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8263        // `reclaim_orphaned_running` looks up the task's last run, which
8264        // touches `run::home()`; the first call anywhere in this binary wins,
8265        // so this is a no-op if another test already pinned one, and either
8266        // way the run id below is never written under it.
8267        crate::run::pin_test_home();
8268        let dir = tempfile::tempdir().unwrap();
8269        let queue = Queue::at(dir.path().to_path_buf());
8270        let mut t = task();
8271        t.id = "20260101-000000-crsh".to_owned();
8272        t.status = TaskStatus::Running;
8273        t.attempts = 1;
8274        // No `run.json` behind this id: standing in for a run this test does
8275        // not need to make readable, since the point is the lock, not the
8276        // recovery table `reclaim` already has its own tests for.
8277        t.runs.push("20260904-000000-4043".to_owned());
8278        queue.put(&mut t).unwrap();
8279        let dead_pid = injected_dead_pid();
8280
8281        // The crashed daemon's own claim, naming a pid nothing on the
8282        // machine holds anymore.
8283        std::fs::write(
8284            dir.path().join(format!("{}.lock", t.id)),
8285            dead_pid.to_string(),
8286        )
8287        .unwrap();
8288
8289        // Before the lock is swept the task looks claimed, and
8290        // `reclaim_orphaned_running` must leave it alone - this is exactly
8291        // the bug: a `running` task stranded behind a dead daemon's lock,
8292        // invisible to the claim-as-proof check because the lock outlived
8293        // the process that wrote it.
8294        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8295        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8296
8297        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8298            pid != dead_pid
8299        });
8300        assert_eq!(swept, vec![t.id.clone()]);
8301
8302        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8303        assert_eq!(reclaimed, vec![t.id.clone()]);
8304        let after = queue.get(&t.id).unwrap();
8305        assert_eq!(
8306            after.status,
8307            TaskStatus::Held,
8308            "no run.json to recover from, so a human is asked"
8309        );
8310        assert_eq!(
8311            after.runs,
8312            vec!["20260904-000000-4043".to_owned()],
8313            "the crashed run's id is kept as evidence, not discarded"
8314        );
8315    }
8316
8317    #[test]
8318    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8319        let dir = tempfile::tempdir().unwrap();
8320        let queue = Queue::at(dir.path().to_path_buf());
8321        let mut t = task();
8322        t.id = "20260101-000000-unknown".to_owned();
8323        queue.put(&mut t).unwrap();
8324        let dead_pid = injected_dead_pid();
8325        std::fs::write(
8326            dir.path().join(format!("{}.lock", t.id)),
8327            dead_pid.to_string(),
8328        )
8329        .unwrap();
8330
8331        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8332        assert!(swept.is_empty(), "an unknown pid must keep its lock");
8333        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8334    }
8335
8336    fn run_state_in(status: RunStatus, language: &str) -> RunState {
8337        let mut s = run_state(status);
8338        s.config.graph.language = language.to_owned();
8339        s
8340    }
8341
8342    fn unstarted_verdict(status: RunStatus) -> Verdict {
8343        Verdict {
8344            status,
8345            left_pr: false,
8346            quota_hit: false,
8347            parked: false,
8348            no_viable_candidates: false,
8349        }
8350    }
8351
8352    #[test]
8353    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8354        let mut t = task();
8355        t.attempts = 1;
8356        settle_in(
8357            &mut t,
8358            unstarted_verdict(RunStatus::AlreadyInBase),
8359            "already in main",
8360            1,
8361            phrases("en"),
8362        );
8363        assert_eq!(t.status, TaskStatus::Done);
8364        assert_eq!(t.attempts, 0);
8365    }
8366
8367    #[test]
8368    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8369        let reason = |language: &str| {
8370            let mut t = task();
8371            settle_in(
8372                &mut t,
8373                unstarted_verdict(RunStatus::Judging),
8374                "boom",
8375                1,
8376                phrases(language),
8377            );
8378            t.last_error.or(t.hold_reason).unwrap_or_default()
8379        };
8380        assert!(
8381            reason("en").starts_with("the graph stopped at `"),
8382            "{}",
8383            reason("en")
8384        );
8385        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8386        assert!(reason("日本語").contains("boom"));
8387        assert_eq!(reason("fr"), reason("en"));
8388    }
8389
8390    #[test]
8391    fn describe_follows_the_run_language_and_keeps_the_run_id() {
8392        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8393        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8394        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8395        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8396        assert!(ja.contains("[run "), "{ja}");
8397        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8398        assert!(ended.starts_with("run 終了: "), "{ended}");
8399        let mut de = run_state_in(RunStatus::Failed, "de");
8400        let mut en = run_state_in(RunStatus::Failed, "en");
8401        de.id = "same".to_owned();
8402        en.id = "same".to_owned();
8403        assert_eq!(describe(&de), describe(&en));
8404    }
8405
8406    #[test]
8407    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8408        use crate::handover::Refused;
8409        let cases = [
8410            Refused::Foreign {
8411                branch: "b".into(),
8412                path: "/w/x".into(),
8413                why: "made by hand".into(),
8414            },
8415            Refused::Unsafe {
8416                branch: "b".into(),
8417                path: "/w/x".into(),
8418                why: "its worktree has uncommitted changes (a.rs)".into(),
8419            },
8420            Refused::ReleaseFailed {
8421                branch: "b".into(),
8422                path: "/w/x".into(),
8423                run: "ab12".into(),
8424            },
8425        ];
8426        for r in &cases {
8427            let en = (phrases("en").handover_refused)(r);
8428            assert_eq!(en, r.to_string());
8429            let ja = (phrases("ja").handover_refused)(r);
8430            assert!(
8431                !ja.contains("is checked out") && !ja.contains("try again"),
8432                "{ja}"
8433            );
8434            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8435            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8436                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8437            }
8438        }
8439        assert!(phrases("en").handover_hint.contains("release the task"));
8440        assert!(phrases("ja").handover_hint.contains("解放"));
8441    }
8442
8443    #[test]
8444    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8445        let build = |lang: &str| {
8446            let mut s = run_state_in(RunStatus::Blocked, lang);
8447            s.id = "same".to_owned();
8448            s.config.graph.review_rounds = 3;
8449            let mut r = review_round(3);
8450            r.expected = 3;
8451            r.answered = 1;
8452            s.reviews.push(r);
8453            s.event(
8454                "review",
8455                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8456            );
8457            s
8458        };
8459        let en = describe(&build("en"));
8460        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8461        let ja = describe(&build("ja"));
8462        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8463        assert!(!ja.contains("never answered"), "{ja}");
8464        assert!(ja.contains("[run "), "{ja}");
8465
8466        // An incomplete panel whose verification failed is a different stop:
8467        // the real event must survive in ja too.
8468        let mut failed = build("ja");
8469        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8470            command: "cargo test".to_owned(),
8471            code: Some(1),
8472            output_tail: String::new(),
8473            duration_ms: 0,
8474            resource_blocked: false,
8475        });
8476        failed.event("review", "stopped; e2e failed: cargo test");
8477        let ja = describe(&failed);
8478        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8479        assert!(!ja.contains("席のレビュアー"), "{ja}");
8480    }
8481
8482    #[test]
8483    fn refusals_and_recovery_prose_follow_the_language() {
8484        let home = crate::run::test_home();
8485        let t = held_task_with("r1");
8486        let q = action_question(
8487            "r1",
8488            ask::ChoiceAction::Resume {
8489                run: "r1".to_owned(),
8490            },
8491        );
8492        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
8493            ActionDecision::Refuse(s) => s,
8494            other => panic!("{other:?}"),
8495        };
8496        assert!(refuse(phrases("en")).contains("could not be read: gone"));
8497        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8498        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8499
8500        let mut held = task();
8501        reclaim(&mut held, None, 2, "ja");
8502        assert!(held.hold_reason.unwrap().contains("保留にしました"));
8503        let mut held = task();
8504        reclaim(&mut held, None, 2, "xx");
8505        assert!(held.hold_reason.unwrap().contains("held for a human"));
8506    }
8507
8508    fn run_state(status: RunStatus) -> RunState {
8509        let mut state = RunState::new(
8510            PathBuf::from("/repo"),
8511            "main".to_owned(),
8512            "abc1234def".to_owned(),
8513            "add retries".to_owned(),
8514            Config::default(),
8515        );
8516        state.status = status;
8517        state
8518    }
8519
8520    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8521        Candidate {
8522            index: 0,
8523            label,
8524            agent: "claude".to_owned(),
8525            branch: format!("magi/x/{label}"),
8526            worktree: PathBuf::from("/repo"),
8527            summary: summary.to_owned(),
8528            stat: String::new(),
8529            files: 0,
8530            commits: usize::from(!empty),
8531            empty,
8532            failed: failed.map(str::to_owned),
8533            verified_noop: None,
8534            duration_ms: 0,
8535            folded: false,
8536        }
8537    }
8538
8539    #[test]
8540    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8541        let mut state = run_state(RunStatus::Blocked);
8542        state.gate = vec![
8543            CommandOutcome {
8544                command: "cargo make check".to_owned(),
8545                code: Some(0),
8546                output_tail: "ok".to_owned(),
8547                duration_ms: 0,
8548                resource_blocked: false,
8549            },
8550            CommandOutcome {
8551                command: "cargo test".to_owned(),
8552                code: Some(101),
8553                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8554                duration_ms: 0,
8555                resource_blocked: false,
8556            },
8557        ];
8558        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8559        assert!(d.contains("cargo test"), "{d}");
8560        assert!(
8561            !d.contains("cargo make check"),
8562            "a passing check is not a diagnostic: {d}"
8563        );
8564        assert!(d.contains("assertion failed"), "{d}");
8565    }
8566
8567    #[test]
8568    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8569        let mut state = run_state(RunStatus::Blocked);
8570        state.event(
8571            "land",
8572            "stopped: the fixer produced no commit while 2 check(s) were failing \
8573             (build, lint); stopping instead of looping on an unchanged tree",
8574        );
8575        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8576        assert!(d.contains("build"), "{d}");
8577        assert!(d.contains("lint"), "{d}");
8578        assert!(d.contains("fixer produced no commit"), "{d}");
8579    }
8580
8581    #[test]
8582    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8583        // `describe`'s output becomes `Task::last_error` verbatim, and the
8584        // phone renders that in the same alarm-styled box an ordinary
8585        // failure gets. A bare `verified_noop` there would read exactly like
8586        // the failure this status exists to be told apart from.
8587        let state = run_state(RunStatus::VerifiedNoop);
8588        let d = describe(&state);
8589        assert!(
8590            d.contains("agent-verified no-op"),
8591            "expected the display label, not the wire spelling: {d}"
8592        );
8593        assert!(!d.contains("verified_noop"), "{d}");
8594    }
8595
8596    #[test]
8597    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
8598        let mut state = run_state(RunStatus::Failed);
8599        state.gate.push(crate::run::CommandOutcome {
8600            command: "cargo test".into(),
8601            code: Some(101),
8602            output_tail: format!(
8603                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8604                "  41: 0x1234 - backtrace frame\n".repeat(10000)
8605            ),
8606            duration_ms: 1,
8607            resource_blocked: false,
8608        });
8609        let d = diagnostic(&state).unwrap();
8610        assert!(d.contains("panicked at widget.rs:12"), "{d}");
8611        assert!(d.contains("assertion failed: widget missing"));
8612        assert!(d.contains("widget log"));
8613    }
8614
8615    #[test]
8616    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8617        // The whole point of the feature: a run held as "no candidate produced
8618        // a change" can mean the implementer actually finished the task and
8619        // only left a clean local tree behind - see AGENTS.md on this exact
8620        // failure mode. The diagnostic has to carry what the agent actually
8621        // said, not just the fact that nothing was there to judge.
8622        let mut state = run_state(RunStatus::Failed);
8623        state.candidates = vec![candidate(
8624            'A',
8625            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8626            true,
8627            None,
8628        )];
8629        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8630        assert!(d.contains("candidate A"), "{d}");
8631        assert!(d.contains("tagged v1.2.3"), "{d}");
8632    }
8633
8634    #[test]
8635    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8636        let mut state = run_state(RunStatus::Failed);
8637        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8638        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8639        assert!(d.contains("candidate A"), "{d}");
8640        assert!(d.contains("agent timed out"), "{d}");
8641    }
8642
8643    #[test]
8644    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8645        // A viable candidate existed, the gate never ran, and nothing land
8646        // said matches - `Task::last_error` is left to explain this one alone.
8647        let mut state = run_state(RunStatus::Failed);
8648        state.candidates = vec![candidate('A', "did the work", false, None)];
8649        assert!(diagnostic(&state).is_none());
8650    }
8651
8652    #[test]
8653    fn diagnostic_is_bounded_however_much_a_run_printed() {
8654        let mut state = run_state(RunStatus::Blocked);
8655        state.gate = vec![
8656            CommandOutcome {
8657                command: "cargo test".to_owned(),
8658                code: Some(101),
8659                output_tail: "x".repeat(50_000),
8660                duration_ms: 0,
8661                resource_blocked: false,
8662            },
8663            CommandOutcome {
8664                command: "cargo clippy".to_owned(),
8665                code: Some(1),
8666                output_tail: "y".repeat(50_000),
8667                duration_ms: 0,
8668                resource_blocked: false,
8669            },
8670        ];
8671        state.candidates = vec![
8672            candidate('A', &"z".repeat(50_000), true, None),
8673            candidate('B', &"w".repeat(50_000), true, None),
8674        ];
8675        let d = diagnostic(&state).expect("plenty here to diagnose");
8676        assert!(
8677            d.len() <= DIAGNOSTIC_MAX,
8678            "diagnostic grew to {} bytes, unbounded",
8679            d.len()
8680        );
8681    }
8682
8683    #[test]
8684    fn selected_delivery_guards_survive_recovery_failure_accounting() {
8685        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8686            let mut t = task();
8687            let mut state = run_state(status);
8688            t.pr_recovery = Some(crate::pr_recovery::Selection {
8689                url: "url".into(),
8690                branch: format!("magi/task-{}", t.id),
8691                head: "a".repeat(40),
8692                source_head: None,
8693                source_run: None,
8694                source_proof: None,
8695                disposition: Some(crate::pr_recovery::Disposition::Land),
8696                instruction: t.instruction.clone(),
8697                approved_at: Timestamp::now(),
8698            });
8699            state.pr_recovery = t.pr_recovery.clone();
8700            t.start(state.id.clone());
8701            settle_and_diagnose(
8702                &mut t,
8703                Verdict {
8704                    status,
8705                    left_pr: false,
8706                    quota_hit: false,
8707                    parked: false,
8708                    no_viable_candidates: false,
8709                },
8710                "delivery stopped",
8711                5,
8712                &state,
8713            );
8714            assert_eq!(t.status, TaskStatus::Held);
8715            let reason = t.hold_reason.as_deref().unwrap();
8716            if status == RunStatus::Ready {
8717                assert!(reason.contains("Selected PR delivery is incomplete"));
8718                assert!(t.recovery_budget.is_none());
8719            } else {
8720                assert!(reason.contains("Selected recovery stopped"));
8721                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8722            }
8723            assert!(t.pr_recovery.is_some());
8724        }
8725    }
8726
8727    #[test]
8728    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
8729        let mut state = run_state(RunStatus::Voting);
8730        state.base_sync = Some(crate::run::BaseSync {
8731            tip: "base-tip".into(),
8732            behind: 3,
8733            attempts: 4,
8734            conflict: Some("base stopped".into()),
8735            already_in: None,
8736        });
8737        state.record_base_sync_stop("candidate-head");
8738        let mut t = task();
8739        t.start(state.id.clone());
8740        let verdict = Verdict {
8741            status: RunStatus::Blocked,
8742            left_pr: false,
8743            quota_hit: false,
8744            parked: false,
8745            no_viable_candidates: false,
8746        };
8747        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8748        assert_eq!(
8749            t.status,
8750            TaskStatus::Held,
8751            "unspent task attempts cannot start another competition"
8752        );
8753        let at = t.held_at;
8754        let cause = t.hold_notice_cause.clone();
8755        state.begin_pass();
8756        t.release_operator("test-resume", None);
8757        t.start(state.id.clone());
8758        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8759        assert_eq!(t.status, TaskStatus::Held);
8760        assert_eq!(t.held_at, at);
8761        assert_eq!(t.hold_notice_cause, cause);
8762    }
8763
8764    #[test]
8765    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8766        let mut state = run_state(RunStatus::Blocked);
8767        state.gate = vec![CommandOutcome {
8768            command: "cargo test".to_owned(),
8769            code: Some(101),
8770            output_tail: "assertion failed".to_owned(),
8771            duration_ms: 0,
8772            resource_blocked: false,
8773        }];
8774        let verdict = Verdict {
8775            status: RunStatus::Blocked,
8776            left_pr: false,
8777            quota_hit: false,
8778            parked: false,
8779            no_viable_candidates: false,
8780        };
8781
8782        // Attempt one of two still has a retry coming: no diagnostic yet, the
8783        // task is going to run again and this run's evidence would go stale.
8784        let mut t = task();
8785        t.start("run-1".to_owned());
8786        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8787        assert_eq!(t.status, TaskStatus::Failed);
8788        assert!(t.diagnostic.is_none());
8789
8790        // Attempt two exhausts the budget: now it is held, and the
8791        // diagnostic is what `magi task show` has to say more than one line.
8792        t.start("run-2".to_owned());
8793        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8794        assert_eq!(t.status, TaskStatus::Held);
8795        let d = t.diagnostic.expect("a held task must carry its diagnostic");
8796        assert!(d.contains("cargo test"), "{d}");
8797    }
8798
8799    #[test]
8800    fn a_held_task_names_the_open_question_it_is_waiting_on() {
8801        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
8802        // `magi ask` question settled Held with `hold_reason: null`, so the
8803        // notification said nothing actionable. `note_open_question` should
8804        // append the question id to whatever `handed_off` already wrote.
8805        crate::run::pin_test_home();
8806        let home = crate::run::home();
8807        let state = run_state(RunStatus::VerifiedNoop);
8808        let mut q = ask::Question::new(
8809            state.id.clone(),
8810            "implement".to_owned(),
8811            "impl-A".to_owned(),
8812            "is this really a no-op?".to_owned(),
8813            String::new(),
8814            Vec::new(),
8815        );
8816        Questions::at(home.join("questions")).put(&mut q).unwrap();
8817
8818        let verdict = Verdict {
8819            status: RunStatus::VerifiedNoop,
8820            left_pr: false,
8821            quota_hit: false,
8822            parked: false,
8823            no_viable_candidates: false,
8824        };
8825        let mut t = task();
8826        t.start(state.id.clone());
8827        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8828
8829        assert_eq!(t.status, TaskStatus::Held);
8830        let reason = t.hold_reason.expect("a held task must record why");
8831        assert!(
8832            reason.starts_with("run ended agent-verified no-op"),
8833            "the original settle reason must survive unchanged: {reason}"
8834        );
8835        assert!(
8836            reason.contains(q.short()),
8837            "the open question's id must be named so the notice is actionable: {reason}"
8838        );
8839    }
8840
8841    #[test]
8842    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8843        crate::run::pin_test_home();
8844        let state = run_state(RunStatus::VerifiedNoop);
8845
8846        let verdict = Verdict {
8847            status: RunStatus::VerifiedNoop,
8848            left_pr: false,
8849            quota_hit: false,
8850            parked: false,
8851            no_viable_candidates: false,
8852        };
8853        let mut t = task();
8854        t.start(state.id.clone());
8855        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8856
8857        assert_eq!(t.status, TaskStatus::Held);
8858        assert_eq!(
8859            t.hold_reason.as_deref(),
8860            Some("run ended agent-verified no-op"),
8861            "nothing to append when the question was already answered or never asked"
8862        );
8863    }
8864
8865    #[test]
8866    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8867        crate::run::pin_test_home();
8868        let mut first = run_state(RunStatus::Blocked);
8869        first.id = "20260101-000000-sup1".to_owned();
8870        first.save().unwrap();
8871        let mut second = run_state(RunStatus::Merged);
8872        second.id = "20260101-000000-sup2".to_owned();
8873        second.save().unwrap();
8874
8875        let mut t = task();
8876        t.runs = vec![first.id.clone(), second.id.clone()];
8877        t.status = TaskStatus::Done;
8878
8879        supersede_prior_runs(&t, &crate::run::home());
8880
8881        assert_eq!(
8882            RunState::load(&first.id).unwrap().status,
8883            RunStatus::Superseded,
8884            "the first attempt's Blocked no longer needs anyone's attention"
8885        );
8886        assert_eq!(
8887            RunState::load(&second.id).unwrap().status,
8888            RunStatus::Merged,
8889            "the run that actually succeeded is left exactly as it was"
8890        );
8891    }
8892
8893    #[test]
8894    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
8895        // `is_working_on` alone only proves a *daemon* claim; a `magi run
8896        // --resume` invoked by hand outside the daemon never touches
8897        // `daemon.json` at all, so it would look identical to a genuinely
8898        // idle run without also consulting `RunState::liveness`, which reads
8899        // this run's own recorded `driver_pid` instead.
8900        crate::run::pin_test_home();
8901        let mut first = run_state(RunStatus::Blocked);
8902        first.id = "20260101-000000-sup9".to_owned();
8903        // This test process's own pid: guaranteed alive without needing a
8904        // real second process or daemon.
8905        first.driver_pid = Some(std::process::id());
8906        first.driver_started_at = Some(
8907            crate::proc::process_started_at(std::process::id())
8908                .expect("this test process's own start time must be queryable"),
8909        );
8910        first.save().unwrap();
8911        let mut second = run_state(RunStatus::Merged);
8912        second.id = "20260101-000000-supa".to_owned();
8913        second.save().unwrap();
8914
8915        let mut t = task();
8916        t.runs = vec![first.id.clone(), second.id.clone()];
8917        t.status = TaskStatus::Done;
8918
8919        supersede_prior_runs(&t, &crate::run::home());
8920
8921        assert_eq!(
8922            RunState::load(&first.id).unwrap().status,
8923            RunStatus::Blocked,
8924            "a live driver_pid means something is still actually working this run, \
8925             even though no daemon claims it - rewriting under it would just be \
8926             undone the next time that process saves"
8927        );
8928    }
8929
8930    #[test]
8931    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
8932        // The first resweep must skip a still-live attempt exactly like
8933        // `supersede_prior_runs` itself does; a later resweep, once that
8934        // process is no longer actually driving it, is what closes the gap
8935        // `supersede_prior_runs` alone leaves - a task only ever reaches
8936        // `Done` once, so nothing else would ever look at this run again.
8937        let dir = tempfile::tempdir().unwrap();
8938        let home = dir.path().to_path_buf();
8939        let queue = Queue::at(dir.path().join("queue"));
8940
8941        let mut first = run_state(RunStatus::Blocked);
8942        first.id = "20260101-000000-supd".to_owned();
8943        first.driver_pid = Some(std::process::id());
8944        first.driver_started_at = Some(
8945            crate::proc::process_started_at(std::process::id())
8946                .expect("this test process's own start time must be queryable"),
8947        );
8948        first.save_under(&home).unwrap();
8949        let mut second = run_state(RunStatus::Merged);
8950        second.id = "20260101-000000-supe".to_owned();
8951        second.save_under(&home).unwrap();
8952
8953        let mut t = task();
8954        t.runs = vec![first.id.clone(), second.id.clone()];
8955        t.status = TaskStatus::Done;
8956        queue.put(&mut t).unwrap();
8957
8958        resweep_superseded_attempts(&queue, &home);
8959        assert_eq!(
8960            RunState::load_under(&first.id, &home).unwrap().status,
8961            RunStatus::Blocked,
8962            "still live on the first pass, so still untouched"
8963        );
8964
8965        // Stand in for the manual process no longer being the one driving
8966        // this run: same pid (this test process really is still alive), but
8967        // an identity marker that no longer matches it - see
8968        // `RunState::liveness`'s own doc for why a mismatched
8969        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
8970        let mut stale = RunState::load_under(&first.id, &home).unwrap();
8971        stale.driver_started_at = Some("1".to_owned());
8972        stale.save_under(&home).unwrap();
8973
8974        resweep_superseded_attempts(&queue, &home);
8975        assert_eq!(
8976            RunState::load_under(&first.id, &home).unwrap().status,
8977            RunStatus::Superseded,
8978            "the second pass catches up what the first one correctly skipped"
8979        );
8980    }
8981
8982    #[test]
8983    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
8984        crate::run::pin_test_home();
8985        let mut first = run_state(RunStatus::Blocked);
8986        first.id = "20260101-000000-sup3".to_owned();
8987        first.save().unwrap();
8988        let mut second = run_state(RunStatus::Blocked);
8989        second.id = "20260101-000000-sup4".to_owned();
8990        second.save().unwrap();
8991
8992        let mut t = task();
8993        t.runs = vec![first.id.clone(), second.id.clone()];
8994        // Still retrying: nothing about this task's story is settled yet, so
8995        // neither Blocked run may be relabelled, even though a later attempt
8996        // already exists.
8997        t.status = TaskStatus::Failed;
8998
8999        supersede_prior_runs(&t, &crate::run::home());
9000
9001        assert_eq!(
9002            RunState::load(&first.id).unwrap().status,
9003            RunStatus::Blocked
9004        );
9005        assert_eq!(
9006            RunState::load(&second.id).unwrap().status,
9007            RunStatus::Blocked
9008        );
9009    }
9010
9011    #[test]
9012    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9013        // `magi task done` (or the API's equivalent) can close a task with no
9014        // run of its own ever having succeeded - there is nothing here that
9015        // counts as "the attempt that finished it", so nothing is rewritten.
9016        crate::run::pin_test_home();
9017        let mut first = run_state(RunStatus::Blocked);
9018        first.id = "20260101-000000-sup5".to_owned();
9019        first.save().unwrap();
9020
9021        let mut t = task();
9022        t.runs = vec![first.id.clone()];
9023        t.status = TaskStatus::Done;
9024
9025        supersede_prior_runs(&t, &crate::run::home());
9026
9027        assert_eq!(
9028            RunState::load(&first.id).unwrap().status,
9029            RunStatus::Blocked,
9030            "a single-attempt task has no earlier run to supersede"
9031        );
9032    }
9033
9034    #[test]
9035    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9036        // `magi task done` (or the web/conductor equivalents) can close a
9037        // task in any status, including one whose *last* recorded attempt is
9038        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
9039        // never watched, say. `runs.last()` being `Done`-adjacent is not
9040        // proof it actually succeeded, so nothing earlier may be relabelled
9041        // on its say-so alone.
9042        crate::run::pin_test_home();
9043        let mut first = run_state(RunStatus::Blocked);
9044        first.id = "20260101-000000-supb".to_owned();
9045        first.save().unwrap();
9046        let mut second = run_state(RunStatus::Failed);
9047        second.id = "20260101-000000-supc".to_owned();
9048        second.save().unwrap();
9049
9050        let mut t = task();
9051        t.runs = vec![first.id.clone(), second.id.clone()];
9052        t.status = TaskStatus::Done;
9053
9054        supersede_prior_runs(&t, &crate::run::home());
9055
9056        assert_eq!(
9057            RunState::load(&first.id).unwrap().status,
9058            RunStatus::Blocked,
9059            "the task's last attempt never landed, so there is nothing here \
9060             actually superseding it"
9061        );
9062    }
9063
9064    #[test]
9065    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9066        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
9067        // to look" - `Failed` and `VerifiedNoop` are already their own
9068        // terminal answers and must not be relabelled into a third one.
9069        crate::run::pin_test_home();
9070        let mut failed = run_state(RunStatus::Failed);
9071        failed.id = "20260101-000000-sup6".to_owned();
9072        failed.save().unwrap();
9073        let mut noop = run_state(RunStatus::VerifiedNoop);
9074        noop.id = "20260101-000000-sup7".to_owned();
9075        noop.save().unwrap();
9076        let mut winner = run_state(RunStatus::Ready);
9077        winner.id = "20260101-000000-sup8".to_owned();
9078        winner.save().unwrap();
9079
9080        let mut t = task();
9081        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9082        t.status = TaskStatus::Done;
9083
9084        supersede_prior_runs(&t, &crate::run::home());
9085
9086        assert_eq!(
9087            RunState::load(&failed.id).unwrap().status,
9088            RunStatus::Failed
9089        );
9090        assert_eq!(
9091            RunState::load(&noop.id).unwrap().status,
9092            RunStatus::VerifiedNoop
9093        );
9094    }
9095
9096    fn approval_question(run: &str) -> ask::Question {
9097        ask::Question::new(
9098            run.to_owned(),
9099            land::APPROVAL_NODE.to_owned(),
9100            "land".to_owned(),
9101            "merge?".to_owned(),
9102            String::new(),
9103            vec!["merge".to_owned(), "hold".to_owned()],
9104        )
9105    }
9106
9107    #[test]
9108    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9109        crate::run::pin_test_home();
9110        let mut state = run_state(RunStatus::Landing);
9111        state.id = "20260101-000000-fre1".to_owned();
9112        state.parked = true;
9113        state.save().unwrap();
9114        ask::Questions::open()
9115            .put(&mut approval_question(&state.id))
9116            .unwrap();
9117
9118        let mut t = task();
9119        t.runs.push(state.id.clone());
9120        assert_eq!(
9121            land_resume_state(&t),
9122            LandResume::StillWaiting,
9123            "nobody has answered and the timeout has not passed"
9124        );
9125    }
9126
9127    #[test]
9128    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9129        crate::run::pin_test_home();
9130        let mut state = run_state(RunStatus::Gating);
9131        state.id = "20260101-000000-gt01".to_owned();
9132        state.parked = true;
9133        state.config.graph.answer_timeout = 60;
9134        state.github_text = Some(crate::run::GithubTextAsk {
9135            rewrite: None,
9136            fingerprint: "f".into(),
9137            title: true,
9138            body: false,
9139            categories: vec!["title-language".into()],
9140            question: None,
9141            asks: 1,
9142            resolved: false,
9143            chosen_title: None,
9144            choice: None,
9145        });
9146        state.save().unwrap();
9147        let store = ask::Questions::open();
9148        let mut q = ask::Question::new(
9149            state.id.clone(),
9150            crate::github_text::ASK_NODE.to_owned(),
9151            crate::github_text::ASK_SEAT.to_owned(),
9152            "s".into(),
9153            String::new(),
9154            vec!["use fallback".into()],
9155        );
9156        store.put(&mut q).unwrap();
9157        let mut t = task();
9158        t.runs.push(state.id.clone());
9159        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9160        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9161        store.put(&mut q).unwrap();
9162        assert_eq!(land_resume_state(&t), LandResume::Ready);
9163        assert!(!store.get(&q.id).unwrap().status.open());
9164        // Once decided, a parked run is an ordinary candidate again.
9165        state.github_text.as_mut().unwrap().resolved = true;
9166        state.save().unwrap();
9167        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9168    }
9169
9170    #[test]
9171    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9172        // `ask::ask_and_wait`'s own deadline used to retire a question
9173        // nobody answered; land's approval bypasses that wait (see
9174        // `land::approval_gate`), so this is now the only place
9175        // `graph.answer_timeout` is enforced for a land approval at all.
9176        crate::run::pin_test_home();
9177        let mut state = run_state(RunStatus::Landing);
9178        state.id = "20260101-000000-exp1".to_owned();
9179        state.parked = true;
9180        state.config.graph.answer_timeout = 60;
9181        state.save().unwrap();
9182
9183        let store = ask::Questions::open();
9184        let mut q = approval_question(&state.id);
9185        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9186        store.put(&mut q).unwrap();
9187
9188        let mut t = task();
9189        t.runs.push(state.id.clone());
9190        assert_eq!(
9191            land_resume_state(&t),
9192            LandResume::Ready,
9193            "an expired question must not be waited on forever"
9194        );
9195
9196        let after = store.get(&q.id).unwrap();
9197        assert!(
9198            !after.status.open(),
9199            "the question is abandoned, not silently ignored"
9200        );
9201        assert!(
9202            after.resolution().is_none(),
9203            "an abandoned question is not read as a decision"
9204        );
9205    }
9206
9207    #[test]
9208    fn reclaim_settles_a_running_task_against_its_last_run() {
9209        let mut t = task();
9210        t.start("20260904-000000-4043".to_owned());
9211        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9212        assert_eq!(
9213            t.status,
9214            TaskStatus::Done,
9215            "a run that actually finished must not stay `running` forever"
9216        );
9217    }
9218
9219    #[test]
9220    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9221        let mut t = task();
9222        t.start("20260904-000000-4043".to_owned());
9223        t.last_error = Some("earlier trouble".to_owned());
9224        let mut state = run_state(RunStatus::Judging);
9225        state.parked = true;
9226        reclaim(&mut t, Some(state), 1, "en");
9227        assert_eq!(t.status, TaskStatus::Parked);
9228        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9229        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9230        assert!(t.park_reason.is_some());
9231        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9232        assert!(!t.fresh_start);
9233        assert!(t.status.runnable());
9234    }
9235
9236    #[test]
9237    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9238        let mut t = task();
9239        t.start("20260904-000000-4043".to_owned());
9240        t.last_error = Some("earlier trouble".to_owned());
9241        settle(
9242            &mut t,
9243            Verdict {
9244                status: RunStatus::Judging,
9245                left_pr: false,
9246                quota_hit: false,
9247                parked: true,
9248                no_viable_candidates: false,
9249            },
9250            "parked after `judging`",
9251            1,
9252        );
9253        assert_eq!(t.status, TaskStatus::Parked);
9254        assert_eq!(t.attempts, 0);
9255        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9256        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9257        assert_eq!(t.schema, crate::queue::SCHEMA);
9258        assert!(
9259            crate::notices::task_held(&t).is_none(),
9260            "a park is not news"
9261        );
9262        t.start("20260904-000000-4043".to_owned());
9263        assert_eq!(t.park_reason, None);
9264    }
9265
9266    #[test]
9267    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9268        // A blocked run with attempts left goes back to `Failed`, exactly as
9269        // it would from `attempt` itself - `reclaim` must not invent a second
9270        // policy for a task a daemon merely stopped without reporting.
9271        let mut t = task();
9272        t.start("20260904-000000-4043".to_owned());
9273        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9274        assert_eq!(t.status, TaskStatus::Failed);
9275        assert!(t.status.runnable());
9276    }
9277
9278    #[test]
9279    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9280        let mut t = task();
9281        t.start("20260904-000000-4043".to_owned());
9282        assert_eq!(t.attempts, 1);
9283        let mut run = run_state(RunStatus::Implementing);
9284        run.id = "20260904-000000-4043".to_owned();
9285        run.begin_pass();
9286        let cause = crate::run::ParkCause::Upgrade {
9287            from: "0.121.0".to_owned(),
9288            to: Some("0.121.1".to_owned()),
9289        };
9290        run.end_pass_parked(cause.clone());
9291        run.parked = true;
9292        let verdict = Verdict {
9293            status: run.status,
9294            left_pr: false,
9295            quota_hit: false,
9296            parked: true,
9297            no_viable_candidates: false,
9298        };
9299        // A crash after the checkpoint but before queue settlement must
9300        // recover exactly the same scheduling evidence and refund.
9301        let mut orphan = t.clone();
9302        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9303        assert_eq!(orphan.status, TaskStatus::Parked);
9304        assert_eq!(orphan.attempts, 0);
9305        assert_eq!(
9306            orphan.upgrade_resume_key(),
9307            Some((run.passes[0].started_at, orphan.id.as_str()))
9308        );
9309        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9310        assert_eq!(t.attempts, 0);
9311        assert_eq!(t.passes.len(), 1);
9312        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9313        assert_eq!(t.passes[0].parked, Some(cause));
9314        assert_eq!(t.passes[0].pass_index, 0);
9315        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9316        assert!(t.upgrade_resume_key().is_some());
9317
9318        // A resumed pass that then fails spends its attempt, and the earlier
9319        // pass's entry is untouched.
9320        t.start("20260904-000000-4043".to_owned());
9321        run.begin_pass();
9322        run.status = RunStatus::Failed;
9323        let verdict = Verdict {
9324            status: RunStatus::Failed,
9325            left_pr: false,
9326            quota_hit: false,
9327            parked: false,
9328            no_viable_candidates: false,
9329        };
9330        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9331        assert_eq!(t.passes.len(), 2);
9332        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9333        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9334        assert_eq!(t.passes[1].pass_index, 1);
9335        assert_eq!(t.attempts, 1);
9336    }
9337
9338    #[test]
9339    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9340        let mut t = task();
9341        t.start("20260904-000000-4043".to_owned());
9342        reclaim(&mut t, None, 2, "en");
9343        assert_eq!(t.status, TaskStatus::Held);
9344        assert!(
9345            t.last_error
9346                .as_deref()
9347                .is_some_and(|e| e.contains("running")),
9348            "the operator needs to know why this task was held"
9349        );
9350    }
9351
9352    #[test]
9353    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9354        let dir = tempfile::tempdir().unwrap();
9355        let queue = Queue::at(dir.path().to_path_buf());
9356
9357        // No run recorded, so this never has to touch `RunState::load`.
9358        let mut orphaned = task();
9359        orphaned.id = "20260904-000000-orph".to_owned();
9360        orphaned.status = TaskStatus::Running;
9361        orphaned.attempts = 1;
9362        queue.put(&mut orphaned).unwrap();
9363
9364        let mut alive = task();
9365        alive.id = "20260904-000000-live".to_owned();
9366        alive.status = TaskStatus::Running;
9367        alive.attempts = 1;
9368        queue.put(&mut alive).unwrap();
9369        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9370
9371        let mut queued = task();
9372        queued.id = "20260904-000000-wait".to_owned();
9373        queue.put(&mut queued).unwrap();
9374
9375        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9376        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9377
9378        assert_eq!(
9379            queue.get(&orphaned.id).unwrap().status,
9380            TaskStatus::Held,
9381            "nothing was driving it and there was no run to recover"
9382        );
9383        assert_eq!(
9384            queue.get(&alive.id).unwrap().status,
9385            TaskStatus::Running,
9386            "a live claim must protect the task it belongs to"
9387        );
9388        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9389    }
9390
9391    /// Read a run.json back from an explicit `home`, the same way
9392    /// `reclaim_abandoned_runs` itself does - never through the
9393    /// process-global `RunState::load`, which this test's own `home` (an
9394    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
9395    /// use at all.
9396    fn read_run_under(home: &Path, id: &str) -> RunState {
9397        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9398        serde_json::from_str(&body).unwrap()
9399    }
9400
9401    #[test]
9402    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9403        let dir = tempfile::tempdir().unwrap();
9404        let home = dir.path().to_path_buf();
9405        let now = Timestamp::now();
9406        let overrun_seat = || crate::run::ActiveSeat {
9407            node: "implement".to_owned(),
9408            started_at: now - jiff::SignedDuration::new(21_000, 0),
9409            timeout_secs: 3_600,
9410            attempt: 0,
9411            task: None,
9412            command: None,
9413            index: None,
9414            total: None,
9415        };
9416
9417        let mut dead = run_state(RunStatus::Implementing);
9418        dead.id = "20260101-000000-dead".to_owned();
9419        dead.active.insert("impl-A".to_owned(), overrun_seat());
9420        // A `driver_pid` the injected query below confirms gone outright —
9421        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
9422        dead.driver_pid = Some(4242);
9423        dead.save_under(&home).unwrap();
9424
9425        // Same shape, but a live daemon's heartbeat names it: must be left
9426        // exactly alone, however far past its own timeout the seat sits.
9427        let mut alive = run_state(RunStatus::Implementing);
9428        alive.id = "20260101-000000-aliv".to_owned();
9429        alive.active.insert("impl-A".to_owned(), overrun_seat());
9430        alive.save_under(&home).unwrap();
9431        let mut status = Status::new();
9432        status.current = vec![Current {
9433            worker: None,
9434            task: "20260101-000000-task".to_owned(),
9435            run: alive.id.clone(),
9436        }];
9437        write_status_to(&home.join("daemon.json"), &status).unwrap();
9438
9439        // The abandoned seat left an open question behind: nobody is left to
9440        // read an answer once the run is failed, and this must not wait for
9441        // some later daemon startup's own sweep to notice that.
9442        let questions = Questions::at(home.join("questions"));
9443        let mut q = ask::Question::new(
9444            dead.id.clone(),
9445            "implement".to_owned(),
9446            "impl-A".to_owned(),
9447            "Which storage backend?".to_owned(),
9448            String::new(),
9449            vec!["SQLite".to_owned(), "Redis".to_owned()],
9450        );
9451        questions.put(&mut q).unwrap();
9452
9453        let abandoned = reclaim_abandoned_runs_with(
9454            &home,
9455            now,
9456            |pid| if pid == 4242 { Some(false) } else { None },
9457            |_| panic!("a query answering Dead outright needs no identity corroboration"),
9458        );
9459        assert_eq!(abandoned, vec![dead.id.clone()]);
9460
9461        let reloaded = read_run_under(&home, &dead.id);
9462        assert_eq!(reloaded.status, RunStatus::Failed);
9463        assert!(reloaded.active.is_empty());
9464        assert!(
9465            !questions.get(&q.id).unwrap().status.open(),
9466            "the failed run's own open question must be settled in the same pass"
9467        );
9468
9469        let still_alive = read_run_under(&home, &alive.id);
9470        assert_eq!(
9471            still_alive.status,
9472            RunStatus::Implementing,
9473            "a live daemon's claim protects it"
9474        );
9475        assert!(!still_alive.active.is_empty());
9476    }
9477
9478    /// The exact shape a review round flagged as broken: `magi serve` running
9479    /// in this same `home` scans *every* run on disk, including a manual
9480    /// `magi review` / `magi run` this daemon never started and that
9481    /// therefore claims no heartbeat of its own. Before this scan asked
9482    /// `liveness` rather than just `is_working_on`, a manual run whose active
9483    /// seat merely ran a little past its own timeout — the CLI finishing up,
9484    /// its result still being collected — got wiped and failed by a daemon
9485    /// that had nothing to do with it, out from under a process that was
9486    /// still very much running.
9487    #[test]
9488    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9489        let dir = tempfile::tempdir().unwrap();
9490        let home = dir.path().to_path_buf();
9491        let now = Timestamp::now();
9492
9493        let mut manual = run_state(RunStatus::Reviewing);
9494        manual.id = "20260101-000000-manl".to_owned();
9495        manual.active.insert(
9496            "review-1".to_owned(),
9497            crate::run::ActiveSeat {
9498                node: "review".to_owned(),
9499                started_at: now - jiff::SignedDuration::new(21_000, 0),
9500                timeout_secs: 3_600,
9501                attempt: 0,
9502                task: None,
9503                command: None,
9504                index: None,
9505                total: None,
9506            },
9507        );
9508        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
9509        // but a real, still-running process: `liveness` must corroborate this
9510        // as `Live`, not read the missing daemon claim as death.
9511        manual.driver_pid = Some(4242);
9512        manual.driver_started_at = Some("1790000000".to_owned());
9513        manual.save_under(&home).unwrap();
9514
9515        let abandoned = reclaim_abandoned_runs_with(
9516            &home,
9517            now,
9518            |pid| if pid == 4242 { Some(true) } else { None },
9519            |pid| {
9520                if pid == 4242 {
9521                    Some("1790000000".to_owned())
9522                } else {
9523                    None
9524                }
9525            },
9526        );
9527        assert!(
9528            abandoned.is_empty(),
9529            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9530        );
9531
9532        let reloaded = read_run_under(&home, &manual.id);
9533        assert_eq!(reloaded.status, RunStatus::Reviewing);
9534        assert!(!reloaded.active.is_empty());
9535    }
9536
9537    #[test]
9538    fn an_already_claimed_task_is_skipped_rather_than_failed() {
9539        let dir = tempfile::tempdir().unwrap();
9540        let queue = Queue::at(dir.path().to_path_buf());
9541        let mut only = task();
9542        queue.put(&mut only).unwrap();
9543
9544        let _elsewhere = queue.claim(&only.id).unwrap();
9545        let candidates = runnable(&queue);
9546        assert_eq!(candidates.len(), 1, "the task is still runnable");
9547        assert!(
9548            queue.claim(&candidates[0].id).is_err(),
9549            "the loop cannot take a claim somebody else holds"
9550        );
9551
9552        let after = queue.get(&only.id).unwrap();
9553        assert_eq!(after.status, TaskStatus::Queued);
9554        assert_eq!(
9555            after.attempts, 0,
9556            "losing the race is not an attempt at the task"
9557        );
9558        assert_eq!(after.last_error, None);
9559    }
9560
9561    #[test]
9562    fn the_status_file_round_trips_and_its_heartbeat_advances() {
9563        let dir = tempfile::tempdir().unwrap();
9564        let path = dir.path().join("daemon.json");
9565
9566        let mut status = Status::new();
9567        status.idle = false;
9568        status.completed = 7;
9569        status.current = vec![Current {
9570            worker: None,
9571            task: "20260902-000000-t111".to_owned(),
9572            run: "20260902-000001-r111".to_owned(),
9573        }];
9574        write_status_to(&path, &status).unwrap();
9575        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9576        assert_eq!(first.schema, SCHEMA);
9577        assert_eq!(first.pid, std::process::id());
9578        assert!(!first.idle);
9579        assert_eq!(first.completed, 7);
9580        assert_eq!(first.current, status.current);
9581        assert!(
9582            !path.with_extension("json.tmp").exists(),
9583            "the temp file is renamed, not left behind"
9584        );
9585
9586        std::thread::sleep(Duration::from_millis(5));
9587        status.updated_at = Timestamp::now();
9588        status.polls = 3;
9589        write_status_to(&path, &status).unwrap();
9590        let second: Status =
9591            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9592        assert!(
9593            second.updated_at > first.updated_at,
9594            "a reader can only detect staleness if the heartbeat moves"
9595        );
9596        assert_eq!(
9597            second.started_at, first.started_at,
9598            "the start time is not a heartbeat"
9599        );
9600        assert_eq!(second.polls, 3);
9601    }
9602
9603    #[test]
9604    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9605        let dir = tempfile::tempdir().unwrap();
9606
9607        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9608
9609        let mut status = Status::new();
9610        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9611        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9612        let stale = read_status(dir.path()).unwrap();
9613        assert!(
9614            !stale.running(Timestamp::now()),
9615            "a minute without a heartbeat is a dead daemon, not a busy one"
9616        );
9617        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9618
9619        status.updated_at = Timestamp::now();
9620        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9621        let fresh = read_status(dir.path()).unwrap();
9622        assert!(fresh.running(Timestamp::now()));
9623    }
9624
9625    #[test]
9626    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9627        let dir = tempfile::tempdir().unwrap();
9628        let now = Timestamp::now();
9629        let mine = "20260903-080619-01c2";
9630
9631        assert!(
9632            !is_working_on(dir.path(), mine, now),
9633            "no status file means nobody is working on anything"
9634        );
9635
9636        let mut status = Status::new();
9637        status.current = vec![Current {
9638            worker: None,
9639            task: "20260903-080340-0167".to_owned(),
9640            run: mine.to_owned(),
9641        }];
9642        status.updated_at = now;
9643        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9644        assert!(is_working_on(dir.path(), mine, now));
9645        assert!(
9646            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9647            "a daemon busy with one run is not working on another"
9648        );
9649
9650        // A killed daemon stops writing heartbeats but leaves the file behind
9651        // naming the run it died in. That run must not be undeletable forever.
9652        status.updated_at = now - jiff::SignedDuration::from_secs(600);
9653        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9654        assert!(
9655            !is_working_on(dir.path(), mine, now),
9656            "a stale heartbeat is a dead daemon, so its run is a leftover"
9657        );
9658    }
9659
9660    #[test]
9661    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9662        let dir = tempfile::tempdir().unwrap();
9663        let now = Timestamp::now();
9664
9665        assert!(
9666            !is_working_on_short(dir.path(), "01c2", now),
9667            "no status file means nobody is working on anything"
9668        );
9669
9670        let mut status = Status::new();
9671        status.current = vec![Current {
9672            worker: None,
9673            task: "20260903-080340-0167".to_owned(),
9674            run: "20260903-080619-01c2".to_owned(),
9675        }];
9676        status.updated_at = now;
9677        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9678        assert!(
9679            is_working_on_short(dir.path(), "01c2", now),
9680            "the run's short id is the last block of its full id"
9681        );
9682        assert!(
9683            !is_working_on_short(dir.path(), "3cbf", now),
9684            "a daemon busy with one worktree bay is not working on another"
9685        );
9686    }
9687
9688    #[test]
9689    fn a_newer_status_file_still_yields_a_reading() {
9690        let dir = tempfile::tempdir().unwrap();
9691        // A field this build has never heard of must not turn the reading into
9692        // nothing at all; that is the whole reason the reader is permissive.
9693        std::fs::write(
9694            dir.path().join("daemon.json"),
9695            serde_json::json!({
9696                "schema": 2,
9697                "updated_at": Timestamp::now().to_string(),
9698                "idle": true,
9699                "surprise": { "nested": [1, 2, 3] },
9700            })
9701            .to_string(),
9702        )
9703        .unwrap();
9704
9705        let reading = read_status(dir.path()).expect("a forward-compatible read");
9706        assert!(reading.running(Timestamp::now()));
9707        assert!(reading.idle);
9708        assert!(reading.current.is_empty());
9709    }
9710
9711    #[test]
9712    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9713        // A daemon started before `current` became a list keeps writing this
9714        // shape on every heartbeat until it is restarted. A rolling upgrade
9715        // - a newer `magi web` or `magi doctor` reading an older `magi
9716        // serve`'s heartbeat - must still see the run it is on, not "no
9717        // daemon" from a type mismatch failing the whole struct.
9718        let dir = tempfile::tempdir().unwrap();
9719        std::fs::write(
9720            dir.path().join("daemon.json"),
9721            serde_json::json!({
9722                "schema": 1,
9723                "pid": 4242,
9724                "updated_at": Timestamp::now().to_string(),
9725                "idle": false,
9726                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9727                "completed": 3,
9728                "polls": 9,
9729            })
9730            .to_string(),
9731        )
9732        .unwrap();
9733
9734        let reading = read_status(dir.path()).expect("an older shape must still parse");
9735        assert!(reading.running(Timestamp::now()));
9736        assert_eq!(
9737            reading.current,
9738            vec![Current {
9739                worker: None,
9740                task: "20260902-140501-aaaa".to_owned(),
9741                run: "20260902-140502-bbbb".to_owned(),
9742            }]
9743        );
9744    }
9745
9746    #[test]
9747    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9748        let dir = tempfile::tempdir().unwrap();
9749        std::fs::write(
9750            dir.path().join("daemon.json"),
9751            serde_json::json!({
9752                "schema": 1,
9753                "updated_at": Timestamp::now().to_string(),
9754                "idle": true,
9755                "current": null,
9756            })
9757            .to_string(),
9758        )
9759        .unwrap();
9760        let with_null = read_status(dir.path()).expect("null must still parse");
9761        assert!(with_null.current.is_empty());
9762
9763        std::fs::write(
9764            dir.path().join("daemon.json"),
9765            serde_json::json!({
9766                "schema": 1,
9767                "updated_at": Timestamp::now().to_string(),
9768                "idle": true,
9769            })
9770            .to_string(),
9771        )
9772        .unwrap();
9773        let absent = read_status(dir.path()).expect("a missing field must still parse");
9774        assert!(absent.current.is_empty());
9775    }
9776
9777    #[test]
9778    fn a_task_without_a_repository_runs_in_the_daemons_default() {
9779        let fallback = Path::new("/default");
9780        let mut blank = task();
9781        blank.repo = PathBuf::new();
9782        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9783        let mut dot = task();
9784        dot.repo = PathBuf::from(".");
9785        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9786        assert_eq!(
9787            repo_for(&task(), fallback),
9788            PathBuf::from("/repo"),
9789            "a task that names a repository keeps it"
9790        );
9791    }
9792
9793    #[test]
9794    fn task_implementers_edit_inherits_daemon_config_and_merge() {
9795        let dir = tempfile::tempdir().unwrap();
9796        let path = dir.path().join("explicit.toml");
9797        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9798        let opts = Opts {
9799            config: Some(path),
9800            merge: Some("none".into()),
9801            ..Default::default()
9802        };
9803        let mut t = task();
9804        t.set_implementers(
9805            2,
9806            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9807                .unwrap(),
9808        )
9809        .unwrap();
9810        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9811        assert_eq!(cfg.graph.implementers, 2);
9812        assert_eq!(cfg.graph.judges, 1);
9813        assert_eq!(cfg.merge.mode, MergeMode::None);
9814        t.set_implementers(1, &cfg).unwrap();
9815        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9816        apply_task_implementers(&mut cfg, &t);
9817        assert_eq!(cfg.graph.implementers, 1);
9818        assert_eq!(cfg.graph.judges, 1);
9819        assert_eq!(cfg.merge.mode, MergeMode::None);
9820    }
9821
9822    #[test]
9823    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9824        let dir = tempfile::tempdir().unwrap();
9825        let repo = dir.path().join("repo");
9826        std::fs::create_dir(&repo).unwrap();
9827        std::fs::write(
9828            repo.join("magi.toml"),
9829            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
9830        )
9831        .unwrap();
9832        let daemon_config = dir.path().join("daemon.toml");
9833        std::fs::write(
9834            &daemon_config,
9835            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
9836        )
9837        .unwrap();
9838        let opts = Opts {
9839            config: Some(daemon_config),
9840            merge: Some("pr".into()),
9841            ..Default::default()
9842        };
9843        let q = Queue::at(dir.path().join("queue"));
9844        let validation: Config =
9845            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9846                .unwrap();
9847        // No provenance field on legacy direct tasks: both shapes stay isolated.
9848        for record in ["{}", r#"{"candidates":2}"#] {
9849            let overrides = serde_json::from_str(record).unwrap();
9850            let filing = crate::direct::Filing {
9851                instruction: "work".into(),
9852                title: "direct".into(),
9853                repo: repo.clone(),
9854                source: crate::queue::Source::Human,
9855                solo: false,
9856                overrides,
9857                review_of: None,
9858                sources: Default::default(),
9859            };
9860            let filed =
9861                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
9862            let crate::direct::Filed::Standalone {
9863                mut task,
9864                claim: _claim,
9865            } = filed
9866            else {
9867                panic!("local filing")
9868            };
9869            let before = prepare_for(&repo, &opts, &task).unwrap();
9870            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
9871            assert_eq!(
9872                before.merge.mode,
9873                MergeMode::None,
9874                "daemon --merge must not leak"
9875            );
9876            for n in [2, 1, 2] {
9877                task.set_implementers(n, &validation).unwrap();
9878                q.put(&mut task).unwrap();
9879                task = q.get(&task.id).unwrap();
9880                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
9881                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
9882                apply_task_implementers(&mut cfg, &task);
9883                assert_eq!(cfg.graph.implementers, usize::from(n));
9884                assert_eq!(cfg.graph.judges, 2);
9885                assert_eq!(cfg.merge.mode, MergeMode::None);
9886            }
9887        }
9888    }
9889
9890    #[test]
9891    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
9892        let cfg: Config =
9893            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9894                .unwrap();
9895        let mut t = task();
9896        t.review_of = Some("review-target".into());
9897        t.hold_manual(Some("retry".into()));
9898        let mut previous = RunState::new(
9899            PathBuf::from("/repo"),
9900            "main".into(),
9901            "abc1234".into(),
9902            "review".into(),
9903            cfg.clone(),
9904        );
9905        previous.config.graph.implementers = 2;
9906        for count in [1, 3] {
9907            t.set_implementers(count, &cfg).unwrap();
9908            t.release();
9909            assert_eq!(t.review_of.as_deref(), Some("review-target"));
9910            for proposed in [
9911                Starter::Resume(previous.id.clone()),
9912                Starter::Review("recovery-target".into()),
9913            ] {
9914                assert_eq!(
9915                    starter_with_implementers(&t, Some(&previous), proposed),
9916                    Starter::Review("review-target".into())
9917                );
9918            }
9919            let mut configured = cfg.clone();
9920            apply_task_implementers(&mut configured, &t);
9921            assert_eq!(configured.graph.implementers, usize::from(count));
9922            assert_eq!(previous.config.graph.implementers, 2);
9923        }
9924    }
9925
9926    #[test]
9927    fn task_implementers_dispatch_and_resume_agree() {
9928        let mut t = task();
9929        let cfg: crate::config::Config =
9930            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9931                .unwrap();
9932        let mut run = RunState::new(
9933            PathBuf::from("/repo"),
9934            "main".into(),
9935            "abc1234".into(),
9936            "work".into(),
9937            cfg.clone(),
9938        );
9939        run.config.graph.implementers = 2;
9940        for n in [2, 1, 3, 2] {
9941            t.set_implementers(n, &cfg).unwrap();
9942            let mut dispatched = cfg.clone();
9943            apply_task_implementers(&mut dispatched, &t);
9944            assert_eq!(dispatched.graph.implementers, usize::from(n));
9945            assert_eq!(implementers_match(&t, &run), n == 2);
9946            for proposed in [
9947                Starter::Resume(run.id.clone()),
9948                Starter::Review("old-branch".into()),
9949            ] {
9950                let expected = if n == 2 {
9951                    proposed.clone()
9952                } else {
9953                    Starter::Start
9954                };
9955                assert_eq!(
9956                    starter_with_implementers(&t, Some(&run), proposed),
9957                    expected
9958                );
9959            }
9960            assert_eq!(
9961                run.config.graph.implementers, 2,
9962                "history must not be rewritten"
9963            );
9964        }
9965        t.solo = false;
9966        t.overrides = None;
9967        assert!(implementers_match(&t, &run));
9968    }
9969
9970    #[test]
9971    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
9972        // Three seats said out loud. What `solo` promises is one candidate
9973        // *whatever the config asks for*, so the contrast has to be a number
9974        // this test owns - it used to be `Config::default()`'s, which became
9975        // 1 when one implementation became the default and left the two
9976        // halves of this test asserting the same thing.
9977        let mut solo_cfg = Config::default();
9978        solo_cfg.graph.implementers = 3;
9979        let mut solo_task = task();
9980        solo_task.solo = true;
9981        apply_task_implementers(&mut solo_cfg, &solo_task);
9982        assert_eq!(solo_cfg.graph.implementers, 1);
9983
9984        let mut plain_cfg = Config::default();
9985        plain_cfg.graph.implementers = 3;
9986        let plain_task = task();
9987        assert!(!plain_task.solo);
9988        apply_task_implementers(&mut plain_cfg, &plain_task);
9989        assert_eq!(
9990            plain_cfg.graph.implementers, 3,
9991            "a task that did not ask to run alone keeps the config's candidates"
9992        );
9993    }
9994
9995    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
9996        QuotaLoss {
9997            cause: crate::agent::QuotaCause::UsageLimit,
9998            agent: String::new(),
9999            seat: seat.into(),
10000            node: "judge".into(),
10001            at: at.parse().unwrap(),
10002            reset: reset.map(str::to_string),
10003        }
10004    }
10005
10006    #[test]
10007    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
10008        let now = Timestamp::now();
10009        for reset in [None, Some("in 1h")] {
10010            let auth = crate::agent::Quota {
10011                cause: crate::agent::QuotaCause::Authentication,
10012                agent: "alpha".into(),
10013                reset: reset.map(str::to_owned),
10014            };
10015            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
10016            assert_eq!(cooldown_until(&[loss], now), None);
10017        }
10018    }
10019
10020    #[test]
10021    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
10022        let old: Vec<QuotaLoss> = (1..=4)
10023            .map(|i| {
10024                loss(
10025                    &format!("judge-{i}"),
10026                    "2026-09-23T05:23:00Z",
10027                    Some("2:40pm (Asia/Tokyo)"),
10028                )
10029            })
10030            .collect();
10031        let fresh = losses_this_attempt(&old, &old);
10032        assert!(fresh.is_empty());
10033        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
10034        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
10035    }
10036
10037    #[test]
10038    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
10039        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
10040        let now = Timestamp::now();
10041        let mut after = old.clone();
10042        after.push(loss("judge-2", &now.to_string(), None));
10043        let fresh = losses_this_attempt(&old, &after);
10044        assert_eq!(fresh, vec![after[1].clone()]);
10045        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
10046        assert_eq!(
10047            until,
10048            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
10049        );
10050    }
10051
10052    #[test]
10053    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
10054        // `recover_stall` removes judge-1's loss and the retry then hits quota
10055        // again: the vector is the same length, so an index diff sees nothing.
10056        let before = vec![
10057            loss("judge-1", "2026-09-23T05:23:00Z", None),
10058            loss("judge-2", "2026-09-23T05:24:00Z", None),
10059        ];
10060        let after = vec![
10061            loss("judge-2", "2026-09-23T05:24:00Z", None),
10062            loss("judge-1", "2026-09-24T01:00:00Z", None),
10063        ];
10064        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
10065    }
10066
10067    #[test]
10068    fn merge_overrides_are_parsed_or_refused() {
10069        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
10070        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
10071        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
10072        assert!(merge_mode("squash").is_err());
10073    }
10074
10075    #[test]
10076    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
10077        let now = Timestamp::now();
10078        let fallback = Duration::from_secs(300);
10079        let cap = Duration::from_secs(1800);
10080
10081        // No reset hint at all: the fallback.
10082        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
10083
10084        // A reset ten minutes out, well inside the cap: waited for exactly.
10085        let soon = now + jiff::SignedDuration::from_secs(600);
10086        assert_eq!(
10087            quota_wait(Some(soon), now, fallback, cap),
10088            Duration::from_secs(600)
10089        );
10090
10091        // A reset already in the past is not trusted: the fallback, not a
10092        // zero or negative wait that would spin the loop right back around.
10093        let past = now - jiff::SignedDuration::from_secs(60);
10094        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
10095
10096        // A reset further out than the cap is trusted for direction but not
10097        // for magnitude: a parsing slip must not sleep the loop for a day.
10098        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
10099        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
10100    }
10101
10102    #[test]
10103    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
10104        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10105
10106        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
10107        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
10108
10109        // Same clock reading, but it has already gone by today: read as
10110        // tomorrow's, since the CLI would not still be reporting a limit past
10111        // its own stated reset.
10112        let already_past =
10113            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
10114        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
10115
10116        assert!(
10117            parse_reset_hint("session limit reached", now, now).is_none(),
10118            "free text with no recognised shape is not guessed at"
10119        );
10120        assert!(
10121            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
10122            "an unresolvable zone name is not guessed at either"
10123        );
10124    }
10125
10126    #[test]
10127    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
10128        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10129
10130        let at = parse_reset_hint(
10131            "You've hit your usage limit. Visit \
10132             https://chatgpt.com/codex/settings/usage to purchase more \
10133             credits or try again at Sep 19th, 2026 5:10 PM.",
10134            now,
10135            now,
10136        )
10137        .expect("the codex reset wording is a recognised shape");
10138        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
10139
10140        // The month is explicit, so a date already earlier in the same
10141        // sentence-implied year than `now` is trusted as written rather than
10142        // rolled forward a year the way the bracketed shape rolls a
10143        // same-day clock reading to tomorrow.
10144        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
10145            .expect("an explicit year needs no rollover");
10146        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
10147
10148        assert!(
10149            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
10150            "a two-digit year is not the documented shape and is not guessed at"
10151        );
10152        assert!(
10153            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
10154            "a four-letter month name is not the documented three-letter abbreviation"
10155        );
10156        assert!(
10157            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10158            "an explicit zone on the dated shape is a format nobody has \
10159             documented, and is refused rather than guessed at as UTC"
10160        );
10161    }
10162
10163    #[test]
10164    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10165        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10166        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10167
10168        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10169        assert_eq!(at.as_second() - recorded.as_second(), 3769);
10170
10171        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10172        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10173
10174        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10175            assert!(
10176                parse_reset_hint(bad, now, recorded).is_none(),
10177                "{bad:?} must not be guessed at"
10178            );
10179        }
10180    }
10181
10182    /// A loop whose queue lives in a temp tree and whose poll interval is far
10183    /// longer than the test's patience, so anything that waits out a poll
10184    /// instead of noticing the stop fails rather than merely being slow.
10185    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10186        let config = dir.join("magi.toml");
10187        std::fs::write(
10188            &config,
10189            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10190        )
10191        .unwrap();
10192        let opts = Opts {
10193            poll: Duration::from_secs(30),
10194            config: Some(config),
10195            // The explicit fixture config keeps startup cleanup from reading
10196            // machine configuration. This fictional repository likewise
10197            // keeps any best-effort git cleanup away from this checkout.
10198            repo: dir.join("repo"),
10199            ..Opts::default()
10200        };
10201        // The status file goes in a directory that does not exist yet, so its
10202        // creation is itself evidence the loop published one. `worktrees`
10203        // must be just as fictional: the janitor reclaims worktrees under it
10204        // for real, and a test that let it fall through to
10205        // `crate::run::default_worktree_root()` would have it reclaim
10206        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
10207        // which is exactly what happened before this function took the
10208        // parameter at all.
10209        let home = dir.join("home");
10210        // These control-only fixtures do not launch native workers. Give the
10211        // independently tested maintenance services a fresh cadence receipt.
10212        let stamps = home.join("service-ticks");
10213        std::fs::create_dir_all(&stamps).unwrap();
10214        for service in ["waiter", "deputies", "release-watch"] {
10215            std::fs::write(
10216                stamps.join(service),
10217                Timestamp::now().as_second().to_string(),
10218            )
10219            .unwrap();
10220        }
10221        for operation in [
10222            "conductor",
10223            "maintenance",
10224            "housekeeping",
10225            "disk-pressure",
10226            "cache",
10227            "fetch",
10228        ] {
10229            std::fs::write(
10230                stamps.join(format!("daemon-{operation}")),
10231                serde_json::to_vec(&Timestamp::now()).unwrap(),
10232            )
10233            .unwrap();
10234        }
10235        let worktrees = dir.join("wt");
10236        (
10237            opts,
10238            Queue::at(dir.join("queue")),
10239            home.join("daemon.json"),
10240            home,
10241            worktrees,
10242        )
10243    }
10244
10245    #[test]
10246    fn a_stop_is_idempotent_and_once_set_stays_set() {
10247        let stop = Stop::new();
10248        assert!(!stop.stopped());
10249
10250        stop.stop();
10251        assert!(stop.stopped());
10252        stop.stop();
10253        assert!(stop.stopped(), "a second stop is not a toggle");
10254
10255        let shared = stop.clone();
10256        assert!(
10257            shared.stopped(),
10258            "a clone is the same stop; that is how the loop and its caller share one"
10259        );
10260    }
10261
10262    #[tokio::test]
10263    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10264        for operation in ["conductor", "maintenance", "housekeeping"] {
10265            let dir = tempfile::tempdir().unwrap();
10266            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10267            opts.once = true;
10268            opts.poll = Duration::from_millis(1);
10269            let mut task = task();
10270            task.runs.push("fixture-run".into());
10271            queue.put(&mut task).unwrap();
10272            let claim = queue.claim(&task.id).unwrap();
10273
10274            // Model a live service holding the task's claim across the
10275            // scheduler's dispatch scan. No real subprocess or timed race.
10276            let directory = home.join("workers/jobs/abcdef");
10277            std::fs::create_dir_all(&directory).unwrap();
10278            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10279            crate::pr_head::try_lock_file(&lease).unwrap();
10280            let mut job = crate::worker::Job {
10281                id: "abcdef".into(),
10282                sequence: 1,
10283                kind: "daemon-service".into(),
10284                key: format!("service:daemon-{operation}"),
10285                payload: serde_json::Value::Null,
10286                generation: "fixture".into(),
10287                version: None,
10288                status: crate::worker::Status::Running,
10289                result: None,
10290                pid: Some(std::process::id()),
10291                created_at: Timestamp::now().as_second() as u64,
10292                finished_at: None,
10293            };
10294            let record = directory.join("job.json");
10295            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10296
10297            let status = Arc::new(Mutex::new(Status::new()));
10298            let stop = Stop::new();
10299            let mut drain = Box::pin(poll(
10300                &opts,
10301                &queue,
10302                &status,
10303                &home,
10304                &worktrees,
10305                &stop,
10306                DispatchLimits {
10307                    max_concurrent: 1,
10308                    pause_for_interrupts: false,
10309                    recovery_cfg: None,
10310                },
10311            ));
10312            std::future::poll_fn(|cx| {
10313                use std::future::Future;
10314                assert!(
10315                    drain.as_mut().poll(cx).is_pending(),
10316                    "--once must wait for {operation} to release its queue claim"
10317                );
10318                std::task::Poll::Ready(())
10319            })
10320            .await;
10321            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10322
10323            // An answer arrives while the service still owns the claim. A
10324            // fresh scheduling pass must apply it before declaring idle.
10325            let questions = Questions::at(home.join("questions"));
10326            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10327            questions.put(&mut q).unwrap();
10328            drop(claim);
10329            // Model services that took longer than their cadence, without a
10330            // wall-clock sleep. The final scans must not respawn them even
10331            // though their receipts now permit another periodic invocation.
10332            let expired =
10333                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10334            for service in [operation, "housekeeping"] {
10335                std::fs::write(
10336                    home.join("service-ticks").join(format!("daemon-{service}")),
10337                    &expired,
10338                )
10339                .unwrap();
10340            }
10341            job.status = crate::worker::Status::Finished;
10342            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10343            drop(lease);
10344            tokio::time::timeout(Duration::from_secs(2), drain)
10345                .await
10346                .expect("the settled service must allow the drain to finish")
10347                .unwrap();
10348            let after = queue.get(&task.id).unwrap();
10349            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10350            assert!(after.action_applied(&q.id));
10351            for service in [operation, "housekeeping"] {
10352                assert_eq!(
10353                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10354                        .unwrap(),
10355                    expired,
10356                    "the final once rescan must not restart {service}"
10357                );
10358            }
10359        }
10360    }
10361
10362    #[test]
10363    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10364        let stop = Stop::new();
10365        stop.busy.store(1, Ordering::SeqCst);
10366        assert!(
10367            !stop.finishing(),
10368            "a busy loop nobody has asked to stop is just running"
10369        );
10370
10371        stop.stop();
10372        assert!(
10373            stop.finishing(),
10374            "a stop asked for mid-run has not landed until the run is settled"
10375        );
10376
10377        stop.busy.store(0, Ordering::SeqCst);
10378        assert!(
10379            !stop.finishing(),
10380            "once the run is settled the stop has landed and there is nothing to finish"
10381        );
10382    }
10383
10384    #[test]
10385    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10386        let stop = Stop::new();
10387        stop.busy.store(2, Ordering::SeqCst);
10388        stop.stop();
10389        assert!(stop.finishing(), "two runs still in flight");
10390
10391        stop.busy.store(1, Ordering::SeqCst);
10392        assert!(
10393            stop.finishing(),
10394            "one run finished, but a sibling is still working"
10395        );
10396
10397        stop.busy.store(0, Ordering::SeqCst);
10398        assert!(
10399            !stop.finishing(),
10400            "the last run out is what actually lands the stop"
10401        );
10402    }
10403
10404    #[tokio::test]
10405    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10406        let dir = tempfile::tempdir().unwrap();
10407        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10408        let stop = Stop::new();
10409        stop.stop();
10410
10411        let began = std::time::Instant::now();
10412        tokio::time::timeout(
10413            Duration::from_secs(2),
10414            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10415        )
10416        .await
10417        .expect("a stopped loop must return, not sit out its poll interval")
10418        .expect("the loop's own setup and teardown must not fail");
10419        assert!(
10420            began.elapsed() < opts.poll,
10421            "returned only after {:?}, which is a poll interval, not a stop",
10422            began.elapsed()
10423        );
10424    }
10425
10426    #[tokio::test]
10427    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10428        let dir = tempfile::tempdir().unwrap();
10429        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10430        let stop = Stop::new();
10431
10432        // Asked for after the loop is already parked on its empty queue, which
10433        // is the case an operator tapping stop on a phone actually hits.
10434        let asker = {
10435            let stop = stop.clone();
10436            tokio::spawn(async move {
10437                tokio::time::sleep(Duration::from_millis(20)).await;
10438                stop.stop();
10439            })
10440        };
10441
10442        let began = std::time::Instant::now();
10443        tokio::time::timeout(
10444            Duration::from_secs(2),
10445            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10446        )
10447        .await
10448        .expect("a stop asked for while idle must wake the wait")
10449        .expect("the loop's own setup and teardown must not fail");
10450        asker.await.unwrap();
10451        assert!(
10452            began.elapsed() < opts.poll,
10453            "returned only after {:?}, so the stop waited on the sleep",
10454            began.elapsed()
10455        );
10456    }
10457
10458    #[tokio::test]
10459    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10460        let dir = tempfile::tempdir().unwrap();
10461        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10462        let stop = Stop::new();
10463        stop.stop();
10464
10465        tokio::time::timeout(
10466            Duration::from_secs(2),
10467            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10468        )
10469        .await
10470        .expect("a stopped loop must return")
10471        .expect("the loop's own setup and teardown must not fail");
10472
10473        assert!(
10474            home.is_dir(),
10475            "the loop did publish a status file, so its removal is the teardown and not an absence"
10476        );
10477        assert!(
10478            !status_file.exists(),
10479            "a stopped loop clears its status file"
10480        );
10481        assert!(
10482            read_status(&home).is_none(),
10483            "a reader must see no daemon at all, not a heartbeat that merely stopped"
10484        );
10485    }
10486
10487    #[tokio::test]
10488    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10489        let dir = tempfile::tempdir().unwrap();
10490        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10491
10492        let mut settled = RunState::new(
10493            dir.path().join("repo"),
10494            "main".to_owned(),
10495            "abc1234".to_owned(),
10496            "fixture".to_owned(),
10497            Config::default(),
10498        );
10499        settled.status = RunStatus::Ready;
10500        let run_dir = home.join("runs").join(&settled.id);
10501        std::fs::create_dir_all(&run_dir).unwrap();
10502        std::fs::write(
10503            run_dir.join("run.json"),
10504            serde_json::to_string_pretty(&settled).unwrap(),
10505        )
10506        .unwrap();
10507        let questions = Questions::at(home.join("questions"));
10508        let mut question = ask::Question::new(
10509            settled.id.clone(),
10510            "review".to_owned(),
10511            "reviewer-1".to_owned(),
10512            "Continue?".to_owned(),
10513            String::new(),
10514            Vec::new(),
10515        );
10516        questions.put(&mut question).unwrap();
10517
10518        run_service_worker(
10519            &home,
10520            serde_json::to_value(ServiceWorker {
10521                opts,
10522                queue: queue.root().to_path_buf(),
10523                worktrees_root: worktrees,
10524                operation: "housekeeping".to_owned(),
10525            })
10526            .unwrap(),
10527        )
10528        .await
10529        .unwrap();
10530
10531        assert_eq!(
10532            questions.get(&question.id).unwrap().status,
10533            ask::QuestionStatus::Abandoned,
10534            "the independent housekeeping worker settles ended-run questions"
10535        );
10536    }
10537
10538    #[test]
10539    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10540        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10541
10542        assert!(
10543            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10544            "never checked before: due at once"
10545        );
10546
10547        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10548        assert!(
10549            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10550            "well inside the interval: not due yet"
10551        );
10552
10553        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10554        assert!(
10555            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10556            "exactly at the edge: not yet due, same convention as `clean::due`"
10557        );
10558
10559        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10560        assert!(
10561            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10562            "past the interval: due again"
10563        );
10564    }
10565
10566    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
10567    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
10568    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
10569    /// and the congestion test below both need, and must not drift apart.
10570    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10571        let config = dir.join("magi.toml");
10572        // A literal (single-quoted) TOML string, not a basic one: the cache
10573        // path is a Windows path full of backslashes, and a basic string
10574        // would have TOML try to interpret `\U` (from `\Users\...`) as a
10575        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
10576        // `{{ vars.cache }}` rendering documents.
10577        std::fs::write(
10578            &config,
10579            format!(
10580                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10581                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10582                cache_dir.display()
10583            ),
10584        )
10585        .unwrap();
10586        Opts {
10587            config: Some(config),
10588            repo: dir.join("repo"),
10589            ..Opts::default()
10590        }
10591    }
10592
10593    #[tokio::test]
10594    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10595        let dir = tempfile::tempdir().unwrap();
10596        let home = dir.path().join("home");
10597        let cache_dir = dir.path().join("cache");
10598        std::fs::create_dir_all(&cache_dir).unwrap();
10599        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10600        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10601
10602        // Nobody has asked this daemon to stop, which is the ordinary case;
10603        // the skip that a stop buys is asserted by its own test below.
10604        let running = Stop::new();
10605        let mut last_checked = None;
10606        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10607        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10608            .await;
10609        assert_eq!(
10610            crate::disk::dir_size(&cache_dir),
10611            0,
10612            "over the cap on the first check ever: pruned at once, no idle queue required"
10613        );
10614        assert_eq!(last_checked, Some(t0));
10615
10616        // A fresh oversized file lands, but the next check is not due yet.
10617        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10618        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10619        maybe_prune_cache_between_runs(
10620            &opts.repo,
10621            &opts,
10622            &home,
10623            &running,
10624            &mut last_checked,
10625            too_soon,
10626        )
10627        .await;
10628        assert_eq!(
10629            crate::disk::dir_size(&cache_dir),
10630            10,
10631            "too soon since the last check: left alone rather than rescanned every call"
10632        );
10633        assert_eq!(
10634            last_checked,
10635            Some(t0),
10636            "an idle check does not reset the clock"
10637        );
10638
10639        // Once the interval elapses, the same oversized cache is caught again.
10640        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10641        maybe_prune_cache_between_runs(
10642            &opts.repo,
10643            &opts,
10644            &home,
10645            &running,
10646            &mut last_checked,
10647            due_again,
10648        )
10649        .await;
10650        assert_eq!(
10651            crate::disk::dir_size(&cache_dir),
10652            0,
10653            "due again: pruned back under the cap"
10654        );
10655    }
10656
10657    /// A stop must not queue behind housekeeping. The prune below is a
10658    /// synchronous walk of the whole cache with no await point in it, so a
10659    /// loop that entered it could not get back to its own `stopped()` test
10660    /// until the walk finished - and because no run is in flight at this
10661    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
10662    /// the stop had already landed. The idle branch has always made this same
10663    /// check before reaching `janitor`; the between-runs path makes it too.
10664    #[tokio::test]
10665    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10666        let dir = tempfile::tempdir().unwrap();
10667        let home = dir.path().join("home");
10668        let cache_dir = dir.path().join("cache");
10669        std::fs::create_dir_all(&cache_dir).unwrap();
10670        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10671        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10672
10673        let stop = Stop::new();
10674        stop.stop();
10675        assert!(
10676            !stop.finishing(),
10677            "no run is in flight at a between-runs boundary, so nothing else \
10678             would tell the operator this stop had not taken effect yet"
10679        );
10680
10681        let mut last_checked = None;
10682        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10683        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10684            .await;
10685        assert_eq!(
10686            crate::disk::dir_size(&cache_dir),
10687            10,
10688            "over its cap, and due for the first check ever, but a stop outranks \
10689             it: the cap is a standing policy the next start measures again"
10690        );
10691        assert_eq!(
10692            last_checked, None,
10693            "a check that never happened must not claim the interval"
10694        );
10695    }
10696
10697    /// A backlog must not starve cache pruning. The finite cache worker runs
10698    /// independently of queue drain and must not consume any task attempts.
10699    #[tokio::test]
10700    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10701        let dir = tempfile::tempdir().unwrap();
10702        let cache_dir = dir.path().join("cache");
10703        std::fs::create_dir_all(&cache_dir).unwrap();
10704        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10705
10706        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10707        opts.poll = Duration::from_millis(20);
10708        opts.max_attempts = 1_000;
10709
10710        let queue = Queue::at(dir.path().join("queue"));
10711        for i in 0..128 {
10712            let mut task = Task::new(
10713                format!("queued work {i}"),
10714                format!("queued work {i}"),
10715                opts.repo.clone(),
10716                Source::Human,
10717            );
10718            queue.put(&mut task).unwrap();
10719        }
10720
10721        let home = dir.path().join("home");
10722        let worktrees = dir.path().join("wt");
10723        run_service_worker(
10724            &home,
10725            serde_json::to_value(ServiceWorker {
10726                opts,
10727                queue: queue.root().to_path_buf(),
10728                worktrees_root: worktrees,
10729                operation: "cache".to_owned(),
10730            })
10731            .unwrap(),
10732        )
10733        .await
10734        .unwrap();
10735        let after = queue.list();
10736        assert_eq!(after.len(), 128);
10737        assert!(
10738            after
10739                .iter()
10740                .all(|task| task.status.runnable() && task.attempts == 0)
10741        );
10742
10743        assert_eq!(
10744            crate::disk::dir_size(&cache_dir),
10745            0,
10746            "an oversized cache must not be left to grow unboundedly just because the \
10747             queue kept the loop busy the whole time"
10748        );
10749    }
10750
10751    #[test]
10752    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10753        let dir = tempfile::tempdir().unwrap();
10754        let queue = Queue::at(dir.path().join("queue"));
10755        let questions = Questions::at(dir.path().join("questions"));
10756        let mut task = task();
10757        queue.put(&mut task).unwrap();
10758
10759        let mut task_question = ask::Question::new(
10760            task.id.clone(),
10761            crate::conduct::NODE.to_owned(),
10762            "conduct".to_owned(),
10763            "Which backend?".to_owned(),
10764            String::new(),
10765            Vec::new(),
10766        );
10767        questions.put(&mut task_question).unwrap();
10768        task.block(vec![task_question.id.clone()], None);
10769        queue.put(&mut task).unwrap();
10770
10771        let mut run_question = ask::Question::new(
10772            "20260101-000000-run1".to_owned(),
10773            "review".to_owned(),
10774            "reviewer-1".to_owned(),
10775            "Run question".to_owned(),
10776            String::new(),
10777            Vec::new(),
10778        );
10779        questions.put(&mut run_question).unwrap();
10780
10781        // A question from another node whose `run` happens to equal this
10782        // task's id — the same field, filled in for an unrelated reason. Only
10783        // `crate::conduct::NODE` questions use `run` as a task id; this one
10784        // must never be touched by this reconciliation, even after release.
10785        let mut coincidental = ask::Question::new(
10786            task.id.clone(),
10787            "review".to_owned(),
10788            "reviewer-1".to_owned(),
10789            "Unrelated review question".to_owned(),
10790            String::new(),
10791            Vec::new(),
10792        );
10793        questions.put(&mut coincidental).unwrap();
10794
10795        reconcile_task_questions(&queue, &questions);
10796        assert!(questions.get(&task_question.id).unwrap().status.open());
10797        assert!(questions.get(&run_question.id).unwrap().status.open());
10798        assert!(questions.get(&coincidental.id).unwrap().status.open());
10799
10800        task.release();
10801        queue.put(&mut task).unwrap();
10802        reconcile_task_questions(&queue, &questions);
10803        assert_eq!(
10804            questions.get(&task_question.id).unwrap().status,
10805            ask::QuestionStatus::Abandoned
10806        );
10807        assert!(
10808            questions.get(&run_question.id).unwrap().status.open(),
10809            "run questions remain the run janitor's responsibility"
10810        );
10811        assert!(
10812            questions.get(&coincidental.id).unwrap().status.open(),
10813            "a non-conductor question must not be abandoned just because its \
10814             run id coincides with a task id"
10815        );
10816    }
10817
10818    #[test]
10819    fn a_freshly_started_running_task_is_never_stalled() {
10820        let dir = tempfile::tempdir().unwrap();
10821        let mut t = task();
10822        t.start("run-1".to_owned());
10823        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
10824        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
10825        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10826    }
10827
10828    #[test]
10829    fn a_long_running_task_with_no_live_daemon_is_stalled() {
10830        let dir = tempfile::tempdir().unwrap();
10831        let mut t = task();
10832        t.start("run-1".to_owned());
10833        t.updated_at = Timestamp::now()
10834            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10835        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
10836        assert_eq!(
10837            stalled_tasks(
10838                &Queue::at(dir.path().join("q")),
10839                dir.path(),
10840                Timestamp::now()
10841            )
10842            .len(),
10843            0,
10844            "the task was never written to this queue"
10845        );
10846    }
10847
10848    #[test]
10849    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
10850        let dir = tempfile::tempdir().unwrap();
10851        let mut t = task();
10852        t.id = "20260903-080340-0167".to_owned();
10853        t.start("20260903-080619-01c2".to_owned());
10854        t.updated_at = Timestamp::now()
10855            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10856
10857        let mut status = Status::new();
10858        status.current = vec![Current {
10859            worker: None,
10860            task: t.id.clone(),
10861            run: "20260903-080619-01c2".to_owned(),
10862        }];
10863        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10864
10865        assert!(
10866            !is_stalled(&t, dir.path(), Timestamp::now()),
10867            "a live daemon's own heartbeat rules out stalled, however long the task has run"
10868        );
10869    }
10870
10871    /// Rewrite a task's `updated_at` on disk directly, bypassing
10872    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
10873    /// a fixture look like it has genuinely been `running` for a while.
10874    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
10875        let path = queue.path_of(id);
10876        let body = std::fs::read_to_string(&path).unwrap();
10877        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
10878        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
10879        v["updated_at"] = serde_json::Value::String(old.to_string());
10880        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
10881    }
10882
10883    #[test]
10884    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
10885        // The realistic `poll()` ordering, not `is_stalled` in isolation:
10886        // `reclaim_orphaned_running` runs first, on every poll, and settles
10887        // any `running` task whose claim it can actually take. For most
10888        // crashes that is immediate - a dead pid is proof enough for
10889        // `sweep_stale_claims` to drop the lock the same tick, and the very
10890        // next claim attempt succeeds. But a lock whose pid cannot be parsed
10891        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
10892        // `sweep_stale_claims`'s own doc), so the lock - and the claim
10893        // failure behind it - can legitimately outlive many polls. This is
10894        // exactly the gap `stalled_tasks` exists to surface well before that
10895        // six-hour sweep would: reclaim leaves the task `running`, and it
10896        // must still reach the conductor as stalled.
10897        let dir = tempfile::tempdir().unwrap();
10898        let queue = Queue::at(dir.path().join("queue"));
10899        let home = dir.path().join("home");
10900
10901        let mut t = task();
10902        t.id = "20260101-000001-lock".to_owned();
10903        t.start("run-1".to_owned());
10904        queue.put(&mut t).unwrap();
10905        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10906        std::fs::write(
10907            dir.path().join("queue").join(format!("{}.lock", t.id)),
10908            "not a pid",
10909        )
10910        .unwrap();
10911
10912        let now = Timestamp::now();
10913        assert!(
10914            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
10915            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
10916             and reclaim must leave the task alone"
10917        );
10918        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10919
10920        let stalled = stalled_tasks(&queue, &home, now);
10921        assert_eq!(
10922            stalled.len(),
10923            1,
10924            "reclaim's inability to claim it yet must not hide it from the conductor"
10925        );
10926        assert_eq!(stalled[0].id, t.id);
10927    }
10928
10929    #[test]
10930    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
10931        let dir = tempfile::tempdir().unwrap();
10932        crate::run::set_home(dir.path().join("run-home"));
10933        let queue = Queue::at(dir.path().join("queue"));
10934        let home = dir.path().join("home");
10935        let questions = Questions::at(dir.path().join("questions"));
10936
10937        let mut t = task();
10938        t.id = "20260101-000003-dead".to_owned();
10939        t.start("missing-run".to_owned());
10940        queue.put(&mut t).unwrap();
10941        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10942
10943        // This is the real poll ordering: retain the deterministic stalled
10944        // input before a claim proves the owner is gone and reclaims it.
10945        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10946        assert_eq!(
10947            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
10948            [&t.id]
10949        );
10950        assert_eq!(
10951            reclaim_orphaned_running(&queue, 2, &Default::default()),
10952            [t.id.clone()]
10953        );
10954        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10955
10956        // Reclaim drops its guard before conductor decisions are applied, so
10957        // the decision for the captured stalled input has a real write path.
10958        crate::conduct::apply(
10959            &queue,
10960            &questions,
10961            &crate::conduct::Verdict {
10962                decisions: vec![crate::conduct::Decision {
10963                    id: t.id.clone(),
10964                    recovery: Some(crate::conduct::Recovery::Requeue),
10965                    ..crate::conduct::Decision::default()
10966                }],
10967            },
10968        )
10969        .unwrap();
10970        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10971    }
10972
10973    #[test]
10974    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
10975        let dir = tempfile::tempdir().unwrap();
10976        let queue = Queue::at(dir.path().join("queue"));
10977        let home = dir.path().join("home");
10978
10979        let mut fresh = task();
10980        fresh.id = "20260101-000001-aaaa".to_owned();
10981        fresh.start("run-1".to_owned());
10982        queue.put(&mut fresh).unwrap();
10983
10984        let mut old = task();
10985        old.id = "20260101-000002-bbbb".to_owned();
10986        old.start("run-2".to_owned());
10987        queue.put(&mut old).unwrap();
10988        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
10989
10990        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10991        assert_eq!(stalled.len(), 1);
10992        assert_eq!(stalled[0].id, old.id);
10993    }
10994
10995    #[test]
10996    fn queued_and_finished_task_views_partition_by_status() {
10997        let dir = tempfile::tempdir().unwrap();
10998        let queue = Queue::at(dir.path().join("queue"));
10999
11000        let mut queued = task();
11001        queued.id = "20260101-000001-aaaa".to_owned();
11002        queue.put(&mut queued).unwrap();
11003
11004        let mut failed = task();
11005        failed.id = "20260101-000002-bbbb".to_owned();
11006        failed.start("run-1".to_owned());
11007        failed.fail("gate red", 5);
11008        queue.put(&mut failed).unwrap();
11009
11010        let mut held = task();
11011        held.id = "20260101-000003-cccc".to_owned();
11012        held.hold_machine(None);
11013        queue.put(&mut held).unwrap();
11014
11015        let mut running = task();
11016        running.id = "20260101-000004-dddd".to_owned();
11017        running.start("run-2".to_owned());
11018        queue.put(&mut running).unwrap();
11019
11020        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
11021        assert_eq!(queued_ids, [queued.id.clone()]);
11022
11023        let mut finished_ids: Vec<String> =
11024            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
11025        finished_ids.sort_unstable();
11026        let mut want = vec![failed.id.clone(), held.id.clone()];
11027        want.sort_unstable();
11028        assert_eq!(finished_ids, want);
11029    }
11030
11031    #[test]
11032    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
11033        for short in [false, true] {
11034            let dir = tempfile::tempdir().unwrap();
11035            let queue = Queue::at(dir.path().join("queue"));
11036            let questions = ask::Questions::at(dir.path().join("questions"));
11037            let mut running = task();
11038            running.id = "20261013-192213-feb2".into();
11039            running.start("existing-run".into());
11040            queue.put(&mut running).unwrap();
11041            let mut middle = task();
11042            middle.id = "20261013-193611-ca5b".into();
11043            middle.block(
11044                vec![if short {
11045                    "feb2".into()
11046                } else {
11047                    running.id.clone()
11048                }],
11049                None,
11050            );
11051            queue.put(&mut middle).unwrap();
11052            let mut waiting = task();
11053            waiting.id = "20261013-202849-ee37".into();
11054            waiting.block(
11055                vec![if short {
11056                    "ca5b".into()
11057                } else {
11058                    middle.id.clone()
11059                }],
11060                Some("wait for implementation".into()),
11061            );
11062            queue.put(&mut waiting).unwrap();
11063            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
11064            let inv = crate::blockers::Inventory::load(&queue, &questions);
11065            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
11066            assert!(inv.stuck().is_empty());
11067            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11068            assert!(report.quarantined.is_empty());
11069            assert!(report.asked.is_empty());
11070            resolve_blockers(&queue, &questions);
11071            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11072            assert!(questions.list().is_empty());
11073            // Finishing the transitive prerequisite alone does not satisfy
11074            // the task's direct dependency.
11075            running.succeed();
11076            queue.put(&mut running).unwrap();
11077            resolve_blockers(&queue, &questions);
11078            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
11079            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11080            middle = queue.get(&middle.id).unwrap();
11081            middle.succeed();
11082            queue.put(&mut middle).unwrap();
11083            resolve_blockers(&queue, &questions);
11084            let after = queue.get(&waiting.id).unwrap();
11085            assert_eq!(after.status, TaskStatus::Queued);
11086            assert!(after.blocked_by.is_empty());
11087            assert_eq!(after.instruction, waiting.instruction);
11088        }
11089    }
11090
11091    #[test]
11092    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
11093        for future_schema in [false, true] {
11094            let name = "20261013-193611-ca5b";
11095            let mut future = task();
11096            future.id = name.into();
11097            future.schema = crate::queue::SCHEMA + 1;
11098            let contents = if future_schema {
11099                serde_json::to_string(&future).unwrap()
11100            } else {
11101                "corrupt".into()
11102            };
11103            let dir = tempfile::tempdir().unwrap();
11104            let queue = Queue::at(dir.path().join("queue"));
11105            let questions = ask::Questions::at(dir.path().join("questions"));
11106            let mut waiting = task();
11107            waiting.id = "20261013-202849-ee37".into();
11108            waiting.block(vec!["ca5b".into()], None);
11109            queue.put(&mut waiting).unwrap();
11110            std::fs::write(queue.path_of(name), contents).unwrap();
11111            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
11112            assert!(
11113                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
11114            );
11115            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11116            assert!(report.asked.is_empty());
11117            resolve_blockers(&queue, &questions);
11118            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11119            assert!(questions.list().is_empty());
11120        }
11121        let dir = tempfile::tempdir().unwrap();
11122        let queue = Queue::at(dir.path().join("queue"));
11123        let questions = ask::Questions::at(dir.path().join("questions"));
11124        let mut waiting = task();
11125        waiting.id = "20261013-202849-ee37".into();
11126        waiting.block(vec!["ca5b".into()], None);
11127        queue.put(&mut waiting).unwrap();
11128        let mut done = task();
11129        done.id = "20261013-193611-ca5b".into();
11130        done.succeed();
11131        queue.put(&mut done).unwrap();
11132        // An unreadable second match must not disappear from uniqueness
11133        // checks just because Queue::list skips it.
11134        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
11135        assert!(queue.get("ca5b").is_err());
11136        assert_eq!(
11137            crate::queue::dependency(&queue, &questions, "ca5b"),
11138            crate::queue::Dependency::Ambiguous
11139        );
11140        resolve_blockers(&queue, &questions);
11141        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11142        assert!(report.asked.is_empty());
11143        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11144        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
11145    }
11146
11147    #[test]
11148    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
11149        for held in [false, true] {
11150            for question in [false, true] {
11151                for reference in ["ca5b", "20261013-193611-ca5b"] {
11152                    let dir = tempfile::tempdir().unwrap();
11153                    let queue = Queue::at(dir.path().join("queue"));
11154                    let questions = ask::Questions::at(dir.path().join("questions"));
11155                    let mut prerequisite = task();
11156                    prerequisite.id = "20261013-193611-ca5b".into();
11157                    prerequisite.start("existing-run".into());
11158                    queue.put(&mut prerequisite).unwrap();
11159                    let mut waiting = task();
11160                    waiting.id = "20261013-202849-ee37".into();
11161                    if held {
11162                        waiting.hold_machine(Some("waiting for separate consent".into()));
11163                    }
11164                    queue.put(&mut waiting).unwrap();
11165                    let reason = "Deleting saved data requires separate owner consent";
11166                    crate::conduct::apply(
11167                        &queue,
11168                        &questions,
11169                        &crate::conduct::Verdict {
11170                            decisions: vec![crate::conduct::Decision {
11171                                id: waiting.id.clone(),
11172                                blocked_by: vec![reference.into()],
11173                                question: question.then(|| "May the saved data be deleted?".into()),
11174                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11175                                reason: Some(reason.into()),
11176                                ..crate::conduct::Decision::default()
11177                            }],
11178                        },
11179                    )
11180                    .unwrap();
11181                    let before = queue.get(&waiting.id).unwrap();
11182                    if question {
11183                        assert_eq!(before.status, TaskStatus::Blocked);
11184                        let q = questions.get(&before.blocked_by[0]).unwrap();
11185                        assert_eq!(q.summary, "May the saved data be deleted?");
11186                        assert!(q.status.open());
11187                    } else {
11188                        assert_eq!(before.status, TaskStatus::Held);
11189                        let recorded_reason = before.hold_reason.as_deref().unwrap();
11190                        assert!(recorded_reason.starts_with(reason));
11191                        if held {
11192                            assert!(recorded_reason.contains("waiting for separate consent"));
11193                        }
11194                    }
11195                    prerequisite.succeed();
11196                    queue.put(&mut prerequisite).unwrap();
11197                    resolve_blockers(&queue, &questions);
11198                    let after = queue.get(&waiting.id).unwrap();
11199                    assert_eq!(after.status, before.status);
11200                    assert_eq!(after.blocked_by, before.blocked_by);
11201                    assert_eq!(after.hold_reason, before.hold_reason);
11202                    assert_eq!(after.instruction, waiting.instruction);
11203                    if question {
11204                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11205                    }
11206                    assert!(
11207                        queue.next_runnable().is_none(),
11208                        "dependency completion is not consent"
11209                    );
11210                }
11211            }
11212        }
11213    }
11214
11215    #[test]
11216    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11217        let dir = tempfile::tempdir().unwrap();
11218        let queue = Queue::at(dir.path().join("queue"));
11219        let questions = ask::Questions::at(dir.path().join("questions"));
11220
11221        let mut dep = task();
11222        dep.id = "20260101-000001-dep0".to_owned();
11223        dep.succeed();
11224        queue.put(&mut dep).unwrap();
11225
11226        let mut still_going = task();
11227        still_going.id = "20260101-000002-dep1".to_owned();
11228        queue.put(&mut still_going).unwrap();
11229
11230        let mut blocked = task();
11231        blocked.id = "20260101-000003-main".to_owned();
11232        blocked.block(
11233            vec![dep.id.clone(), still_going.id.clone()],
11234            Some("waits on both".to_owned()),
11235        );
11236        queue.put(&mut blocked).unwrap();
11237
11238        resolve_blockers(&queue, &questions);
11239
11240        let after = queue.get(&blocked.id).unwrap();
11241        assert_eq!(
11242            after.status,
11243            TaskStatus::Blocked,
11244            "one dependency is still outstanding"
11245        );
11246        assert_eq!(after.blocked_by, [still_going.id.clone()]);
11247    }
11248
11249    #[test]
11250    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11251        let dir = tempfile::tempdir().unwrap();
11252        let queue = Queue::at(dir.path().join("queue"));
11253        let questions = ask::Questions::at(dir.path().join("questions"));
11254
11255        let mut q = crate::ask::Question::new(
11256            "20260101-000001-main".to_owned(),
11257            crate::conduct::NODE.to_owned(),
11258            "conduct".to_owned(),
11259            "Which backend?".to_owned(),
11260            String::new(),
11261            Vec::new(),
11262        );
11263        questions.put(&mut q).unwrap();
11264        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11265            .unwrap();
11266        questions.put(&mut q).unwrap();
11267
11268        let mut blocked = task();
11269        blocked.id = "20260101-000001-main".to_owned();
11270        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11271        queue.put(&mut blocked).unwrap();
11272
11273        resolve_blockers(&queue, &questions);
11274
11275        let after = queue.get(&blocked.id).unwrap();
11276        assert_eq!(
11277            after.status,
11278            TaskStatus::Queued,
11279            "the only blocker resolved"
11280        );
11281        assert_eq!(after.answers.len(), 1);
11282        assert_eq!(after.answers[0].question, "Which backend?");
11283        assert_eq!(after.answers[0].answer, "SQLite");
11284
11285        // And the run this task starts next is told about it.
11286        let instruction = instruction_for(&after);
11287        assert!(instruction.contains("Which backend?"));
11288        assert!(instruction.contains("SQLite"));
11289    }
11290
11291    #[test]
11292    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11293        let dir = tempfile::tempdir().unwrap();
11294        let queue = Queue::at(dir.path().join("queue"));
11295        let questions = ask::Questions::at(dir.path().join("questions"));
11296
11297        let mut q = crate::ask::Question::new(
11298            "20260101-000001-main".to_owned(),
11299            crate::conduct::NODE.to_owned(),
11300            "conduct".to_owned(),
11301            "Is the setup done?".to_owned(),
11302            String::new(),
11303            Vec::new(),
11304        );
11305        q.abandon("no answer within 60s of asking");
11306        questions.put(&mut q).unwrap();
11307
11308        let mut blocked = task();
11309        blocked.id = "20260101-000001-main".to_owned();
11310        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11311        queue.put(&mut blocked).unwrap();
11312
11313        resolve_blockers(&queue, &questions);
11314
11315        let after = queue.get(&blocked.id).unwrap();
11316        assert_eq!(
11317            after.status,
11318            TaskStatus::Held,
11319            "never left blocked on nothing"
11320        );
11321        assert!(!after.operator_held(), "a machine hold, for triage");
11322        assert!(
11323            after
11324                .hold_reason
11325                .as_deref()
11326                .unwrap_or_default()
11327                .contains("went unanswered")
11328        );
11329    }
11330
11331    #[test]
11332    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11333        // Reproduces the reported bug (task 3958): a task held out of
11334        // attempts, blocked on a `crate::conduct` follow-up question, must
11335        // come back `held` once that question is answered - never `queued`,
11336        // whatever the answer said - or it silently re-enters the
11337        // competition queue with its attempts already exhausted.
11338        let dir = tempfile::tempdir().unwrap();
11339        let queue = Queue::at(dir.path().join("queue"));
11340        let questions = ask::Questions::at(dir.path().join("questions"));
11341
11342        let mut q = crate::ask::Question::new(
11343            "20260101-000001-main".to_owned(),
11344            crate::conduct::NODE.to_owned(),
11345            "conduct".to_owned(),
11346            "How should this be handled?".to_owned(),
11347            String::new(),
11348            Vec::new(),
11349        );
11350        questions.put(&mut q).unwrap();
11351        q.answer(crate::ask::Answer::Text(
11352            "leave it held, a human will look at it later".to_owned(),
11353        ))
11354        .unwrap();
11355        questions.put(&mut q).unwrap();
11356
11357        let mut held = task();
11358        held.id = "20260101-000001-main".to_owned();
11359        held.hold_machine(Some("out of attempts".to_owned()));
11360        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11361        queue.put(&mut held).unwrap();
11362
11363        resolve_blockers(&queue, &questions);
11364
11365        let after = queue.get(&held.id).unwrap();
11366        assert_eq!(after.status, TaskStatus::Held);
11367        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11368        assert_eq!(
11369            after.answers[0].answer,
11370            "leave it held, a human will look at it later"
11371        );
11372    }
11373
11374    #[test]
11375    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11376        let dir = tempfile::tempdir().unwrap();
11377        let queue = Queue::at(dir.path().join("queue"));
11378        let questions = ask::Questions::at(dir.path().join("questions"));
11379        let mut dep = task();
11380        dep.id = "20260101-000001-gone".to_owned();
11381        queue.put(&mut dep).unwrap();
11382        let mut blocked = task();
11383        blocked.id = "20260101-000003-main".to_owned();
11384        blocked.block(vec![dep.id.clone()], None);
11385        queue.put(&mut blocked).unwrap();
11386
11387        // Claimed, so `remove` cannot rewrite it and the resolver must.
11388        let claim = queue.claim(&blocked.id).unwrap();
11389        queue.remove(&dep.id, false, &questions).unwrap();
11390        drop(claim);
11391        resolve_blockers(&queue, &questions);
11392
11393        let after = queue.get(&blocked.id).unwrap();
11394        assert_eq!(after.status, TaskStatus::Queued);
11395        assert!(after.blocked_by.is_empty());
11396    }
11397
11398    #[test]
11399    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11400        // Reproduces the reported bug: a task blocked on a task id that was
11401        // removed (`magi task rm`, or deleted by hand) can never see that id
11402        // reach `Done`, so the ordinary per-id loop has nothing to notice and
11403        // would otherwise leave the task `blocked` forever with no way for an
11404        // operator to find out why.
11405        let dir = tempfile::tempdir().unwrap();
11406        let queue = Queue::at(dir.path().join("queue"));
11407        let questions = ask::Questions::at(dir.path().join("questions"));
11408
11409        let mut still_going = task();
11410        still_going.id = "20260101-000002-dep1".to_owned();
11411        queue.put(&mut still_going).unwrap();
11412
11413        let mut blocked = task();
11414        blocked.id = "20260101-000003-main".to_owned();
11415        blocked.block(
11416            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11417            Some("waits on both".to_owned()),
11418        );
11419        queue.put(&mut blocked).unwrap();
11420
11421        resolve_blockers(&queue, &questions);
11422
11423        let after = queue.get(&blocked.id).unwrap();
11424        assert_eq!(
11425            after.status,
11426            TaskStatus::Held,
11427            "a missing dependency must not leave the task blocked forever"
11428        );
11429        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11430        assert!(after.blocked_by.is_empty());
11431        let reason = after.hold_reason.as_deref().unwrap_or_default();
11432        assert!(
11433            reason.contains("20260101-000001-gone"),
11434            "the missing id must be named so an operator can tell what happened: {reason}"
11435        );
11436        assert!(
11437            reason.contains(&still_going.id),
11438            "the still-valid dependency must not silently vanish from the record: {reason}"
11439        );
11440    }
11441
11442    #[test]
11443    fn instruction_for_is_unchanged_without_any_answers() {
11444        let t = task();
11445        assert_eq!(instruction_for(&t), t.instruction);
11446    }
11447
11448    #[test]
11449    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11450        let dir = tempfile::tempdir().unwrap();
11451        let q = Queue::at(dir.path().join("queue"));
11452        let src = dir.path().join("shot.png");
11453        std::fs::write(&src, "x").unwrap();
11454        let mut t = task();
11455        q.attach(&mut t, &[src]).unwrap();
11456        let paths = task_attachments(&q, &t).unwrap();
11457        assert_eq!(paths.len(), 1);
11458        assert!(paths[0].is_absolute() && paths[0].is_file());
11459        std::fs::remove_file(&paths[0]).unwrap();
11460        let err = task_attachments(&q, &t).unwrap_err().to_string();
11461        assert!(err.contains("shot.png"), "{err}");
11462    }
11463
11464    #[tokio::test]
11465    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11466        let dir = tempfile::tempdir().unwrap();
11467        let queue_path = dir.path().join("queue");
11468        let queue = Queue::at(queue_path.clone());
11469        let mut t = task();
11470        t.source = Source::Agent {
11471            run: "originating-chat".into(),
11472            node: crate::queue::CHAT_NODE.into(),
11473        };
11474        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11475            stage: "config-fetch",
11476            target: "origin/main".into(),
11477        });
11478        record_config_failure(&mut t, &fetch);
11479        t.hold_machine(Some(format!("{fetch:#}")));
11480        let fetch_key = t.chat_notice_due().unwrap();
11481        t.chat_notices.push(fetch_key.clone());
11482        queue.put(&mut t).unwrap();
11483
11484        let queue = Queue::at(queue_path);
11485        let mut t = queue.get(&t.id).unwrap();
11486        let a = dir.path().join("a.toml");
11487        let b = dir.path().join("b.toml");
11488        for (path, text, new_cause) in [
11489            (&a, "[graph", true),
11490            (&a, "[verify", false),
11491            (&a, "[graph]\nimplementers = 'invalid-type'", true),
11492            (&b, "[graph]\nimplementers = 'invalid-type'", true),
11493        ] {
11494            t.release_operator("test", None);
11495            std::fs::write(path, text).unwrap();
11496            let error = Config::discover_fetched(dir.path(), Some(path))
11497                .await
11498                .unwrap_err();
11499            record_config_failure(&mut t, &error);
11500            t.hold_machine(Some(format!("{error:#}")));
11501            let due = t.chat_notice_due();
11502            assert_eq!(due.is_some(), new_cause, "{error:#}");
11503            if let Some(key) = due {
11504                assert_ne!(key, fetch_key);
11505                t.chat_notices.push(key);
11506            }
11507        }
11508        t.succeed();
11509        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11510    }
11511
11512    #[test]
11513    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11514        let dir = tempfile::tempdir().unwrap();
11515        let queue_path = dir.path().join("queue");
11516        let queue = Queue::at(queue_path.clone());
11517        let mut t = task();
11518        t.source = crate::queue::Source::Agent {
11519            run: "originating-chat".into(),
11520            node: crate::queue::CHAT_NODE.into(),
11521        };
11522        let a = dir.path().join("a.png");
11523        let b = dir.path().join("b.png");
11524        std::fs::write(&a, "a").unwrap();
11525        std::fs::write(&b, "b").unwrap();
11526        queue.attach(&mut t, &[a, b]).unwrap();
11527        let paths = task_attachments(&queue, &t).unwrap();
11528        for path in &paths {
11529            std::fs::remove_file(path).unwrap();
11530        }
11531        let missing = task_attachments(&queue, &t).unwrap_err();
11532        t.attempts += 1;
11533        let reason = missing.to_string();
11534        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11535        let first = t.chat_notice_due().expect("first attachment notice");
11536        t.chat_notices.push(first.clone());
11537        queue.put(&mut t).unwrap();
11538
11539        let queue = Queue::at(queue_path.clone());
11540        let mut t = queue.get(&t.id).unwrap();
11541        assert!(t.chat_notice_due().is_none(), "restart does not replay");
11542        t.release_operator("test", None);
11543        t.attempts += 1;
11544        let missing = task_attachments(&queue, &t).unwrap_err();
11545        t.fail_startup_target(
11546            "startup-attachments",
11547            missing.name,
11548            "same missing attachment with regenerated wording",
11549            1,
11550        );
11551        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11552
11553        std::fs::write(&paths[0], "restored").unwrap();
11554        t.release_operator("test", None);
11555        t.attempts += 1;
11556        let missing = task_attachments(&queue, &t).unwrap_err();
11557        let reason = missing.to_string();
11558        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11559        let second = t
11560            .chat_notice_due()
11561            .expect("different attachment must notify");
11562        assert_ne!(first, second);
11563        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11564    }
11565
11566    #[test]
11567    fn resumed_instruction_is_unchanged_without_any_answers() {
11568        let t = task();
11569        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11570    }
11571
11572    #[test]
11573    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11574        let mut t = task();
11575        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11576        // The run's own instruction on disk predates the answer: it is the
11577        // plain original text `Runner::start` saved before the operator was
11578        // ever asked anything.
11579        let old = t.instruction.clone();
11580
11581        let refreshed = resumed_instruction(&old, &t);
11582        assert!(refreshed.starts_with(&old), "the original text is kept");
11583        assert!(refreshed.contains("Which backend?"));
11584        assert!(refreshed.contains("SQLite"));
11585    }
11586
11587    #[test]
11588    fn resumed_instruction_keeps_an_original_answers_heading() {
11589        let mut t = task();
11590        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11591        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11592
11593        let refreshed = resumed_instruction(&t.instruction, &t);
11594
11595        assert!(
11596            refreshed.starts_with(&t.instruction),
11597            "an answers heading in the original instruction is not the appended block"
11598        );
11599        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11600        assert!(refreshed.contains("Which backend?"));
11601        assert!(refreshed.contains("SQLite"));
11602
11603        let repeated = resumed_instruction(&refreshed, &t);
11604        assert_eq!(
11605            repeated, refreshed,
11606            "only the final appended block is refreshed"
11607        );
11608    }
11609
11610    #[test]
11611    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11612        let mut t = task();
11613        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11614
11615        // A first resume appends the block; a second resume of the same run,
11616        // with no new answer in between, must reproduce exactly the same
11617        // text rather than appending the block a second time.
11618        let once = resumed_instruction(&t.instruction, &t);
11619        let twice = resumed_instruction(&once, &t);
11620        assert_eq!(once, twice);
11621        assert_eq!(once.matches("Which backend?").count(), 1);
11622
11623        // A later answer replaces the block wholesale rather than growing it.
11624        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11625        let refreshed = resumed_instruction(&once, &t);
11626        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11627        assert!(refreshed.contains("Which backend?"));
11628        assert!(refreshed.contains("Which cache?"));
11629    }
11630
11631    #[test]
11632    fn prepare_instruction_covers_all_three_starters() {
11633        let mut t = task();
11634        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11635
11636        // Start: a fresh run gets the task text plus every answer so far —
11637        // exactly `instruction_for`.
11638        assert_eq!(
11639            prepare_instruction(&Starter::Start, None, &t),
11640            Some(instruction_for(&t))
11641        );
11642
11643        // Resume: the run's prior instruction is refreshed with the answer,
11644        // not discarded and not left stale.
11645        let old = t.instruction.clone();
11646        assert_eq!(
11647            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11648            Some(resumed_instruction(&old, &t))
11649        );
11650
11651        // Review: a review-only pass builds its own instruction from the
11652        // branch's history in `crate::graph`, with no task statement at all -
11653        // this boundary must leave it alone.
11654        assert_eq!(
11655            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11656            None
11657        );
11658    }
11659
11660    #[test]
11661    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11662        assert_eq!(
11663            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11664            Starter::Review("magi/eba2/A".to_owned())
11665        );
11666    }
11667
11668    #[test]
11669    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11670        assert_eq!(
11671            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11672            Starter::Start,
11673            "a vanished review branch must not fall back to resuming the old run either"
11674        );
11675    }
11676
11677    #[test]
11678    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11679        let mut t = task();
11680        t.start("old-run".to_owned());
11681        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11682        t.release();
11683        let branch = t.review_branch.take();
11684        assert_eq!(
11685            choose_starter(branch.as_deref(), true, Some("old-run")),
11686            Starter::Review("magi/eba2/A".to_owned()),
11687            "a review wins over resuming the old run"
11688        );
11689    }
11690
11691    #[test]
11692    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11693        assert_eq!(
11694            choose_starter(None, false, Some("some-run")),
11695            Starter::Resume("some-run".to_owned())
11696        );
11697        assert_eq!(choose_starter(None, false, None), Starter::Start);
11698    }
11699
11700    #[test]
11701    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11702        let mut released = task();
11703        released.start("stalled-run".to_owned());
11704        released.requeue();
11705        let unfinished = (!released.fresh_start)
11706            .then(|| Some("stalled-run".to_owned()))
11707            .flatten();
11708        assert_eq!(
11709            choose_starter(None, false, unfinished.as_deref()),
11710            Starter::Start,
11711            "release keeps run history but must not resume it"
11712        );
11713        assert_eq!(released.runs, ["stalled-run"]);
11714    }
11715
11716    fn stopped_public_run(status: RunStatus) -> RunState {
11717        let mut state = run_state(status);
11718        state.driver_exited = true;
11719        state.config.graph.land = true;
11720        state.config.graph.review_rounds = 1;
11721        state.reviews = vec![review_round(1)];
11722        state.merge = Some(crate::run::MergeOutcome {
11723            mode: MergeMode::Pr,
11724            ok: false,
11725            detail: "landing stopped".into(),
11726            empty: false,
11727        });
11728        state.pr = Some(crate::run::PrRecord {
11729            url: "https://example.test/pull/1".into(),
11730            number: 1,
11731            state: "open".into(),
11732            checks: "red".into(),
11733            round: 1,
11734            rounds: 1,
11735            red_at_merge: Vec::new(),
11736        });
11737        state
11738    }
11739
11740    #[test]
11741    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11742        for status in [RunStatus::Blocked, RunStatus::Gating] {
11743            let home = tempfile::tempdir().unwrap();
11744            let mut state = stopped_public_run(status);
11745            state.save_under(home.path()).unwrap();
11746            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11747            assert!(!exhausted_review_budget(&state));
11748            let mut task = held_task_with(&state.id);
11749            task.release();
11750            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11751            assert_eq!(
11752                choose_starter(None, false, unfinished.as_deref()),
11753                Starter::Resume(state.id.clone())
11754            );
11755            let question = action_question(&state.id, resume_action(&state.id));
11756            assert_eq!(
11757                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11758                    state.clone()
11759                )),
11760                ActionDecision::Resume(state.id.clone())
11761            );
11762            // The control-plane command uses this same preflight before pinning.
11763            assert_eq!(
11764                crate::resume::validate(home.path(), &state.id).unwrap().id,
11765                state.id
11766            );
11767            let queue = Queue::at(home.path().join("queue"));
11768            let mut controlled = Task::new(
11769                "resume land".into(),
11770                state.instruction.clone(),
11771                state.repo.clone(),
11772                Source::Agent {
11773                    run: "talk".into(),
11774                    node: crate::queue::CHAT_NODE.into(),
11775                },
11776            );
11777            controlled.runs.push(state.id.clone());
11778            controlled.hold_machine(Some("land stopped".into()));
11779            queue.put(&mut controlled).unwrap();
11780            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11781            assert_eq!(resumed.status, TaskStatus::Queued);
11782            assert_eq!(
11783                resumed.resume_override.unwrap().pinned_run,
11784                Some(state.id.clone())
11785            );
11786            assert_eq!(resumed.attempts, 0);
11787        }
11788    }
11789
11790    #[test]
11791    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
11792        for review_rounds in [0, 1] {
11793            let home = tempfile::tempdir().unwrap();
11794            let mut state = run_state(RunStatus::Blocked);
11795            state.config.graph.review_rounds = review_rounds;
11796            if review_rounds > 0 {
11797                let mut review = review_round(1);
11798                review.clean = true;
11799                state.reviews = vec![review];
11800            }
11801            state.gate_ran = true;
11802            state.gate = vec![crate::run::CommandOutcome {
11803                command: "verify".into(),
11804                code: Some(1),
11805                output_tail: "gate failed after repair budget exhausted".into(),
11806                duration_ms: 0,
11807                resource_blocked: false,
11808            }];
11809            state.save_under(home.path()).unwrap();
11810            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11811            assert!(exhausted_review_budget(&state));
11812            let mut task = held_task_with(&state.id);
11813            task.release();
11814            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
11815            let question = action_question(&state.id, resume_action(&state.id));
11816            assert_ne!(
11817                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11818                    state.clone()
11819                )),
11820                ActionDecision::Resume(state.id.clone())
11821            );
11822            let error = crate::resume::validate(home.path(), &state.id)
11823                .unwrap_err()
11824                .to_string();
11825            assert!(!error.contains("review budget exhausted"), "{error}");
11826            assert!(
11827                error.contains(if review_rounds == 0 {
11828                    "review is disabled"
11829                } else {
11830                    "gate already ran"
11831                }),
11832                "{error}"
11833            );
11834
11835            // An unexecuted gate still has work to do with or without reviews.
11836            state.gate_ran = false;
11837            state.gate.clear();
11838            assert!(!exhausted_review_budget(&state));
11839            assert_eq!(
11840                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
11841                Some(state.id)
11842            );
11843        }
11844    }
11845
11846    #[test]
11847    fn resource_blocked_verification_resumes_the_same_run() {
11848        for (kind, stage) in [
11849            ("cache", "clean"),
11850            ("coordination", "clean"),
11851            ("cache", "review-e2e"),
11852            ("coordination", "no-reviews"),
11853            ("coordination", "handoff"),
11854        ] {
11855            let home = tempfile::tempdir().unwrap();
11856            let mut state = run_state(RunStatus::Blocked);
11857            state.config.graph.review_rounds = 1;
11858            let mut review = review_round(1);
11859            review.clean = true;
11860            state.reviews = vec![review];
11861            if stage == "review-e2e" {
11862                let review = &mut state.reviews[0];
11863                review.clean = false;
11864                review.blocking = 1;
11865                review.e2e = vec![crate::run::CommandOutcome {
11866                    command: "verify".into(),
11867                    code: None,
11868                    output_tail: "resource wait expired".into(),
11869                    duration_ms: 0,
11870                    resource_blocked: true,
11871                }];
11872            } else if stage == "no-reviews" {
11873                state.config.graph.review_rounds = 0;
11874                state.reviews.clear();
11875            } else if stage == "handoff" {
11876                // A completed final verification can hand off to the gate
11877                // even when the review still carries contested findings.
11878                let review = &mut state.reviews[0];
11879                review.clean = false;
11880                review.blocking = 1;
11881                review.e2e = vec![crate::run::CommandOutcome {
11882                    command: "verify".into(),
11883                    code: Some(0),
11884                    output_tail: String::new(),
11885                    duration_ms: 0,
11886                    resource_blocked: false,
11887                }];
11888            }
11889            state.gate_ran = false;
11890            state.resource_block = Some(crate::run::ResourceBlock {
11891                cause: crate::run::ResourceBlockCause::Other,
11892                node: if stage == "review-e2e" {
11893                    "review"
11894                } else {
11895                    "gate"
11896                }
11897                .into(),
11898                kind: kind.into(),
11899                detail: "resource wait expired".into(),
11900                at: jiff::Timestamp::now(),
11901            });
11902            state.save_under(home.path()).unwrap();
11903            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11904            assert!(!exhausted_review_budget(&state));
11905            let mut task = held_task_with(&state.id);
11906            task.release();
11907            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11908            assert_eq!(
11909                choose_starter(None, false, unfinished.as_deref()),
11910                Starter::Resume(state.id.clone())
11911            );
11912            let question = action_question(&state.id, resume_action(&state.id));
11913            assert_eq!(
11914                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11915                    state.clone()
11916                )),
11917                ActionDecision::Resume(state.id.clone())
11918            );
11919            assert_eq!(
11920                crate::resume::validate(home.path(), &state.id).unwrap().id,
11921                state.id
11922            );
11923            let queue = Queue::at(home.path().join("queue"));
11924            let mut controlled = Task::new(
11925                "resume verification".into(),
11926                state.instruction.clone(),
11927                state.repo.clone(),
11928                Source::Agent {
11929                    run: "talk".into(),
11930                    node: crate::queue::CHAT_NODE.into(),
11931                },
11932            );
11933            controlled.runs.push(state.id.clone());
11934            controlled.hold_machine(Some("verification resource unavailable".into()));
11935            queue.put(&mut controlled).unwrap();
11936            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11937            assert_eq!(resumed.status, TaskStatus::Queued);
11938            assert_eq!(
11939                resumed.resume_override.unwrap().pinned_run,
11940                Some(state.id.clone())
11941            );
11942            assert_eq!(resumed.attempts, 0);
11943
11944            // A genuinely unresolved final review still exhausts the budget.
11945            state.config.graph.review_rounds = 1;
11946            let mut unresolved = review_round(1);
11947            unresolved.blocking = 1;
11948            state.reviews = vec![unresolved];
11949            state.resource_block = None;
11950            state.save_under(home.path()).unwrap();
11951            assert!(exhausted_review_budget(&state));
11952            assert!(crate::resume::validate(home.path(), &state.id).is_err());
11953        }
11954    }
11955
11956    #[tokio::test]
11957    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
11958        if !crate::standalone_test(
11959            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
11960        ) {
11961            return;
11962        }
11963        let home = tempfile::tempdir().unwrap();
11964        let mut owner = stopped_public_run(RunStatus::Blocked);
11965        owner.save_under(home.path()).unwrap();
11966        let history = vec![owner.id.clone()];
11967        let repo = owner.repo.clone();
11968        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
11969        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
11970        let initial =
11971            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
11972        assert!(
11973            initial.is_pending(),
11974            "a busy record must not hold or resume the task"
11975        );
11976        owner.retired_to = Some("20260101-000001-bbbb".into());
11977        owner.save_under(home.path()).unwrap();
11978        drop(lock);
11979        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
11980            .await
11981            .expect("ownership lock released")
11982            .expect("read settled owner");
11983        assert!(
11984            result.is_none(),
11985            "the retired owner must not be resumed from a stale read"
11986        );
11987    }
11988
11989    #[tokio::test]
11990    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
11991        if !crate::standalone_test(
11992            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
11993        ) {
11994            return;
11995        }
11996        let home = tempfile::tempdir().unwrap();
11997        let mut owner = stopped_public_run(RunStatus::Blocked);
11998        let repo = tempfile::tempdir().unwrap();
11999        crate::git::git(repo.path(), &["init"]).await.unwrap();
12000        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
12001        owner.id = "20260101-000000-aaaa".into();
12002        owner.save_under(home.path()).unwrap();
12003        let mut successor = run_state(RunStatus::Blocked);
12004        successor.id = "20260101-000001-bbbb".into();
12005        successor.save_under(home.path()).unwrap();
12006        let runs = vec![owner.id.clone(), successor.id.clone()];
12007        assert_eq!(
12008            public_resume_owner(home.path(), &runs, &owner.repo)
12009                .await
12010                .unwrap()
12011                .unwrap()
12012                .id,
12013            owner.id
12014        );
12015        let subdir = owner.repo.join("nested");
12016        std::fs::create_dir(&subdir).unwrap();
12017        assert_eq!(
12018            public_resume_owner(home.path(), &runs, &subdir)
12019                .await
12020                .unwrap()
12021                .unwrap()
12022                .id,
12023            owner.id
12024        );
12025        #[cfg(unix)]
12026        {
12027            let alias = home.path().join("repo-alias");
12028            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
12029            assert_eq!(
12030                public_resume_owner(home.path(), &runs, &alias.join("nested"))
12031                    .await
12032                    .unwrap()
12033                    .unwrap()
12034                    .id,
12035                owner.id
12036            );
12037        }
12038        let different = tempfile::tempdir().unwrap();
12039        crate::git::git(different.path(), &["init"]).await.unwrap();
12040        assert!(
12041            public_resume_owner(home.path(), &runs, different.path())
12042                .await
12043                .is_err()
12044        );
12045        std::fs::remove_file(
12046            home.path()
12047                .join("runs")
12048                .join(&successor.id)
12049                .join("run.json"),
12050        )
12051        .unwrap();
12052        assert!(
12053            public_resume_owner(home.path(), &runs, &owner.repo)
12054                .await
12055                .is_err()
12056        );
12057    }
12058
12059    #[test]
12060    fn an_ordinary_release_keeps_a_resumable_run_available() {
12061        let mut released = task();
12062        released.start("stalled-run".to_owned());
12063        released.release();
12064        let unfinished = (!released.fresh_start)
12065            .then(|| Some("stalled-run".to_owned()))
12066            .flatten();
12067        assert_eq!(
12068            choose_starter(None, false, unfinished.as_deref()),
12069            Starter::Resume("stalled-run".to_owned()),
12070            "manual release must preserve the normal resume path"
12071        );
12072    }
12073
12074    #[test]
12075    fn resume_refusals_explain_admission_without_changing_task_or_run() {
12076        use crate::handover::{ResumeRefusal, resume_refusal_under};
12077        let home = tempfile::tempdir().unwrap();
12078        let mut exhausted = run_state(RunStatus::Blocked);
12079        exhausted.driver_exited = true;
12080        exhausted.config.graph.review_rounds = 3;
12081        exhausted.reviews = (1..=3).map(review_round).collect();
12082        for refusal in [
12083            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
12084            ResumeRefusal::Status(RunStatus::Ready),
12085            ResumeRefusal::Released("20261022-000000-aaaa".into()),
12086            ResumeRefusal::Retired("retirement-successor".into()),
12087            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
12088        ] {
12089            let mut state = exhausted.clone();
12090            let expected = match refusal {
12091                ResumeRefusal::Status(_) => {
12092                    state.status = RunStatus::Ready;
12093                    "status `ready`"
12094                }
12095                ResumeRefusal::Released(ref target) => {
12096                    state.released_to = Some(target.clone());
12097                    "execution was released"
12098                }
12099                ResumeRefusal::Retired(ref target) => {
12100                    state.retired_to = Some(target.clone());
12101                    "execution was retired"
12102                }
12103                ResumeRefusal::OwnershipTransferred(ref target) => {
12104                    state.pr_taken_over_by = Some(target.clone());
12105                    "PR ownership was transferred"
12106                }
12107                _ => "review budget exhausted (3/3 rounds used)",
12108            };
12109            assert_eq!(
12110                resume_refusal_under(&state, Some(home.path())),
12111                Some(refusal.clone())
12112            );
12113            assert_eq!(
12114                refusal.successor(),
12115                state
12116                    .released_to
12117                    .as_deref()
12118                    .or(state.retired_to.as_deref())
12119                    .or(state.pr_taken_over_by.as_deref())
12120            );
12121            state.save_under(home.path()).unwrap();
12122            let queue = Queue::at(home.path().join("queue"));
12123            let mut task = Task::new(
12124                "retained implementation".into(),
12125                state.instruction.clone(),
12126                state.repo.clone(),
12127                Source::Agent {
12128                    run: "talk".into(),
12129                    node: crate::queue::CHAT_NODE.into(),
12130                },
12131            );
12132            task.runs.push(state.id.clone());
12133            task.hold_machine(Some("stopped".into()));
12134            queue.put(&mut task).unwrap();
12135            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
12136            let before_run = serde_json::to_value(&state).unwrap();
12137            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
12138                .unwrap_err()
12139                .to_string();
12140            assert!(error.contains(expected), "{error}");
12141            assert!(!error.contains("only a stalled or blocked"), "{error}");
12142            if matches!(refusal, ResumeRefusal::Status(_)) {
12143                assert!(
12144                    error.contains("is final; there is nothing left to resume"),
12145                    "{error}"
12146                );
12147            }
12148            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
12149                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
12150                assert!(error.contains("review-only successor with a new review budget"));
12151                assert!(error.contains("does not resume this run"));
12152            }
12153            for target in [
12154                &state.released_to,
12155                &state.retired_to,
12156                &state.pr_taken_over_by,
12157            ]
12158            .into_iter()
12159            .flatten()
12160            {
12161                let short = if state.retired_to.as_ref() == Some(target) {
12162                    target.as_str()
12163                } else {
12164                    crate::run::short_of(target)
12165                };
12166                assert!(
12167                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
12168                    "{error}"
12169                );
12170                if short != target {
12171                    assert!(!error.contains(target), "full successor id leaked: {error}");
12172                }
12173            }
12174            assert_eq!(
12175                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12176                before_task
12177            );
12178            assert_eq!(
12179                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12180                    .unwrap(),
12181                before_run
12182            );
12183            let question = action_question(&state.id, resume_action(&state.id));
12184            for phrases in [&PHRASES_EN, &PHRASES_JA] {
12185                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
12186                    RunState::load_under(id, home.path())
12187                });
12188                let ActionDecision::Refuse(detail) = decision else {
12189                    panic!(
12190                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
12191                        state.id,
12192                        home.path().display()
12193                    );
12194                };
12195                assert!(detail.contains(expected), "{detail}");
12196            }
12197        }
12198        // Preserve predicate ordering, while keeping every recorded destination visible.
12199        exhausted.status = RunStatus::Ready;
12200        exhausted.released_to = Some("released".into());
12201        exhausted.retired_to = Some("retired".into());
12202        exhausted.pr_taken_over_by = Some("owner".into());
12203        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12204        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12205        let detail = reason.diagnostic(&exhausted);
12206        for target in ["released", "retired", "owner"] {
12207            assert!(detail.contains(&format!("magi show {target}")));
12208        }
12209    }
12210
12211    #[test]
12212    fn resume_action_ignores_question_checkpoints_in_another_home() {
12213        crate::run::pin_test_home();
12214        let home = tempfile::tempdir().unwrap();
12215        let mut state = run_state(RunStatus::Blocked);
12216        // The private directory reserves this fixture's identity even while
12217        // other tests write questions into the process-wide store.
12218        state.id = format!(
12219            "resume-context-{}",
12220            home.path().file_name().unwrap().to_str().unwrap()
12221        );
12222        state.driver_exited = true;
12223        state.config.graph.review_rounds = 1;
12224        state.reviews = vec![review_round(1)];
12225        state.save_under(home.path()).unwrap();
12226        let task = held_task_with(&state.id);
12227        let answer = action_question(&state.id, resume_action(&state.id));
12228        let mut checkpoint = approval_question(&state.id);
12229        let foreign = Questions::open();
12230        foreign.put(&mut checkpoint).unwrap();
12231        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
12232        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12233            RunState::load_under(id, home.path())
12234        });
12235        let matching: Vec<_> = foreign
12236            .list()
12237            .into_iter()
12238            .filter(|q| q.run == state.id && q.status.open())
12239            .collect();
12240        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
12241        assert!(
12242            matches!(decision, ActionDecision::Refuse(_)),
12243            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
12244            state.id,
12245            home.path().display(),
12246            crate::run::test_home().display()
12247        );
12248        assert_eq!(
12249            refusal,
12250            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
12251        );
12252        let local = Questions::at(home.path().join("questions"));
12253        for status in [
12254            ask::QuestionStatus::Open,
12255            ask::QuestionStatus::Answered,
12256            ask::QuestionStatus::Abandoned,
12257        ] {
12258            let mut question = checkpoint.clone();
12259            match status {
12260                ask::QuestionStatus::Open => {}
12261                ask::QuestionStatus::Answered => {
12262                    question
12263                        .answer(ask::Answer::Choice(question.choices[0].clone()))
12264                        .unwrap();
12265                }
12266                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
12267            }
12268            local.put(&mut question).unwrap();
12269            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12270                RunState::load_under(id, home.path())
12271            });
12272            if status.open() {
12273                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
12274            } else {
12275                assert!(
12276                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
12277                    "status={status:?}, decision={decision:?}"
12278                );
12279            }
12280        }
12281    }
12282
12283    #[test]
12284    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
12285        let home = tempfile::tempdir().unwrap();
12286        let mut state = run_state(RunStatus::Stalled);
12287        state.id = format!(
12288            "resume-driver-{}",
12289            home.path().file_name().unwrap().to_str().unwrap()
12290        );
12291        state.driver_claimed = Some(false);
12292        state.save_under(home.path()).unwrap();
12293        let task = held_task_with(&state.id);
12294        let question = action_question(&state.id, resume_action(&state.id));
12295        let decide = || {
12296            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
12297                RunState::load_under(id, home.path())
12298            })
12299        };
12300        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
12301        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
12302        assert_eq!(
12303            decide(),
12304            ActionDecision::Refuse("run already has a live driver".into())
12305        );
12306        drop(lease);
12307        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
12308    }
12309
12310    #[test]
12311    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12312        let home = tempfile::tempdir().unwrap();
12313        let mut state = run_state(RunStatus::Blocked);
12314        state.driver_exited = true;
12315        state.config.graph.review_rounds = 1;
12316        state.reviews = vec![review_round(1)];
12317        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12318        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12319            let mut saved = state.clone();
12320            match checkpoint {
12321                "publication" => saved.pr_publication_pending = true,
12322                "approval" => {
12323                    saved.land_approval = Some(crate::run::LandApproval {
12324                        question: "approval".into(),
12325                        head: "head".into(),
12326                    })
12327                }
12328                "armed" => saved.land_armed_head = Some("head".into()),
12329                "landing" => saved.status = RunStatus::Landing,
12330                _ => {
12331                    let mut question = ask::Question::new(
12332                        saved.id.clone(),
12333                        "review".into(),
12334                        "review-1".into(),
12335                        "continue?".into(),
12336                        String::new(),
12337                        vec!["continue".into()],
12338                    );
12339                    ask::Questions::at(home.path().join("questions"))
12340                        .put(&mut question)
12341                        .unwrap();
12342                }
12343            }
12344            saved.save_under(home.path()).unwrap();
12345            assert!(
12346                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12347                "{checkpoint}"
12348            );
12349            assert!(
12350                crate::resume::validate(home.path(), &saved.id).is_ok(),
12351                "{checkpoint}"
12352            );
12353        }
12354    }
12355
12356    #[test]
12357    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12358        let mut state = run_state(RunStatus::Blocked);
12359        state.config.graph.review_rounds = 3;
12360        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12361        assert!(exhausted_review_budget(&state));
12362
12363        // One round still unused: resuming can still ask a reviewer something.
12364        state.reviews.pop();
12365        assert!(!exhausted_review_budget(&state));
12366
12367        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
12368        // count: only a `Blocked` run re-enters the review loop on resume.
12369        let mut stalled = run_state(RunStatus::Stalled);
12370        stalled.config.graph.review_rounds = 1;
12371        stalled.reviews = vec![review_round(1)];
12372        assert!(!exhausted_review_budget(&stalled));
12373    }
12374
12375    fn review_round(round: usize) -> crate::run::ReviewRound {
12376        crate::run::ReviewRound {
12377            round,
12378            head: "deadbeef".to_owned(),
12379            verified_head: None,
12380            verified_at: None,
12381            reviews: Vec::new(),
12382            e2e: Vec::new(),
12383            verify_retried: false,
12384            e2e_deferred: false,
12385            e2e_defer_reason: None,
12386            fix: None,
12387            blocking: 0,
12388            answered: 1,
12389            expected: 1,
12390            clean: false,
12391            progressed: true,
12392            vote_split: false,
12393            reconsideration: Vec::new(),
12394            verdict: None,
12395        }
12396    }
12397
12398    #[test]
12399    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12400        let mut run = RunState::new(
12401            PathBuf::from("/repo"),
12402            "main".to_owned(),
12403            "abc1234def".to_owned(),
12404            "add retries".to_owned(),
12405            Config::default(),
12406        );
12407        run.status = RunStatus::Judging;
12408        run.parked = true;
12409        let mut task = Task::new(
12410            "add retries".to_owned(),
12411            "add retries".to_owned(),
12412            PathBuf::from("/repo"),
12413            crate::queue::Source::Human,
12414        );
12415        task.status = TaskStatus::Failed;
12416        task.runs = vec![run.id.clone()];
12417        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12418        assert!(with(&task, &run), "parked after judging is the case");
12419        let mut parked_task = task.clone();
12420        parked_task.status = TaskStatus::Parked;
12421        assert!(with(&parked_task, &run), "the Parked status is the case");
12422
12423        let mut not_parked = run.clone();
12424        not_parked.parked = false;
12425        not_parked.status = RunStatus::Stalled;
12426        assert!(!with(&task, &not_parked), "a stall is the conductor's");
12427
12428        let mut fresh = task.clone();
12429        fresh.fresh_start = true;
12430        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12431
12432        let mut review = task.clone();
12433        review.review_branch = Some("magi/x/A".to_owned());
12434        assert!(!with(&review, &run), "review is ranked before resume");
12435
12436        let mut held = task.clone();
12437        held.status = TaskStatus::Held;
12438        assert!(!with(&held, &run), "a hold stays visible to the conductor");
12439
12440        let mut released = run.clone();
12441        released.released_to = Some("20260901-000000-new1".to_owned());
12442        assert!(!with(&task, &released), "nothing left to resume into");
12443
12444        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12445            "unreadable"
12446        )));
12447    }
12448
12449    #[test]
12450    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12451        let mut released = RunState::new(
12452            PathBuf::from("/repo"),
12453            "main".to_owned(),
12454            "abc1234def".to_owned(),
12455            "add retries".to_owned(),
12456            Config::default(),
12457        );
12458        released.status = RunStatus::Blocked;
12459        assert_eq!(
12460            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12461            Some(released.id.clone())
12462        );
12463        released.released_to = Some("20260901-000000-new1".to_owned());
12464        assert_eq!(
12465            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12466            None,
12467            "there is nothing left to resume it into"
12468        );
12469    }
12470
12471    #[test]
12472    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12473        // Mirrors the failure this exists to close: a task's last run ended
12474        // `Blocked` with the review budget spent, `crate::conduct` chose
12475        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
12476        // evidence), and without this check `attempt` would go on treating
12477        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
12478        // review loop iterates zero times over an already-spent budget, so
12479        // the resumed run settles right back to `Blocked` having asked nobody
12480        // anything, and `Requeue`'s promised fresh competition never happens.
12481        let mut exhausted = RunState::new(
12482            PathBuf::from("/repo"),
12483            "main".to_owned(),
12484            "abc1234def".to_owned(),
12485            "add retries".to_owned(),
12486            Config::default(),
12487        );
12488        exhausted.status = RunStatus::Blocked;
12489        exhausted.config.graph.review_rounds = 1;
12490        exhausted.reviews = vec![review_round(1)];
12491
12492        assert_eq!(
12493            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12494            None,
12495            "an exhausted `Blocked` run must not be offered as resumable"
12496        );
12497
12498        // A `Blocked` run with rounds still unused is genuinely worth
12499        // resuming, and must still be found.
12500        let mut has_budget_left = RunState::new(
12501            PathBuf::from("/repo"),
12502            "main".to_owned(),
12503            "abc1234def".to_owned(),
12504            "add retries".to_owned(),
12505            Config::default(),
12506        );
12507        has_budget_left.status = RunStatus::Blocked;
12508        has_budget_left.config.graph.review_rounds = 3;
12509        has_budget_left.reviews = vec![review_round(1)];
12510
12511        assert_eq!(
12512            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12513                Ok(has_budget_left.clone())
12514            }),
12515            Some(has_budget_left.id.clone())
12516        );
12517    }
12518
12519    #[test]
12520    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12521        let mut run = RunState::new(
12522            PathBuf::from("/repo"),
12523            "main".to_owned(),
12524            "abc1234def".to_owned(),
12525            "add retries".to_owned(),
12526            Config::default(),
12527        );
12528        run.status = RunStatus::Blocked;
12529        run.config.graph.review_rounds = 1;
12530        run.reviews = vec![review_round(1)];
12531        run.pr_publication_pending = true;
12532        assert_eq!(
12533            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12534            Some(run.id.clone()),
12535            "a spent review budget must not turn a failed publication into a re-competition"
12536        );
12537    }
12538
12539    #[test]
12540    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12541        let mut task = Task::new(
12542            "recover work".into(),
12543            "recover work".into(),
12544            PathBuf::from("/repo"),
12545            crate::queue::Source::Human,
12546        );
12547        let mut history = std::collections::BTreeMap::new();
12548        for index in 0..8 {
12549            let mut run = run_state(RunStatus::Blocked);
12550            run.id = format!("20260101-000000-{index:04}");
12551            run.base_commit = format!("upstream-{index}");
12552            // Seven empty newer attempts must not erase the old recovery owner.
12553            if index > 0 {
12554                run.candidates.clear();
12555            }
12556            task.runs.extend([run.id.clone(), run.id.clone()]);
12557            history.insert(run.id.clone(), run);
12558            task.requeue();
12559        }
12560        let check = |task: &Task, starter: &Starter, limit| {
12561            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12562        };
12563        assert!(
12564            check(&task, &Starter::Start, 8)
12565                .unwrap()
12566                .contains("8 unretired")
12567        );
12568        assert!(check(&task, &Starter::Start, 9).is_none());
12569        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12570        task.release_operator("owner", None);
12571        assert_eq!(task.attempts, 0);
12572        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12573        assert!(check(&restored, &Starter::Start, 8).is_some());
12574        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12575        assert!(check(&restored, &Starter::Start, 0).is_none());
12576    }
12577
12578    #[test]
12579    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
12580        let tmp = tempfile::tempdir().unwrap();
12581        let mut task = Task::new(
12582            "recover selected PR".into(),
12583            "preserve implementation".into(),
12584            tmp.path().join("repo"),
12585            crate::queue::Source::Human,
12586        );
12587        let mut failed = run_state(RunStatus::Failed);
12588        failed.id = "20260101-000000-fail".into();
12589        failed.candidates.clear();
12590        failed.prep_complete = Some(false);
12591        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
12592        failed.startup = Some(crate::run::Startup {
12593            kind: "pr-recovery".into(),
12594            branch: Some("selected-public-head".into()),
12595            stage: "worktree-setup".into(),
12596            complete: false,
12597            failure: Some("setup modified a tracked file and failed".into()),
12598        });
12599        // Setup may fail before a candidate is recorded; its dirty worktree
12600        // still needs protection and consumes the independent retained bound.
12601        let worktree = failed.worktree_root().join("under-review");
12602        std::fs::create_dir_all(&worktree).unwrap();
12603        let retained_edit = worktree.join("implementation");
12604        std::fs::write(&retained_edit, "retained setup edit").unwrap();
12605        task.record_startup_failure(crate::run::StartupFailure {
12606            run: failed.id.clone(),
12607            stage: "worktree-setup".into(),
12608        });
12609        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12610        assert!(task.runs.is_empty() && task.passes.is_empty());
12611        assert_eq!(task.attempts, 0);
12612        let starter = Starter::Review("selected-public-head".into());
12613        assert!(
12614            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
12615                .unwrap()
12616                .contains("1 unretired")
12617        );
12618        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
12619        assert!(
12620            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
12621                .unwrap()
12622                .contains("Cannot verify")
12623        );
12624        // Older or mixed writers can link the same reservation in both lists.
12625        let mut mixed = task.clone();
12626        mixed.runs.push(failed.id.clone());
12627        mixed
12628            .startup_failures
12629            .push(task.startup_failures[0].clone());
12630        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
12631        failed.retired_to = Some("verified-recovery-owner".into());
12632        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
12633        assert!(
12634            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
12635                panic!("resuming the existing owner must not allocate a new attempt")
12636            })
12637            .is_none()
12638        );
12639        assert_eq!(
12640            std::fs::read_to_string(retained_edit).unwrap(),
12641            "retained setup edit"
12642        );
12643        assert!(task.runs.is_empty() && task.passes.is_empty());
12644        assert_eq!(task.attempts, 0);
12645    }
12646
12647    #[test]
12648    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12649        let mut task = Task::new(
12650            "recover work".into(),
12651            "recover work".into(),
12652            PathBuf::from("/repo"),
12653            crate::queue::Source::Human,
12654        );
12655        let mut run = run_state(RunStatus::Superseded);
12656        run.candidates.clear();
12657        task.runs.push(run.id.clone());
12658        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12659        run.retired_to = Some("authority".into());
12660        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12661        run.retired_to = None;
12662        run.released_to = Some("authority".into());
12663        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12664        assert!(
12665            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12666                .unwrap()
12667                .contains("Cannot verify")
12668        );
12669        // Resuming an existing owner needs no new inventory or worktree budget.
12670        assert!(
12671            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12672                panic!("resume must not load historical attempts")
12673            })
12674            .is_none()
12675        );
12676    }
12677
12678    #[test]
12679    fn retired_resume_requires_a_valid_same_repository_authority() {
12680        let mut source = run_state(RunStatus::Blocked);
12681        let mut empty = run_state(RunStatus::Blocked);
12682        empty.retired_to = Some(source.id.clone());
12683        let runs = vec![source.id.clone(), empty.id.clone()];
12684        let resolve = |source: &RunState, empty: &RunState| {
12685            unfinished_run_with(&runs, "fixture", |id| {
12686                if id == source.id {
12687                    Ok(source.clone())
12688                } else if id == empty.id {
12689                    Ok(empty.clone())
12690                } else {
12691                    bail!("unreadable authority")
12692                }
12693            })
12694        };
12695        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12696        assert_eq!(
12697            choose_starter(None, false, resolve(&source, &empty).as_deref()),
12698            Starter::Resume(source.id.clone())
12699        );
12700        source.retired_to = Some(empty.id.clone());
12701        assert!(
12702            resolve(&source, &empty).is_none(),
12703            "cycles do not revive obsolete runs"
12704        );
12705        source.retired_to = None;
12706        source.repo = PathBuf::from("/another-repository");
12707        assert!(resolve(&source, &empty).is_none());
12708        source.repo = empty.repo.clone();
12709        source.released_to = Some("later".into());
12710        assert!(resolve(&source, &empty).is_none());
12711        empty.retired_to = Some("unlisted-run".into());
12712        assert!(resolve(&source, &empty).is_none());
12713    }
12714
12715    #[test]
12716    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12717        // A task whose history holds an *older* run that still looks
12718        // resumable (say, a competition `Runner::review` was started
12719        // alongside after that older run went `Stalled`) and a *newest* run
12720        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
12721        // on this task must mean a fresh competition — falling back to the
12722        // stale, superseded `Stalled` run instead would resurrect history
12723        // nothing asked to revisit and silently defeat the requeue.
12724        let mut older_stalled = RunState::new(
12725            PathBuf::from("/repo"),
12726            "main".to_owned(),
12727            "abc1234def".to_owned(),
12728            "add retries".to_owned(),
12729            Config::default(),
12730        );
12731        older_stalled.status = RunStatus::Stalled;
12732
12733        let mut newest_exhausted = RunState::new(
12734            PathBuf::from("/repo"),
12735            "main".to_owned(),
12736            "abc1234def".to_owned(),
12737            "add retries".to_owned(),
12738            Config::default(),
12739        );
12740        newest_exhausted.status = RunStatus::Blocked;
12741        newest_exhausted.config.graph.review_rounds = 1;
12742        newest_exhausted.reviews = vec![review_round(1)];
12743
12744        assert_eq!(
12745            unfinished_run_with(
12746                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12747                "t",
12748                |_| Ok(newest_exhausted.clone())
12749            ),
12750            None,
12751            "the newest run is exhausted, so nothing here is worth resuming - \
12752             least of all the older, already-superseded run"
12753        );
12754    }
12755
12756    #[test]
12757    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12758        assert_eq!(
12759            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12760                Err(anyhow::anyhow!("fixture is absent"))
12761            }),
12762            None
12763        );
12764    }
12765
12766    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12767        let mut q = ask::Question::new(
12768            run.to_owned(),
12769            "implement".to_owned(),
12770            "impl-A".to_owned(),
12771            "continue?".to_owned(),
12772            String::new(),
12773            vec!["resume で続行する".to_owned(), "other".to_owned()],
12774        );
12775        q.actions.insert("resume で続行する".to_owned(), action);
12776        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12777            .unwrap();
12778        q
12779    }
12780
12781    fn held_task_with(run: &str) -> Task {
12782        let mut t = task();
12783        t.runs = vec![run.to_owned()];
12784        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
12785        t
12786    }
12787
12788    fn resume_action(run: &str) -> ask::ChoiceAction {
12789        ask::ChoiceAction::Resume { run: run.into() }
12790    }
12791
12792    #[test]
12793    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
12794        let home = crate::run::test_home();
12795        for parked in [false, true] {
12796            let mut t = task();
12797            t.start("A".into());
12798            t.start("B".into());
12799            assert_eq!(t.runs, vec!["A", "B"]);
12800            t.start("A".into());
12801            let mut resumed = run_state(RunStatus::Blocked);
12802            resumed.id = "A".into();
12803            resumed.parked = parked;
12804            resumed.driver_exited = true;
12805            t.hold_machine(Some("resumed run stopped".into()));
12806            let q = action_question("A", resume_action("A"));
12807            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12808            assert_eq!(
12809                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
12810                    assert_eq!(id, "A");
12811                    Ok(resumed.clone())
12812                }),
12813                ActionDecision::Resume("A".into())
12814            );
12815            assert_eq!(
12816                action_standing(&t, &action_question("B", resume_action("B"))),
12817                ActionStanding::Stale
12818            );
12819            t.release_operator("cli", None);
12820            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
12821                assert_eq!(id, "A");
12822                Ok(resumed.clone())
12823            });
12824            assert_eq!(
12825                choose_starter(None, false, unfinished.as_deref()),
12826                Starter::Resume("A".into())
12827            );
12828            assert_eq!(t.runs, vec!["B", "A"]);
12829        }
12830    }
12831
12832    #[test]
12833    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
12834        let home = crate::run::test_home();
12835        let mut state = crate::land::tests::repair_state(true, true);
12836        state.status = RunStatus::Landing;
12837        state.parked = true;
12838        state.driver_exited = true;
12839        let mut q = ask::Question::new(
12840            state.id.clone(),
12841            land::APPROVAL_NODE.into(),
12842            "land".into(),
12843            "Merge?".into(),
12844            String::new(),
12845            vec![land::APPROVE.into(), land::HOLD.into()],
12846        );
12847        q.id = state.id.clone();
12848        state.land_approval = Some(crate::run::LandApproval {
12849            question: q.id.clone(),
12850            head: "current-head".into(),
12851        });
12852        assert!(land::upgrade_repair_choice(&mut q, &state));
12853        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12854        let mut task = held_task_with(&state.id);
12855        task.status = TaskStatus::Parked;
12856        assert_eq!(
12857            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12858            ActionDecision::Resume(state.id.clone())
12859        );
12860        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12861        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
12862        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
12863        assert_eq!(
12864            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12865            ActionDecision::Resume(state.id.clone()),
12866            "a repair answer newer than the manual hold resumes the existing owner"
12867        );
12868        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12869        for answered_at in [q.answered_at, None] {
12870            let mut older = q.clone();
12871            older.answered_at = answered_at;
12872            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
12873                panic!("a later manual hold must prevent dispatch")
12874            });
12875            let ActionDecision::Refuse(reason) = refused else {
12876                panic!("expected an actionable refusal, got {refused:?}");
12877            };
12878            assert!(reason.contains("later operator decision"));
12879            assert!(reason.contains(&format!("magi task release {}", task.id)));
12880        }
12881        task.operator_decided_at = None;
12882        let mut superseded = state.clone();
12883        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
12884        assert_eq!(
12885            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
12886            ActionDecision::Stale
12887        );
12888        for case in 1..4 {
12889            let mut changed = state.clone();
12890            match case {
12891                1 => changed.status = RunStatus::Blocked,
12892                2 => changed.released_to = Some("new-owner".into()),
12893                _ => changed.land_approval.as_mut().unwrap().head.clear(),
12894            }
12895            assert!(matches!(
12896                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
12897                ActionDecision::Refuse(_)
12898            ));
12899        }
12900        assert!(matches!(
12901            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
12902                "missing owner"
12903            )),
12904            ActionDecision::Refuse(_)
12905        ));
12906        task.runs.push("replacement".into());
12907        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12908        assert_eq!(
12909            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
12910                "old owner must not load"
12911            )),
12912            ActionDecision::Stale
12913        );
12914    }
12915
12916    #[test]
12917    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
12918        let mut state = crate::land::tests::repair_state(true, true);
12919        state.status = RunStatus::Landing;
12920        state.parked = true;
12921        state.driver_exited = true;
12922        let mut q = ask::Question::new(
12923            state.id.clone(),
12924            land::APPROVAL_NODE.into(),
12925            "land".into(),
12926            "Merge?".into(),
12927            String::new(),
12928            vec![land::APPROVE.into(), land::HOLD.into()],
12929        );
12930        q.id = state.id.clone();
12931        state.land_approval = Some(crate::run::LandApproval {
12932            question: q.id.clone(),
12933            head: "current-head".into(),
12934        });
12935        state.save().unwrap();
12936        land::upgrade_repair_choice(&mut q, &state);
12937        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12938        Questions::open().put(&mut q).unwrap();
12939        let tmp = tempfile::tempdir().unwrap();
12940        let queue = Queue::at(tmp.path().join("queue"));
12941        let mut task = held_task_with(&state.id);
12942        task.status = TaskStatus::Parked;
12943        queue.put(&mut task).unwrap();
12944        let empty = Arc::new(tokio::sync::Semaphore::new(0));
12945        let free = Arc::new(tokio::sync::Semaphore::new(1));
12946        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
12947        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
12948        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
12949        assert!(claim.permit.is_some());
12950        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
12951        drop(claim);
12952        Questions::open()
12953            .update(&q.id, |q| {
12954                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
12955                Ok(())
12956            })
12957            .unwrap();
12958        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
12959        assert!(claim.permit.is_none());
12960        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
12961    }
12962
12963    #[test]
12964    fn decide_action_resumes_only_the_latest_resumable_run() {
12965        let home = crate::run::test_home();
12966        let t = held_task_with("r1");
12967        let q = action_question("r1", resume_action("r1"));
12968        let load = |s: RunState| move |_: &str| Ok(s);
12969        assert_eq!(
12970            decide_action(
12971                &home,
12972                &t,
12973                &q,
12974                &PHRASES_EN,
12975                load(run_state(RunStatus::Blocked))
12976            ),
12977            ActionDecision::Resume("r1".into())
12978        );
12979        // Not the latest run of the task.
12980        let q_other = action_question("r1", resume_action("r0"));
12981        assert!(matches!(
12982            decide_action(
12983                &home,
12984                &t,
12985                &q_other,
12986                &PHRASES_EN,
12987                load(run_state(RunStatus::Blocked))
12988            ),
12989            ActionDecision::Refuse(_)
12990        ));
12991        // A finished run cannot make progress.
12992        assert!(matches!(
12993            decide_action(
12994                &home,
12995                &t,
12996                &q,
12997                &PHRASES_EN,
12998                load(run_state(RunStatus::Ready))
12999            ),
13000            ActionDecision::Refuse(_)
13001        ));
13002        // A released one either.
13003        let mut released = run_state(RunStatus::Blocked);
13004        released.released_to = Some("elsewhere".into());
13005        assert!(matches!(
13006            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
13007            ActionDecision::Refuse(_)
13008        ));
13009        // Unreadable state is a refusal, never a fresh competition.
13010        assert!(matches!(
13011            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
13012            ActionDecision::Refuse(_)
13013        ));
13014    }
13015
13016    #[test]
13017    fn decide_action_ignores_a_question_about_an_earlier_run() {
13018        let home = crate::run::test_home();
13019        let mut t = held_task_with("r1");
13020        t.runs.push("r2".to_owned());
13021        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13022        assert_eq!(
13023            decide_action(
13024                &home,
13025                &t,
13026                &action_question("r1", ask::ChoiceAction::Done),
13027                &PHRASES_EN,
13028                never
13029            ),
13030            ActionDecision::Stale
13031        );
13032    }
13033
13034    #[test]
13035    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
13036        let home = crate::run::test_home();
13037        let mut t = held_task_with("r1");
13038        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13039        assert_eq!(
13040            decide_action(
13041                &home,
13042                &t,
13043                &action_question("r1", ask::ChoiceAction::Requeue),
13044                &PHRASES_EN,
13045                never
13046            ),
13047            ActionDecision::Requeue
13048        );
13049        let done_q = action_question("r1", ask::ChoiceAction::Done);
13050        assert_eq!(
13051            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13052            ActionDecision::Done
13053        );
13054        t.mark_action_applied(&done_q.id);
13055        assert_eq!(
13056            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13057            ActionDecision::Skip
13058        );
13059
13060        // A plain answer (no action for that label) does nothing.
13061        let mut plain = action_question("r1", ask::ChoiceAction::Done);
13062        plain.actions.clear();
13063        assert_eq!(
13064            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
13065            ActionDecision::Skip
13066        );
13067        // A running task is left alone.
13068        let mut running = held_task_with("r1");
13069        running.status = TaskStatus::Running;
13070        assert_eq!(
13071            decide_action(
13072                &home,
13073                &running,
13074                &action_question("r1", ask::ChoiceAction::Done),
13075                &PHRASES_EN,
13076                never
13077            ),
13078            ActionDecision::Skip
13079        );
13080    }
13081
13082    #[test]
13083    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
13084        crate::run::pin_test_home();
13085        for legacy in [false, true] {
13086            let dir = tempfile::tempdir().unwrap();
13087            let queue = Queue::at(dir.path().join("queue"));
13088            let questions = Questions::at(dir.path().join("questions"));
13089            let run = "20260101-000000-hold";
13090            let mut task = held_task_with(run);
13091            task.status = TaskStatus::Parked;
13092            let mut q = ask::Question::new(
13093                run.into(),
13094                land::APPROVAL_NODE.into(),
13095                "land".into(),
13096                "Repair?".into(),
13097                String::new(),
13098                vec![land::REPAIR.into()],
13099            );
13100            q.actions.insert(land::REPAIR.into(), resume_action(run));
13101            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13102            // Deterministically order the answer before the actual manual hold.
13103            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13104            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
13105            questions.put(&mut q).unwrap();
13106            task.hold_manual(Some("Keep this PR paused".into()));
13107            if legacy {
13108                task.hold_source = None;
13109            }
13110            queue.put(&mut task).unwrap();
13111
13112            apply_task_choice_actions(&queue, &questions, dir.path());
13113            let after = queue.get(&task.id).unwrap();
13114            assert!(after.operator_held());
13115            assert_eq!(after.hold_source, task.hold_source);
13116            assert_eq!(after.operator_decided_at, task.operator_decided_at);
13117            assert_eq!(after.runs, task.runs);
13118            assert_eq!(after.instruction, task.instruction);
13119            assert!(after.resume_override.is_none());
13120            assert!(after.action_applied(&q.id));
13121            let reason = after.hold_reason.as_deref().unwrap();
13122            assert!(reason.starts_with("Keep this PR paused"));
13123            assert!(reason.contains("later operator decision"));
13124            assert!(reason.contains(&format!("magi task release {}", task.id)));
13125
13126            for recovery in [
13127                crate::conduct::Recovery::Review,
13128                crate::conduct::Recovery::Requeue,
13129            ] {
13130                crate::conduct::apply(
13131                    &queue,
13132                    &questions,
13133                    &crate::conduct::Verdict {
13134                        decisions: vec![crate::conduct::Decision {
13135                            id: task.id.clone(),
13136                            recovery: Some(recovery),
13137                            ..Default::default()
13138                        }],
13139                    },
13140                )
13141                .unwrap();
13142            }
13143            // Reconciliation is idempotent, and automatic recovery cannot
13144            // reopen this owner after it observes the rejected repair answer.
13145            apply_task_choice_actions(&queue, &questions, dir.path());
13146            let still_held = queue.get(&task.id).unwrap();
13147            assert!(still_held.operator_held());
13148            assert_eq!(still_held.hold_reason, after.hold_reason);
13149            assert_eq!(still_held.runs, task.runs);
13150            assert!(still_held.review_branch.is_none());
13151            assert!(!still_held.fresh_start);
13152            assert!(queue.next_runnable().is_none());
13153        }
13154    }
13155
13156    #[test]
13157    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
13158        for held in [false, true] {
13159            for retry in [false, true] {
13160                let dir = tempfile::tempdir().unwrap();
13161                let queue = Queue::at(dir.path().join("queue"));
13162                let questions = Questions::at(dir.path().join("questions"));
13163                let home = dir.path().join("home");
13164                let mut t = task();
13165                if held {
13166                    t.hold_machine(Some("driver state unknown".into()));
13167                }
13168                queue.put(&mut t).unwrap();
13169                let verdict = serde_json::from_value(serde_json::json!({
13170                    "decisions": [{
13171                        "id": t.id,
13172                        "question": "Driver state unknown; retry the checks or hold?",
13173                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
13174                        "actions": {
13175                            "daemon: recheck and retry": {"do": "requeue"},
13176                            "daemon: hold the task": {"do": "hold"}
13177                        }
13178                    }]
13179                }))
13180                .unwrap();
13181                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
13182                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13183                let mut q = questions.list().pop().unwrap();
13184                let choice = if retry {
13185                    "daemon: recheck and retry"
13186                } else {
13187                    "daemon: hold the task"
13188                };
13189                assert_eq!(q.actions.len(), 2);
13190                q.answer(ask::Answer::Choice(choice.into())).unwrap();
13191                questions.put(&mut q).unwrap();
13192
13193                // A Web answer does not remove the deputy's fresh lease.
13194                questions.beat(&q.id, ask::WaiterKind::Deputy);
13195                for _ in 0..2 {
13196                    resolve_blockers(&queue, &questions);
13197                    apply_task_choice_actions(&queue, &questions, &home);
13198                    let waiting = queue.get(&t.id).unwrap();
13199                    assert_eq!(waiting.status, TaskStatus::Blocked);
13200                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
13201                    assert!(waiting.answers.is_empty());
13202                    assert!(!waiting.action_applied(&q.id));
13203                    assert!(runnable(&queue).is_empty());
13204                    let free = Arc::new(tokio::sync::Semaphore::new(1));
13205                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
13206                }
13207                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13208
13209                // Releasing the blocker and applying the operation share one save.
13210                resolve_blockers(&queue, &questions);
13211                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13212                apply_task_choice_actions(&queue, &questions, &home);
13213                let after = queue.get(&t.id).unwrap();
13214                assert_eq!(
13215                    after.status,
13216                    if retry {
13217                        TaskStatus::Queued
13218                    } else {
13219                        TaskStatus::Held
13220                    }
13221                );
13222                assert!(after.action_applied(&q.id));
13223                assert_eq!(after.operator_held(), !retry);
13224                assert_eq!(after.answers.len(), 1);
13225
13226                // A later operator decision must not replay this answer.
13227                let mut changed = after;
13228                if retry {
13229                    changed.hold_manual(Some("later hold".into()));
13230                } else {
13231                    changed.release_operator("test", None);
13232                }
13233                let expected = changed.status;
13234                queue.put(&mut changed).unwrap();
13235                apply_task_choice_actions(&queue, &questions, &home);
13236                assert_eq!(queue.get(&t.id).unwrap().status, expected);
13237            }
13238        }
13239    }
13240
13241    #[test]
13242    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
13243        let dir = tempfile::tempdir().unwrap();
13244        let queue = Queue::at(dir.path().join("queue"));
13245        let questions = Questions::at(dir.path().join("questions"));
13246        let home = dir.path().join("home");
13247        let mut state = run_state(RunStatus::Blocked);
13248        state.id = "20260101-000000-act1".to_owned();
13249        state.save_under(&home).unwrap();
13250
13251        let mut t = held_task_with(&state.id);
13252        queue.put(&mut t).unwrap();
13253        let mut q = action_question(&state.id, resume_action(&state.id));
13254        questions.put(&mut q).unwrap();
13255
13256        apply_task_choice_actions(&queue, &questions, &home);
13257        let after = queue.get(&t.id).unwrap();
13258        assert_eq!(after.status, TaskStatus::Queued);
13259        assert!(!after.fresh_start);
13260        assert!(after.action_applied(&q.id));
13261        let pin = after.resume_override.clone().unwrap();
13262        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
13263        assert!(pin.forced);
13264
13265        // Held again later: the same answer does not release it a second time.
13266        let mut again = queue.get(&t.id).unwrap();
13267        again.hold_machine(Some("later".into()));
13268        queue.put(&mut again).unwrap();
13269        apply_task_choice_actions(&queue, &questions, &home);
13270        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13271    }
13272
13273    #[test]
13274    fn a_delivered_answer_is_still_acted_on_exactly_once() {
13275        let dir = tempfile::tempdir().unwrap();
13276        let queue = Queue::at(dir.path().join("queue"));
13277        let questions = Questions::at(dir.path().join("questions"));
13278        let home = dir.path().join("home");
13279        let mut state = run_state(RunStatus::Blocked);
13280        state.id = "20260101-000000-act2".to_owned();
13281        state.save_under(&home).unwrap();
13282
13283        let mut t = held_task_with(&state.id);
13284        queue.put(&mut t).unwrap();
13285        let mut q = action_question(&state.id, resume_action(&state.id));
13286        q.answer_delivered = true;
13287        questions.put(&mut q).unwrap();
13288
13289        // Delivered, and the agent then died: the task is still held, so the
13290        // chosen action applies.
13291        apply_task_choice_actions(&queue, &questions, &home);
13292        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13293        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
13294
13295        // Held again: the same answer does nothing a second time.
13296        let mut again = queue.get(&t.id).unwrap();
13297        again.hold_machine(Some("later".into()));
13298        queue.put(&mut again).unwrap();
13299        apply_task_choice_actions(&queue, &questions, &home);
13300        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13301    }
13302
13303    #[test]
13304    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
13305        let dir = tempfile::tempdir().unwrap();
13306        let queue = Queue::at(dir.path().join("queue"));
13307        let questions = Questions::at(dir.path().join("questions"));
13308        let home = dir.path().join("home");
13309        let mut state = run_state(RunStatus::Blocked);
13310        state.id = "20260101-000000-act3".to_owned();
13311        state.save_under(&home).unwrap();
13312        let mut t = held_task_with(&state.id);
13313        queue.put(&mut t).unwrap();
13314        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
13315        questions.put(&mut q).unwrap();
13316
13317        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
13318        apply_task_choice_actions(&queue, &questions, &home);
13319        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13320
13321        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13322        apply_task_choice_actions(&queue, &questions, &home);
13323        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13324    }
13325
13326    #[test]
13327    fn action_standing_tells_the_reasons_apart() {
13328        let mut t = held_task_with("r1");
13329        let q = action_question("r1", ask::ChoiceAction::Requeue);
13330        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13331        let mut plain = q.clone();
13332        plain.actions.clear();
13333        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
13334
13335        // Applied wins over everything, even a running task.
13336        t.mark_action_applied(&q.id);
13337        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
13338
13339        // A newer attempt running: the old question is Stale, not Busy.
13340        let mut t = held_task_with("r1");
13341        t.start("r2".to_owned());
13342        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
13343        // The same question about the latest run just waits.
13344        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
13345        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13346        t.status = TaskStatus::Blocked;
13347        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13348
13349        // A conductor question is keyed by the task, never stale.
13350        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
13351        c.node = crate::conduct::NODE.to_owned();
13352        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
13353        assert!(!ActionStanding::Busy.daemon_owns());
13354    }
13355
13356    #[test]
13357    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
13358        let dir = tempfile::tempdir().unwrap();
13359        let queue = Queue::at(dir.path().join("queue"));
13360        let questions = Questions::at(dir.path().join("questions"));
13361        let home = dir.path().join("home");
13362        let mut state = run_state(RunStatus::Blocked);
13363        state.id = "20260101-000000-act4".to_owned();
13364        state.save_under(&home).unwrap();
13365        let mut t = held_task_with(&state.id);
13366        t.status = TaskStatus::Running;
13367        queue.put(&mut t).unwrap();
13368        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13369        q.cwd = Some(dir.path().display().to_string());
13370        questions.put(&mut q).unwrap();
13371
13372        // While the task runs the daemon will not act, so the waiter still
13373        // delivers the word to the dead asker's seat ...
13374        let running = queue.get(&t.id).unwrap();
13375        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13376        assert!(matches!(
13377            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13378            crate::waiter::Action::Deliver(_)
13379        ));
13380        // ... and the daemon waits while the task runs, then applies once.
13381        apply_task_choice_actions(&queue, &questions, &home);
13382        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13383        let mut back = queue.get(&t.id).unwrap();
13384        back.hold_machine(Some("later".into()));
13385        queue.put(&mut back).unwrap();
13386        apply_task_choice_actions(&queue, &questions, &home);
13387        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13388        let mut again = queue.get(&t.id).unwrap();
13389        again.hold_machine(Some("again".into()));
13390        queue.put(&mut again).unwrap();
13391        apply_task_choice_actions(&queue, &questions, &home);
13392        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13393    }
13394}