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(format!("Base synchronization remains stopped. {} A release without a new owner approval grants no additional synchronization budget and starts no replacement competition.", held.base_sync_next_action())));
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
4353            .recovery_exhausted(
4354                &head,
4355                &inputs,
4356                task.attempt_limit
4357                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4358            )
4359            .filter(|_| {
4360                !task.repair_grants.last().is_some_and(|receipt| {
4361                    RunState::load(&receipt.request.run)
4362                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4363                })
4364            })
4365        {
4366            task.hold_unrequested_retry(Some(reason));
4367            record(queue, task);
4368            return Vec::new();
4369        }
4370        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4371    }
4372
4373    // The free-space gate, checked *before* anything is minted: a task that
4374    // waits out a full disk costs nothing yet, and must not spend an attempt
4375    // or start a run the machine cannot finish. Held tasks stay in the list
4376    // for the human to see, and `magi task release` re-queues them when space
4377    // comes back - the same recovery as any other hold. A volume whose free
4378    // space cannot be measured closes the gate too: starting a run blind on a
4379    // disk that may be full is how the machine ends up with 6.7 GB free.
4380    if let Some(reason) = disk_gate(&repo, &config) {
4381        task.notice_cause("disk-space", None, None);
4382        task.last_error = Some(reason.clone());
4383        task.hold_machine(Some(reason.clone()));
4384        record(queue, task);
4385        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4386        // Stable wording - the free-space figures live in the task's hold
4387        // reason, and changing numbers would relight the bell every poll.
4388        notices::raise(
4389            Notice::warn(
4390                &format!("disk:{}", repo.display()),
4391                format!("Task {} held for want of free disk space: {reason}. Free some, then release it from the queue.", task.id),
4392            )
4393            .link(Link::Task {
4394                id: task.id.clone(),
4395            }),
4396        );
4397        return Vec::new();
4398    }
4399
4400    // A resumable run of this task is carried on, never re-competed. The
4401    // candidates are built and paid for, and a fresh competition races a
4402    // second implementation against them.
4403    //
4404    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4405    // started 3cbf on the same task a moment later, duplicating two and a
4406    // half hours of agent work. Then b25f stalled on a judge that timed out
4407    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4408    // was to blame for - and 4043 started **one second** later, buying three
4409    // fresh implementations to reach the same panel. `RunStatus::resumable`
4410    // rather than `!done()` is what catches the second case: a stall is
4411    // terminal, and its cheap recovery re-asks only the absent seats.
4412    //
4413    // A load failure is warned about rather than silently read as "not
4414    // resumable": the alternative is exactly what let a schema mismatch on
4415    // run `eba2` fall through to a full re-competition with nobody told why.
4416    // `crate::conduct` is what actually offers a better answer than
4417    // `Runner::start` here (see `Recovery::Review`), once this task's next
4418    // failure shows it up as `held`/`failed` with the run state unreadable.
4419    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
4420    // branch survived, and this reopens exactly that branch as a
4421    // review-only pass rather than resuming or competing again. Consumed
4422    // (cleared) here whichever way this goes, so it never outlives this one
4423    // attempt - see `queue::Task::review_branch`.
4424    let review_branch = take_review_branch(task, previous.as_ref());
4425    let branch_exists = match &review_branch {
4426        Some(branch) => crate::git::branch_exists(&repo, branch)
4427            .await
4428            .unwrap_or(false),
4429        None => false,
4430    };
4431    // An explicit `magi review <branch>` is reviewed whatever happens to the
4432    // branch unless an explicit implementer change requires fresh work. An
4433    // unfinished run of the same task still wins, so a retry resumes.
4434    let proposed = review_retry_starter(
4435        task,
4436        previous.as_ref(),
4437        review_branch.as_deref(),
4438        branch_exists,
4439        unfinished.as_deref(),
4440    );
4441    let retry_selected = task.replacement.is_some()
4442        && task.resumption.is_some()
4443        && !task.fresh_start
4444        && previous.as_ref().is_some_and(|run| {
4445            run.replaces.is_some()
4446                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4447                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4448        });
4449    let stop_pin = task
4450        .resume_override
4451        .as_ref()
4452        .filter(|pin| {
4453            Questions::open().get(&pin.question_id).is_ok_and(|q| {
4454                q.node == land::APPROVAL_NODE
4455                    && q.resolution()
4456                        .as_deref()
4457                        .is_some_and(crate::merge_decision::stops)
4458            })
4459        })
4460        .and_then(|pin| pin.pinned_run.clone());
4461    let granted_run = task.repair_grants.last().and_then(|receipt| {
4462        let state = RunState::load(&receipt.request.run).ok()?;
4463        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
4464    });
4465    let starter = if let Some(run) = granted_run {
4466        Starter::Resume(run)
4467    } else if let Some(owner) = &public_owner {
4468        Starter::Resume(owner.id.clone())
4469    } else if let Some(run) = stop_pin {
4470        // Stop actions resume their exact owner even after seat-count edits;
4471        // they must never fall through to implementation or a takeover.
4472        Starter::Resume(run)
4473    } else if retry_selected {
4474        Starter::Resume(previous.as_ref().unwrap().id.clone())
4475    } else if let Some(selected) = &task.pr_recovery {
4476        if selected.check_task(&task.id, &task.instruction).is_ok() {
4477            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4478        } else {
4479            Starter::Review(selected.branch.clone())
4480        }
4481    } else {
4482        starter_with_implementers(task, previous.as_ref(), proposed)
4483    };
4484    // An explicit resume pin must never degrade into a new competition or
4485    // takeover, including when its run stops being eligible after the answer.
4486    if let Some(pin) = &task.resume_override
4487        && let Some(run) = &pin.pinned_run
4488        && starter != Starter::Resume(run.clone())
4489    {
4490        let run = run.clone();
4491        task.notice_cause("resume-owner", Some(&run), None);
4492        task.hold_machine(Some(format!(
4493            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4494            task.id
4495        )));
4496        record(queue, task);
4497        return Vec::new();
4498    }
4499    if task.replacement.is_some()
4500        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4501        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4502    {
4503        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()));
4504        record(queue, task);
4505        return Vec::new();
4506    }
4507    if let Some(reason) = retained_attempt_hold(
4508        task,
4509        &starter,
4510        config.disk.retained_attempt_limit,
4511        RunState::load,
4512    ) {
4513        // The review choice was consumed above. Preserve it across this hold
4514        // so a later release cannot silently become a fresh implementation.
4515        if let Starter::Review(branch) = &starter {
4516            task.review_branch = Some(branch.clone());
4517        }
4518        task.hold_unrequested_retry(Some(reason));
4519        record(queue, task);
4520        return Vec::new();
4521    }
4522    // Absolute paths of the files the task was filed with, re-read from the
4523    // task now so a file attached while it was held reaches a resumed run
4524    // too. A stored name whose file has gone is an error before any agent is
4525    // paid for, never a silent omission the implementer cannot notice.
4526    let attachments = match task_attachments(queue, task) {
4527        Ok(a) => a,
4528        Err(e) => {
4529            task.attempts += 1;
4530            task.fail_startup_target(
4531                "startup-attachments",
4532                e.name.clone(),
4533                format!("{start_failed}{e:#}"),
4534                opts.max_attempts,
4535            );
4536            record(queue, task);
4537            return Vec::new();
4538        }
4539    };
4540    let startup_pause = stop.pause();
4541    let startup_interrupt = interrupt_pause.clone();
4542    let wait = crate::repo_lock::WaitPolicy::new(
4543        Duration::from_secs(config.graph.timeout_resource_wait),
4544        move || startup_pause.parked() || startup_interrupt.parked(),
4545    );
4546    // Startup includes review takeover and recovery. Do not embed its large
4547    // future in both the wait scope and the surrounding attempt stack frame.
4548    let started = wait.scope(Box::pin(async { match &starter {
4549        Starter::Review(_) if task.pr_recovery.is_some() => {
4550            let selected = task.pr_recovery.clone().expect("selected recovery");
4551            match selected.check_task(&task.id, &task.instruction) {
4552                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4553                    .await
4554                    .map(|mut r| {
4555                        r.state.attachments = attachments.clone();
4556                        r
4557                    }),
4558                Err(e) => Err(e),
4559            }
4560        }
4561        Starter::Review(branch) => {
4562            tracing::info!(
4563                "task {} reopens `{branch}` as a review-only pass",
4564                task.short()
4565            );
4566            // Every earlier attempt is superseded by the one being minted
4567            // now, so a branch one of them still holds may be taken over.
4568            let takeover = crate::handover::Takeover {
4569                earlier: task.earlier_attempts().to_vec(),
4570                home: crate::run::home(),
4571                choice: take_divergence_answer(branch, &config.merge.remote, task),
4572                task_instruction: Some(instruction_for(task)),
4573            };
4574            Runner::review_taking_over(
4575                &repo,
4576                branch,
4577                config,
4578                Some(takeover),
4579                crate::run::Origin::queue(&task.id),
4580            )
4581            .await
4582        }
4583        Starter::Resume(id) => {
4584            tracing::info!("resuming run {id} rather than competing again");
4585            Runner::resume(id).and_then(|mut r| {
4586                if retry_selected {
4587                    // The explicit queue release retries this same pinned
4588                    // implementation, preserving the attempt and worktrees.
4589                    for candidate in &mut r.state.candidates {
4590                        candidate.failed = None;
4591                        candidate.empty = false;
4592                        candidate.commits = 0;
4593                    }
4594                    r.state.status = RunStatus::Implementing;
4595                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4596                }
4597                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4598                    r.state.sources = task.sources.clone();
4599                }
4600                if r.state.prep_failure.is_some() {
4601                    let approval = task
4602                        .resumption
4603                        .as_ref()
4604                        .context("preparation retry requires an explicit task release")?;
4605                    r.retry_preparation(approval.at)?;
4606                }
4607                if let Some(instruction) =
4608                    prepare_instruction(&starter, Some(&r.state.instruction), task)
4609                {
4610                    r.state.instruction = instruction;
4611                }
4612                r.state.attachments = attachments.clone();
4613                if task.replacement.is_some() {
4614                    r.state.config.merge.mode = MergeMode::Pr;
4615                    r.state.config.graph.land_approval = true;
4616                }
4617                // Replacements publish a new PR and ask again. Selected PR
4618                // recoveries keep their saved disposition; ordinary runs can
4619                // retain the task's merge override.
4620                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4621                    .overrides
4622                    .as_ref()
4623                    .and_then(|o| o.merge.as_deref())
4624                    .and_then(|m| merge_mode(m).ok())
4625                {
4626                    r.state.config.merge.mode = mode;
4627                }
4628                Ok(r)
4629            })
4630        }
4631        Starter::Start => {
4632            if let Some(branch) = &review_branch {
4633                tracing::warn!(
4634                    "conductor chose review for task {} but branch `{branch}` no longer \
4635                     exists; requeuing as a fresh competition instead",
4636                    task.short()
4637                );
4638            }
4639            let instruction = prepare_instruction(&starter, None, task)
4640                .unwrap_or_else(|| task.instruction.clone());
4641            Runner::start_naming(
4642                &repo,
4643                instruction,
4644                &task.title,
4645                config,
4646                crate::run::Origin::queue(&task.id),
4647            )
4648            .await
4649            .map(|mut r| {
4650                r.state.attachments = attachments.clone();
4651                r.state.sources = task.sources.clone();
4652                r
4653            })
4654        }
4655    }})).await;
4656    if let Err(error) = &started
4657        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
4658    {
4659        task.record_startup_failure(failure.clone());
4660    }
4661    let mut runner = match started {
4662        Ok(r) => r,
4663        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4664            task.last_error = Some(e.to_string());
4665            if stop.parking() || interrupt_pause.parked() {
4666                let attempts = task.attempts;
4667                task.park(e.to_string());
4668                // Startup has not spent an attempt to refund.
4669                task.attempts = attempts;
4670            } else {
4671                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4672            }
4673            record(queue, task);
4674            return Vec::new();
4675        }
4676        // A branch an earlier attempt still holds and magi will not release
4677        // by itself is the operator's call, not a failed attempt: hold the
4678        // task with the reason, spend nothing, and say so on the bell.
4679        Err(e) if task.pr_recovery.is_some() => {
4680            task.startup_notice_cause("startup-public-head");
4681            task.attempts += 1;
4682            task.last_error = Some(format!("{start_failed}{e:#}"));
4683            task.hold_unrequested_retry(Some(format!(
4684                "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."
4685            )));
4686            record(queue, task);
4687            return Vec::new();
4688        }
4689        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4690            let detail = match e.downcast_ref::<crate::handover::Refused>() {
4691                Some(r) => (p.handover_refused)(r),
4692                None => format!("{e:#}"),
4693            };
4694            task.startup_notice_cause("startup-handover");
4695            let reason = format!("{start_failed}{detail}");
4696            task.last_error = Some(reason.clone());
4697            // Consumed above by `take`; keep it so the released task retries
4698            // as a review of this same branch.
4699            let branch = match &starter {
4700                Starter::Review(branch) => Some(branch.clone()),
4701                _ => None,
4702            };
4703            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
4704            // one page; the guidance rides in the reason, fixed per state so a
4705            // re-put never changes the wording and relights it.
4706            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4707            record(queue, task);
4708            tracing::warn!(
4709                "holding {} for a branch it cannot take over: {e:#}",
4710                task.short()
4711            );
4712            return Vec::new();
4713        }
4714        // A branch that differs between here and the remote in ways magi
4715        // cannot prove are the same change is a decision for the owner, not a
4716        // failed attempt: ask with both sides laid out, spend no attempt, and
4717        // let the answer requeue the task.
4718        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4719            let d = e
4720                .downcast_ref::<crate::reconcile::Diverged>()
4721                .expect("checked by the guard");
4722            let mut q = ask::Question::new(
4723                task.id.clone(),
4724                crate::reconcile::NODE.to_owned(),
4725                crate::reconcile::SEAT.to_owned(),
4726                d.summary(),
4727                d.detail(),
4728                d.choices(),
4729            );
4730            match Questions::open().put(&mut q) {
4731                Ok(()) => {
4732                    task.last_error = Some(format!("{e:#}"));
4733                    // Consumed above by `take`; the answer has to reach a review
4734                    // of this same branch, so keep pointing the task at it.
4735                    task.review_branch = Some(d.branch.clone());
4736                    task.review_instruction = Some(task.instruction.clone());
4737                    task.block(vec![q.id.clone()], Some(d.summary()));
4738                }
4739                Err(put) => {
4740                    tracing::warn!("could not file the divergence question: {put:#}");
4741                    task.attempts += 1;
4742                    task.fail_startup(
4743                        "startup-question-store",
4744                        format!("{start_failed}{e:#}"),
4745                        opts.max_attempts,
4746                    );
4747                }
4748            }
4749            record(queue, task);
4750            return Vec::new();
4751        }
4752        Err(e) => {
4753            // The answer was stale and nothing was applied: keep pointing at
4754            // the branch so the next attempt asks again against its new tips.
4755            // Nothing went wrong with the task, so no attempt is spent: a
4756            // budget one short of its limit must not hold it instead of
4757            // letting the question be asked again.
4758            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4759                && let Starter::Review(branch) = &starter
4760            {
4761                task.review_branch = Some(branch.clone());
4762                task.review_instruction = Some(task.instruction.clone());
4763                task.last_error = Some(format!("{start_failed}{e:#}"));
4764                task.status = crate::queue::TaskStatus::Failed;
4765                record(queue, task);
4766                return Vec::new();
4767            }
4768            task.attempts += 1;
4769            task.last_error = Some(format!("{start_failed}{e:#}"));
4770            task.startup_notice_cause("startup-source");
4771            task.hold_unrequested_retry(Some(format!(
4772                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4773            )));
4774            record(queue, task);
4775            return Vec::new();
4776        }
4777    };
4778    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4779        runner.state.recovery_config = Some(config_evidence);
4780    }
4781    if let Some(replacement) = &task.replacement {
4782        if matches!(starter, Starter::Start) {
4783            runner.state.instruction.push_str(&format!(
4784                "\n\n# Replacement review context\n{}",
4785                replacement.context
4786            ));
4787        }
4788        runner.state.replaces = Some(replacement.clone());
4789        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4790        if let Ok(mut old) = RunState::load(&replacement.run)
4791            && let Some(d) = &mut old.merge_decision
4792        {
4793            d.replacement_run = Some(runner.state.id.clone());
4794            old.event(
4795                "replacement",
4796                format!(
4797                    "replacement run {} owns the next attempt; old PR remains closed",
4798                    runner.state.id
4799                ),
4800            );
4801            if let Err(e) = old.save() {
4802                let error = runner.fail_startup("replacement-history", e);
4803                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4804                    task.record_startup_failure(failure.clone());
4805                }
4806                task.hold_manual(Some(format!(
4807                    "Could not link replacement history: {error:#}; no agents dispatched"
4808                )));
4809                record(queue, task);
4810                return Vec::new();
4811            }
4812        }
4813    }
4814    runner.state.task_instruction = Some(task.instruction.clone());
4815    // The follow-up depth is fixed now, while the task certainly exists:
4816    // deleting it later must not reset the cap (`crate::followup`).
4817    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4818    if runner.state.origin_chat.is_none() {
4819        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4820    }
4821    // A stop that means "park" reaches the graph through this handle.
4822    runner.on_pause(stop.pause());
4823    // `poll`'s interrupt scheduler reaches this one run - and no other -
4824    // through this handle. See `Pause`'s own doc for why these are never
4825    // the same one.
4826    runner.watch_interrupt(interrupt_pause);
4827
4828    // `start` has minted the run, so the task can now point at it. Persisting
4829    // `Running` before `execute` is what makes a crash mid-run legible.
4830    let run = runner.state.id.clone();
4831    let before_start = task.clone();
4832    task.start(run.clone());
4833    if let Err(error) = queue.put(task) {
4834        *task = before_start;
4835        let error = runner.fail_startup("task-start", error);
4836        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4837            task.record_startup_failure(failure.clone());
4838        }
4839        task.hold_manual(Some(format!(
4840            "Could not persist task start; no agents dispatched: {error:#}"
4841        )));
4842        record(queue, task);
4843        return Vec::new();
4844    }
4845    lock(status).current.push(Current {
4846        worker: None,
4847        task: task.id.clone(),
4848        run,
4849    });
4850
4851    // `RunState::quota` is the run's whole history across every resume, so
4852    // only what this execution added may arm the cooldown or earn a refund.
4853    let quota_before = runner.state.quota.clone();
4854    runner.state.next_pass_task_entry = true;
4855    let result = runner.execute().await;
4856    finish_attempt(
4857        opts.max_attempts,
4858        queue,
4859        task,
4860        &runner.state,
4861        &quota_before,
4862        result,
4863    )
4864}
4865
4866/// Settle `task` after its run executed: the verdict, the diagnosis, the
4867/// supersession of earlier attempts and the save. Shared by the loop and by
4868/// `magi run --resume`, so an attempt is counted one way wherever it ran.
4869/// Returns the quota losses this execution added to the run.
4870pub fn finish_attempt(
4871    max_attempts: usize,
4872    queue: &Queue,
4873    task: &mut Task,
4874    state: &RunState,
4875    quota_before: &[QuotaLoss],
4876    result: Result<()>,
4877) -> Vec<QuotaLoss> {
4878    let detail = match result {
4879        Ok(()) => describe(state),
4880        Err(e) => format!("{e:#}"),
4881    };
4882    let fresh = losses_this_attempt(quota_before, &state.quota);
4883    let verdict = Verdict {
4884        status: state.status,
4885        // A run that opened a pull request handed its work over, whatever the
4886        // gate then decided about merging it.
4887        left_pr: state.pr.is_some(),
4888        // Only a rate limit earns the task its attempt back - and only one
4889        // suffered now: a refund justified by a previous session's loss is
4890        // the same mistake as re-arming the cooldown from it. A stalled run
4891        // resumed without hitting quota again therefore spends its attempt,
4892        // like any other failure of the task's own.
4893        quota_hit: !fresh.is_empty(),
4894        // A run that parked was asked to stop; that is not a failure and must
4895        // not spend an attempt, or replacing the binary a few times would
4896        // exhaust a task's budget without an agent ever misbehaving.
4897        parked: state.parked,
4898        // A quota loss that left nothing viable is the same machine fact as a
4899        // `Stalled` quota loss; see `settle`'s doc table.
4900        no_viable_candidates: state.viable().is_empty(),
4901    };
4902    if let Some(replacement) = &state.replaces
4903        && let Some(pr) = &state.pr
4904        && let Ok(mut old) = RunState::load(&replacement.run)
4905        && let Some(d) = &mut old.merge_decision
4906    {
4907        d.replacement_pr = Some(pr.url.clone());
4908        let _ = old.save();
4909    }
4910    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4911    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4912        task.hold_unrequested_retry(Some(format!(
4913            "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.",
4914            task.short()
4915        )));
4916    }
4917    if task.status == TaskStatus::Done {
4918        supersede_prior_runs(task, &crate::run::home());
4919    }
4920    record(queue, task);
4921    tracing::info!(
4922        "task {} is {} after run {} ({})",
4923        task.short(),
4924        task.status.as_str(),
4925        state.short(),
4926        label(state.status)
4927    );
4928    fresh
4929}
4930
4931/// A task a hand-started run leaves runnable (failed with attempts to spare,
4932/// or requeued) is **held**: nobody asked for a retry, and a loop starting
4933/// later must not spend agent calls on it. `magi task release` retries.
4934pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4935    // Parked work (including legacy Failed records with a parked run) is a
4936    // checkpoint or owner handoff, not an unrequested retry.
4937    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
4938        && !awaiting_resume_with(task, RunState::load)
4939        // A run parked on the owner's word about a withheld PR title/body
4940        // resumes via `land_resume_state`, including review-only tasks that
4941        // `awaiting_resume_with` does not consider.
4942        && withheld_text_wait(task).is_none()
4943        && !(task.fresh_start && task.replacement.is_some())
4944    {
4945        let why = task.last_error.clone().map_or_else(
4946            || "the run did not finish".to_owned(),
4947            |e| format!("the run did not finish: {e}"),
4948        );
4949        task.hold_unrequested_retry(Some(format!(
4950            "{why}. It was started by hand, so it is not retried \
4951             automatically; `magi task release` retries it."
4952        )));
4953        record(queue, task);
4954    }
4955}
4956
4957/// Whether an attempt at a task whose newest run is `run` would resume that
4958/// run rather than start a fresh competition. `magi run --resume` hands a run
4959/// to a live loop only when this holds.
4960#[must_use]
4961pub fn loop_would_resume(run: &str) -> bool {
4962    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4963}
4964
4965/// A loop in another process that is alive right now: a fresh heartbeat in
4966/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
4967/// carries the pid it published (`None` inside when it published none - a
4968/// fresh heartbeat is still evidence of a live loop).
4969///
4970/// The one judgement of "is somebody else serving this queue", shared by the
4971/// web UI's refusal to start a second loop and by `magi run` / `magi review`
4972/// deciding whether to hand a task to the loop. A claim file proves nothing
4973/// here: whether a claim succeeds says nothing about whether its owner lives.
4974#[must_use]
4975pub fn foreign_loop(
4976    reading: Option<&Reading>,
4977    now: Timestamp,
4978    own_pid: u32,
4979) -> Option<Option<u32>> {
4980    let reading = reading.filter(|r| r.running(now))?;
4981    match reading.pid {
4982        Some(pid) if pid == own_pid => None,
4983        pid => Some(pid),
4984    }
4985}
4986
4987fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
4988    reading.worker_protocol != Some(1)
4989        && (foreign_loop(Some(reading), now, own_pid).is_some()
4990            || reading
4991                .pid
4992                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
4993}
4994
4995/// Low-level claimed-task execution shared by the detached standalone worker
4996/// and focused lifecycle fixtures. The caller must retain the queue claim for
4997/// this entire call. CLI callers transfer ownership through
4998/// [`run_detached_claimed`] instead of executing inside their own runtime.
4999///
5000/// The one deliberate difference from the loop: a task the attempt leaves
5001/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5002/// Nobody asked for a retry, and a daemon starting later must not spend agent
5003/// calls re-running a hand-started task behind the operator's back;
5004/// `magi task release` is the explicit retry.
5005pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5006    run_claimed_until(opts, queue, task, &Stop::new()).await;
5007}
5008
5009async fn run_claimed_until(
5010    opts: &Opts,
5011    queue: &Queue,
5012    task: &mut Task,
5013    stop: &Stop,
5014) -> Vec<QuotaLoss> {
5015    let status = Arc::new(Mutex::new(Status::new()));
5016    // An attempt embeds startup and graph futures. Keep it off the standalone
5017    // caller's stack, on both the initial execution and withheld-text resume.
5018    let mut quota = Box::pin(attempt(
5019        opts,
5020        queue,
5021        &status,
5022        stop,
5023        crate::graph::Pause::new(),
5024        task,
5025    ))
5026    .await;
5027    // A run parked on the owner's word about a withheld PR title/body has no
5028    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5029    // here with the claim still held, and resume once the question is settled
5030    // (answered, or abandoned at its deadline -> the neutral text).
5031    // A rejected reply files one more question (the gate asks at most twice),
5032    // so after a resume the run may be waiting again: keep going, with a fresh
5033    // limit for the new question. `resumes` bounds it even if a resume parks
5034    // without asking anything new.
5035    let mut resumes = 0;
5036    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5037        let Some(timeout) = withheld_text_wait(task) else {
5038            break;
5039        };
5040        eprintln!(
5041            "waiting for the owner's answer on a withheld pull request text \
5042             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5043        );
5044        // The deadline abandons the question itself; the extra margin only
5045        // covers an abandon that could not be saved.
5046        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5047        let ready = loop {
5048            match land_resume_state(task) {
5049                LandResume::StillWaiting
5050                    if !stop.parking() && std::time::Instant::now() < limit =>
5051                {
5052                    tokio::time::sleep(WITHHELD_POLL).await;
5053                }
5054                LandResume::Ready => break true,
5055                _ => break false,
5056            }
5057        };
5058        if !ready || stop.parking() {
5059            break;
5060        }
5061        resumes += 1;
5062        quota.extend(
5063            Box::pin(attempt(
5064                opts,
5065                queue,
5066                &status,
5067                stop,
5068                crate::graph::Pause::new(),
5069                task,
5070            ))
5071            .await,
5072        );
5073    }
5074    hold_if_runnable(queue, task);
5075    quota
5076}
5077
5078/// Resumes an in-process run makes for withheld-text questions: the gate asks
5079/// at most twice, plus one for a resume that asks nothing new.
5080const MAX_WITHHELD_RESUMES: u32 = 3;
5081
5082/// How often an in-process run rechecks its withheld-text question.
5083const WITHHELD_POLL: Duration = Duration::from_secs(15);
5084
5085/// The `answer_timeout` (seconds) of the task's last run when that run is
5086/// parked on an unresolved withheld-text question; `None` otherwise.
5087fn withheld_text_wait(task: &Task) -> Option<u64> {
5088    let id = task.runs.last()?;
5089    let s = RunState::load(id).ok()?;
5090    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5091        .then_some(s.config.graph.answer_timeout)
5092}
5093
5094/// The quota losses `after` holds that `before` did not: what one execution
5095/// suffered, as opposed to the run's history.
5096///
5097/// Compared by value rather than by length or position because
5098/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5099/// the vector can shrink and shift under a resume. A retried seat that hits
5100/// quota again is a `push` with a new `at`, so it shows up as new here.
5101/// Crash recovery uses the recorded pass start as its boundary when available;
5102/// legacy records without passes retain their original history-based policy.
5103fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5104    after
5105        .iter()
5106        .filter(|q| !before.contains(q))
5107        .cloned()
5108        .collect()
5109}
5110
5111/// When the loop-wide quota cooldown should end, given this attempt's losses;
5112/// `None` when there were none. Reset-hint parsing and the cap live here.
5113fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5114    let quota: Vec<_> = quota
5115        .iter()
5116        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5117        .collect();
5118    if quota.is_empty() {
5119        return None;
5120    }
5121    let with_hint = quota.iter().find(|q| q.reset.is_some());
5122    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5123    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5124    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5125    Some(
5126        now.checked_add(jiff::SignedDuration::from_secs(secs))
5127            .unwrap_or(Timestamp::MAX),
5128    )
5129}
5130
5131/// An explicit task count must agree with a run before any resume.
5132fn implementers_match(task: &Task, state: &RunState) -> bool {
5133    task.replacement.as_ref().map_or_else(
5134        || {
5135            task.implementers()
5136                .is_none_or(|n| n == state.config.graph.implementers)
5137        },
5138        |replacement| {
5139            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5140                && state.config.graph.implementers == 1
5141        },
5142    )
5143}
5144
5145/// Never resume or take over candidate work built for a different seat count.
5146fn starter_with_implementers(
5147    task: &Task,
5148    previous: Option<&RunState>,
5149    proposed: Starter,
5150) -> Starter {
5151    if previous.is_some_and(|s| !implementers_match(task, s)) {
5152        task.review_of
5153            .as_ref()
5154            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5155    } else {
5156        proposed
5157    }
5158}
5159
5160/// Apply this task's explicit count to the new attempt, without changing defaults.
5161fn apply_task_implementers(config: &mut Config, task: &Task) {
5162    if let Some(n) = task.implementers() {
5163        config.graph.implementers = n;
5164    }
5165}
5166
5167/// [`prepare`] for one task: its own `--config` and command-line overrides
5168/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5169/// over the loop's, so handing a hand-started task to a daemon changes nothing
5170/// about what it does.
5171#[cfg(test)]
5172fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5173    let explicit = match &task.overrides {
5174        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5175        _ => opts.config.as_deref(),
5176    };
5177    let (mut config, _) = Config::discover(repo, explicit)?;
5178    apply_options(&mut config, opts, task)?;
5179    Ok(config)
5180}
5181
5182fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5183    if task
5184        .overrides
5185        .as_ref()
5186        .is_none_or(|o| o.inherit_daemon_options)
5187        && let Some(mode) = opts.merge.as_deref()
5188    {
5189        config.merge.mode = merge_mode(mode)?;
5190    }
5191    if let Some(o) = &task.overrides {
5192        o.apply(config);
5193    }
5194    Ok(())
5195}
5196
5197/// Load the config for a task's repository, with the merge override applied.
5198fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5199    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5200    if let Some(mode) = &opts.merge {
5201        config.merge.mode = merge_mode(mode)?;
5202    }
5203    Ok(config)
5204}
5205
5206/// Prune the shared build cache at a between-runs boundary. The detached cache
5207/// service checks authoritative task jobs first; dispatch waits for that finite
5208/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5209/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5210async fn maybe_prune_cache_between_runs(
5211    repo: &Path,
5212    opts: &Opts,
5213    home: &Path,
5214    stop: &Stop,
5215    last_checked: &mut Option<Timestamp>,
5216    now: Timestamp,
5217) {
5218    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5219        return;
5220    }
5221    *last_checked = Some(now);
5222    let cfg = match prepare(repo, opts) {
5223        Ok(cfg) => cfg,
5224        Err(e) => {
5225            tracing::warn!("cache check: no config: {e:#}");
5226            return;
5227        }
5228    };
5229    match clean::prune_cache_if_over_limit(&cfg, home) {
5230        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5231            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5232            pruned.files,
5233            pruned.freed
5234        ),
5235        Ok(_) => {}
5236        Err(e) => {
5237            tracing::warn!("housekeep: prune cache: {e:#}");
5238            notices::raise_in(
5239                home,
5240                Notice::warn(
5241                    "housekeep:cache",
5242                    format!(
5243                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5244                        e.to_string()
5245                            .lines()
5246                            .next()
5247                            .unwrap_or("unknown cleanup error")
5248                    ),
5249                ),
5250            );
5251        }
5252    }
5253}
5254
5255/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5256/// now, given when it last did (if ever). Pure, so the cadence is asserted
5257/// directly rather than by waiting out real minutes in a test.
5258fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5259    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5260}
5261
5262/// The disk janitor, with its housekeeping logged rather than fatal.
5263///
5264/// Called only at the loop's idle points, for the reason the caller documents:
5265/// a prune racing a live compile would delete files mid-build. The config is
5266/// re-read on every call because the repository that just ran may not be the
5267/// daemon's own default, and the cache directory is a repository fact.
5268///
5269/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5270/// and [`crate::run::default_worktree_root`] read here, for the same reason
5271/// [`drive`] takes its queue and status file rather than resolving them: a
5272/// test driving the loop must not reach through to the operator's real home
5273/// or worktree bay just because the janitor runs on every idle tick.
5274/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5275/// to get wrong silently - a test's `home` was already isolated, but nothing
5276/// exercised the parameter next to it, so a real worktree bay stayed wired in
5277/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5278/// it for real, every test in this file that drives the loop at all started
5279/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5280async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5281    let cfg = match prepare(repo, opts) {
5282        Ok(cfg) => cfg,
5283        Err(e) => {
5284            tracing::warn!("housekeep: no config: {e:#}");
5285            return;
5286        }
5287    };
5288    // A run's own worktree lives under `config.graph.worktree_root` when the
5289    // repository sets one - the same precedence `RunState::worktree_root`
5290    // uses - and `worktrees_root` only stands in for the *default* an
5291    // unconfigured repository resolves to (see this function's own
5292    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5293    // that always swept the default regardless of this override would never
5294    // see, and so never reclaim, a single worktree for a repository that
5295    // relocated them elsewhere.
5296    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5297    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5298    // Reported whenever there is anything to say, not only when `folded > 0`:
5299    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5300    // folded, on every single pass, for months - a report gated on `folded`
5301    // would have stayed silent through every one of them.
5302    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5303        let mut extra = Vec::new();
5304        if out.unreadable > 0 {
5305            extra.push(format!("{} unreadable", out.unreadable));
5306        }
5307        if out.orphaned_worktrees > 0 {
5308            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5309        }
5310        let detail = if extra.is_empty() {
5311            String::new()
5312        } else {
5313            format!(" ({})", extra.join(", "))
5314        };
5315        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5316    }
5317    if out.external_merges_recorded > 0 {
5318        tracing::info!(
5319            "housekeep: recorded {} run(s) as merged externally",
5320            out.external_merges_recorded
5321        );
5322    }
5323    if out.stale_pr_states_repaired > 0 {
5324        tracing::info!(
5325            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5326            out.stale_pr_states_repaired
5327        );
5328    }
5329    if out.cache_files > 0 {
5330        tracing::info!(
5331            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5332            out.cache_files,
5333            out.cache_freed
5334        );
5335    }
5336    if out.questions_abandoned > 0 {
5337        tracing::info!(
5338            "housekeep: abandoned {} question(s) left open by a finished run",
5339            out.questions_abandoned
5340        );
5341    }
5342}
5343
5344/// Run [`triage::run_once`] and log whatever it did, the same "only when
5345/// there is something to say" rule [`janitor`] follows for its own report.
5346///
5347/// Called at the same idle points as [`janitor`] - once per full poll
5348/// interval, never mid-attempt - for the same reason: it is not liveness
5349/// critical, and a task's own `hold_reason` string is the one thing this
5350/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5351/// tick for no benefit.
5352async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5353    let questions = Questions::at(home.join("questions"));
5354    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5355    if report.is_empty() {
5356        return;
5357    }
5358    if !report.quarantined.is_empty() {
5359        tracing::info!(
5360            "triage: held {} blocked task(s) whose blocked-on task or \
5361             question no longer exists: {}",
5362            report.quarantined.len(),
5363            report.quarantined.join(", ")
5364        );
5365    }
5366    if !report.resumed.is_empty() {
5367        tracing::info!(
5368            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5369            report.resumed.len(),
5370            report.resumed.join(", ")
5371        );
5372    }
5373    if !report.asked.is_empty() {
5374        tracing::info!(
5375            "triage: asked about {} held task(s): {}",
5376            report.asked.len(),
5377            report.asked.join(", ")
5378        );
5379    }
5380    if !report.answered.is_empty() {
5381        tracing::info!(
5382            "triage: applied {} operator answer(s): {}",
5383            report.answered.len(),
5384            report.answered.join(", ")
5385        );
5386    }
5387}
5388
5389/// The free-space gate: what stands between this task and a new run, if
5390/// anything. `Some(reason)` holds the task; `None` lets it start.
5391///
5392/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5393/// the operator opted out. A measurement failure is a gate, not a pass: both
5394/// sides of "cannot tell" are served by not starting.
5395pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5396    disk_gate_with(repo, config, crate::disk::free_bytes)
5397}
5398
5399/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
5400/// test can assert the exact wiring `attempt` runs - config's threshold in,
5401/// task-holding reason out - without asking the real machine's disk anything.
5402fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5403    repo: &Path,
5404    config: &Config,
5405    free_bytes: F,
5406) -> Option<String> {
5407    let min = config.disk.min_free_bytes;
5408    if min == 0 {
5409        return None;
5410    }
5411    let mut paths = vec![repo.to_owned()];
5412    if let Some(cache) = config.cache_dir() {
5413        paths.push(cache);
5414    }
5415    if let Some(root) = &config.graph.worktree_root {
5416        paths.push(root.clone());
5417    }
5418    for path in paths {
5419        let probe = if path == repo {
5420            path.as_path()
5421        } else {
5422            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5423        };
5424        let reason = match free_bytes(probe) {
5425            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5426            Err(e) => Some(crate::disk::unmeasured_in(
5427                probe,
5428                &e,
5429                &config.graph.language,
5430            )),
5431        };
5432        if reason.is_some() {
5433            return reason;
5434        }
5435    }
5436    None
5437}
5438
5439/// How long to wait before offering another task when a run lost a seat to a
5440/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
5441/// could read, or carried nothing at all. Long enough that a quota outage
5442/// cannot burn through a whole backlog in the few seconds each doomed attempt
5443/// takes to fail; short enough that a quota which clears early is not left
5444/// idle for the fallback's sake.
5445const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5446
5447/// Longest a parsed reset hint may push the wait out to. The hint comes from
5448/// the CLI's own words, not a contract, so a parsing slip that lands a day
5449/// away must not leave the loop asleep for a day.
5450const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5451
5452/// How long [`poll`] should wait before offering the next task, after a run
5453/// lost at least one seat to a rate limit.
5454///
5455/// Pure and separate from the loop so the policy can be exercised without a
5456/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
5457/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
5458/// nothing to parse, or the parsed time has already passed; `cap` bounds how
5459/// far a parsed hint is trusted to push the wait out.
5460fn quota_wait(
5461    reset_at: Option<Timestamp>,
5462    now: Timestamp,
5463    fallback: Duration,
5464    cap: Duration,
5465) -> Duration {
5466    match reset_at {
5467        Some(at) if at > now => {
5468            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5469            Duration::from_secs(secs).min(cap)
5470        }
5471        _ => fallback,
5472    }
5473}
5474
5475/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
5476///
5477/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
5478/// explains why parsing it exactly "would be a bug factory" — so this only
5479/// recognises the shapes actually observed in the wild, and returns `None`
5480/// for anything else rather than guess at a format nobody has seen.
5481///
5482/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
5483/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
5484/// said it, not from whenever this loop happens to read it: anchoring on `now`
5485/// would push the reset later on every read and would read an already-elapsed
5486/// reset as still in the future. (A long hint is still clamped by
5487/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
5488fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5489    parse_reset_hint_zoned(text, now)
5490        .or_else(|| parse_reset_hint_dated(text))
5491        .or_else(|| parse_reset_hint_relative(text, recorded))
5492}
5493
5494/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
5495/// optional but at least one required, in that order. A bare number or any
5496/// unknown unit is refused.
5497fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5498    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5499    let mut rest = rest.trim();
5500    if rest.is_empty() {
5501        return None;
5502    }
5503    let mut total: i64 = 0;
5504    let mut matched = false;
5505    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5506        if let Some((digits, tail)) = rest.split_once(unit)
5507            && !digits.is_empty()
5508            && digits.bytes().all(|b| b.is_ascii_digit())
5509        {
5510            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5511            rest = tail;
5512            matched = true;
5513        }
5514    }
5515    if !rest.is_empty() || !matched {
5516        return None;
5517    }
5518    recorded
5519        .checked_add(jiff::SignedDuration::from_secs(total))
5520        .ok()
5521}
5522
5523/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
5524/// case-insensitive) into a 24-hour hour and minute. Shared by every
5525/// reset-hint shape below.
5526fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5527    let clock = clock.trim().to_lowercase();
5528    let (digits, pm) = clock
5529        .strip_suffix("am")
5530        .map(|d| (d, false))
5531        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5532    let (h, m) = digits.trim().split_once(':')?;
5533    let mut hour: i8 = h.trim().parse().ok()?;
5534    let minute: i8 = m.trim().parse().ok()?;
5535    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5536        return None;
5537    }
5538    if pm && hour != 12 {
5539        hour += 12;
5540    } else if !pm && hour == 12 {
5541        hour = 0;
5542    }
5543    Some((hour, minute))
5544}
5545
5546/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
5547/// and a zone, never a date. A clock reading already past today is read as
5548/// tomorrow's: a CLI naming a same-day reset that has already gone by means
5549/// the window rolled over while nothing was watching.
5550fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5551    let open = text.find('(')?;
5552    let close = text.rfind(')')?;
5553    if close <= open {
5554        return None;
5555    }
5556    let zone = text[open + 1..close].trim();
5557    let (hour, minute) = parse_12h_clock(&text[..open])?;
5558    let tz = jiff::tz::TimeZone::get(zone).ok()?;
5559    let candidate = now
5560        .to_zoned(tz)
5561        .with()
5562        .hour(hour)
5563        .minute(minute)
5564        .second(0)
5565        .millisecond(0)
5566        .microsecond(0)
5567        .nanosecond(0)
5568        .build()
5569        .ok()?;
5570    let mut at = candidate.timestamp();
5571    if at <= now {
5572        at += jiff::SignedDuration::from_hours(24);
5573    }
5574    Some(at)
5575}
5576
5577/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
5578/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
5579/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
5580/// "already past today" correction to make: the year already disambiguates
5581/// it. Scanned as a five-word window so it can be pulled out of the middle
5582/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
5583/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
5584/// any other timestamp with no zone attached.
5585fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5586    let words: Vec<&str> = text.split_whitespace().collect();
5587    if words.len() < 5 {
5588        return None;
5589    }
5590    (0..=words.len() - 5)
5591        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5592}
5593
5594/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
5595/// parenthesis right after the window is refused rather than ignored — it
5596/// reads as an explicit zone annotation on a shape that otherwise carries
5597/// none, and guessing UTC anyway would be exactly the silent misread this
5598/// module's parsing otherwise avoids.
5599fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5600    if trailing.is_some_and(|next| next.starts_with('(')) {
5601        return None;
5602    }
5603    let month = month_number(window[0])?;
5604    let day_token = window[1].strip_suffix(',')?.to_lowercase();
5605    let day_digits = ["st", "nd", "rd", "th"]
5606        .iter()
5607        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5608    let day: i8 = day_digits.parse().ok()?;
5609    let year_token = window[2];
5610    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5611        return None;
5612    }
5613    let year: i16 = year_token.parse().ok()?;
5614    // The am/pm word carries the sentence's own trailing punctuation, e.g.
5615    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
5616    // reusing the same 12-hour clock reader the bracketed shape uses.
5617    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5618    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5619    let date = jiff::civil::Date::new(year, month, day).ok()?;
5620    let candidate = date
5621        .at(hour, minute, 0, 0)
5622        .to_zoned(jiff::tz::TimeZone::UTC)
5623        .ok()?;
5624    Some(candidate.timestamp())
5625}
5626
5627/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
5628/// case-insensitively, into a 1-based month number.
5629fn month_number(name: &str) -> Option<i8> {
5630    const NAMES: [&str; 12] = [
5631        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5632    ];
5633    let lower = name.to_lowercase();
5634    NAMES
5635        .iter()
5636        .position(|n| *n == lower.as_str())
5637        .map(|i| i as i8 + 1)
5638}
5639
5640/// Test probe for the shared resume policy's review-budget exclusion.
5641#[cfg(test)]
5642fn exhausted_review_budget(state: &RunState) -> bool {
5643    // A run whose task-head publication failed has nothing left to review:
5644    // resuming it only retries the publication, so it is never "exhausted".
5645    !crate::handover::can_resume(state)
5646        && state.status == RunStatus::Blocked
5647        && !state.released()
5648        && state.retired_to.is_none()
5649}
5650
5651/// This task's *most recent* run, if resuming it would actually make
5652/// progress. `short` is only for the warning's own message.
5653///
5654/// Only ever `runs.last()` — never a search back through older history.
5655/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
5656/// mint, oldest first, and every entry before the last one was already
5657/// superseded at the moment it was minted: the daemon only ever starts a new
5658/// run when the previous one was not worth resuming (unresumable, exhausted,
5659/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
5660/// opens a fresh review-only run alongside an older, already-failed
5661/// competition. Searching further back would let an old run that merely
5662/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
5663/// behind, say — get resumed instead of the fresh competition
5664/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
5665/// nothing asked to revisit.
5666///
5667/// Two runs paid for the "prefer resuming over restarting" half of this
5668/// lesson, which is why this still checks `runs.last()` rather than always
5669/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
5670/// task a moment later, duplicating two and a half hours of agent work. Then
5671/// b25f stalled on a judge that timed out and one that answered with no JSON
5672/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
5673/// **one second** later, buying three fresh implementations to reach the
5674/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
5675/// the second case: a stall is terminal, and its cheap recovery re-asks only
5676/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
5677/// that is technically `resumable()` but provably cannot progress must not
5678/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
5679/// no-op instead of the fresh competition it promises.
5680///
5681/// A load failure is warned about rather than silently read as "not
5682/// resumable": the alternative is exactly what let a schema mismatch on run
5683/// `eba2` fall through to a full re-competition with nobody told why.
5684/// `crate::conduct` is what actually offers a better answer than
5685/// `Runner::start` here (see `Recovery::Review`), once this task's next
5686/// failure shows it up as `held`/`failed` with the run state unreadable.
5687fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5688    unfinished_run_with(runs, short, RunState::load)
5689}
5690
5691/// [`unfinished_run`] with an injected state reader. Tests provide their
5692/// fixtures directly rather than touching the process-global run home.
5693pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5694where
5695    F: FnMut(&str) -> Result<RunState>,
5696{
5697    let mut id = runs.last()?.clone();
5698    let mut visited = std::collections::BTreeSet::new();
5699    let mut repo = None;
5700    loop {
5701        if !runs.contains(&id) || !visited.insert(id.clone()) {
5702            tracing::warn!("invalid or cyclic recovery authority for task {short}");
5703            return None;
5704        }
5705        let state = match load(&id) {
5706            Ok(state) if state.id == id => state,
5707            Ok(_) => return None,
5708            Err(e) => {
5709                tracing::warn!("could not read run {id} for task {short}: {e:#}");
5710                return None;
5711            }
5712        };
5713        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5714            return None;
5715        }
5716        repo = Some(state.repo.clone());
5717        if let Some(authority) = state.retired_to {
5718            id = authority;
5719            continue;
5720        }
5721        return (crate::handover::can_resume(&state)
5722            && state.liveness(false) != crate::run::Liveness::Live)
5723            .then_some(id);
5724    }
5725}
5726
5727/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
5728/// that [`attempt`] will resume it on its own?
5729///
5730/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
5731/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
5732/// injected reader like its sibling. An unreadable run is not awaiting
5733/// anything: it keeps going to the conductor as before.
5734fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5735where
5736    F: FnOnce(&str) -> Result<RunState>,
5737{
5738    // `Failed` stays: a record an older build wrote for a parked run.
5739    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5740        || task.fresh_start
5741        || task.review_branch.is_some()
5742    {
5743        return false;
5744    }
5745    let Some(id) = task.runs.last() else {
5746        return false;
5747    };
5748    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
5749}
5750
5751/// Which of the three ways [`attempt`] can mint or continue a run this task
5752/// should use.
5753#[derive(Debug, Clone, PartialEq, Eq)]
5754enum Starter {
5755    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
5756    /// and that still exists.
5757    Review(String),
5758    /// `crate::graph::Runner::resume` on an unfinished run of this task.
5759    Resume(String),
5760    /// `crate::graph::Runner::start`: a fresh competition.
5761    Start,
5762}
5763
5764/// A second bound independent of inputs and the resettable failure counter.
5765/// Count execution and failed-startup recovery records once per run. Startup
5766/// failures can retain unrecorded preparation assets without an execution pass.
5767/// Unknown history is not evidence that a new set of worktrees is affordable.
5768fn retained_attempt_hold(
5769    task: &Task,
5770    starter: &Starter,
5771    limit: usize,
5772    mut load: impl FnMut(&str) -> Result<RunState>,
5773) -> Option<String> {
5774    if limit == 0 || matches!(starter, Starter::Resume(_)) {
5775        return None;
5776    }
5777    let mut retained = 0;
5778    for id in task
5779        .runs
5780        .iter()
5781        .chain(task.startup_failures.iter().map(|failure| &failure.run))
5782        .collect::<std::collections::BTreeSet<_>>()
5783    {
5784        let state = match load(id) {
5785            Ok(state) if state.id == *id => state,
5786            _ => {
5787                return Some(format!(
5788                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5789                ));
5790            }
5791        };
5792        if state.retired_to.is_some() || state.released() {
5793            continue;
5794        }
5795        // Neither a completed status nor an empty candidate array proves that
5796        // all recovery sources (including unrecorded preparation) were retired.
5797        retained += 1;
5798    }
5799    (retained >= limit).then(|| format!(
5800        "[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."
5801    ))
5802}
5803
5804/// A selected public implementation overrides every historical candidate and pin.
5805fn selected_starter(
5806    selected: &crate::pr_recovery::Selection,
5807    previous: Option<&RunState>,
5808    unfinished: Option<&str>,
5809) -> Starter {
5810    if let Some(id) = unfinished
5811        && previous.is_some_and(|r| {
5812            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5813        })
5814    {
5815        Starter::Resume(id.to_owned())
5816    } else {
5817        Starter::Review(selected.branch.clone())
5818    }
5819}
5820
5821/// The owner's answer to this branch's divergence question, consumed from the
5822/// task so a later, different divergence asks again. The runner applies it
5823/// (see `Runner::review_taking_over`), after the earlier worktree is released.
5824fn take_divergence_answer(
5825    branch: &str,
5826    remote: &str,
5827    task: &mut Task,
5828) -> Option<crate::reconcile::Choice> {
5829    let summary = crate::reconcile::summary_for(branch, remote);
5830    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5831        (a.question == summary)
5832            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5833            .flatten()
5834            .map(|c| (i, c))
5835    })?;
5836    task.answers.remove(idx);
5837    Some(choice)
5838}
5839
5840/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
5841/// this attempt should use. Pure, and separate from [`attempt`], so the
5842/// routing itself is assertable without spawning a real graph or a git
5843/// process: `attempt`'s own `crate::git::branch_exists` call has already
5844/// happened by the time this is called.
5845///
5846/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
5847/// whose branch is gone falls all the way through to [`Starter::Start`], not
5848/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
5849/// old (likely `Blocked`) run in the first place, and a branch that vanished
5850/// out from under that choice is not evidence resuming it would fare better.
5851fn choose_starter(
5852    review_branch: Option<&str>,
5853    branch_exists: bool,
5854    unfinished: Option<&str>,
5855) -> Starter {
5856    match review_branch {
5857        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5858        Some(_) => Starter::Start,
5859        None => match unfinished {
5860            Some(id) => Starter::Resume(id.to_owned()),
5861            None => Starter::Start,
5862        },
5863    }
5864}
5865
5866/// Reuse a compatible latest review owner instead of taking its checked-out
5867/// branch into a new run. Different branches and changed criteria still use
5868/// the ordinary review/takeover policy.
5869fn review_retry_starter(
5870    task: &Task,
5871    previous: Option<&RunState>,
5872    branch: Option<&str>,
5873    exists: bool,
5874    unfinished: Option<&str>,
5875) -> Starter {
5876    if let Some(run) = previous
5877        && unfinished == Some(run.id.as_str())
5878        && run.reviewed_commits.is_some()
5879        && branch.is_some_and(|branch| {
5880            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
5881        })
5882        && may_resume_run(run, task)
5883    {
5884        return Starter::Resume(run.id.clone());
5885    }
5886    match (branch, unfinished, &task.review_of) {
5887        (None, None, Some(branch)) => Starter::Review(branch.clone()),
5888        _ => choose_starter(branch, exists, unfinished),
5889    }
5890}
5891
5892/// Consume a retained review only while its authored criteria still match.
5893fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5894    let branch = task.review_branch.take();
5895    let instruction = task.review_instruction.take();
5896    branch.filter(|branch| match &instruction {
5897        Some(authored) => *authored == task.instruction,
5898        // Legacy retained branches must agree with their prior run; only an
5899        // explicitly pinned review can proceed without recoverable provenance.
5900        None => previous.map_or_else(
5901            || task.review_of.as_ref() == Some(branch),
5902            |run| compatible_run_instruction(run, task),
5903        ),
5904    })
5905}
5906
5907/// A current explicit pin can select an otherwise incompatible run. Edits
5908/// and subsequent approvals invalidate pins selected for earlier criteria.
5909fn may_resume_run(run: &RunState, task: &Task) -> bool {
5910    task.resume_override
5911        .as_ref()
5912        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5913        || compatible_run_instruction(run, task)
5914}
5915
5916/// Review scaffolding is execution context, not evidence of an operator edit.
5917pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5918    if let Some(authored) = &run.task_instruction {
5919        return compatible_instruction(authored, task);
5920    }
5921    if compatible_instruction(&run.instruction, task) {
5922        return true;
5923    }
5924    // Recognize only the existing generated review shapes on legacy runs.
5925    // Ordinary authored text with a similar heading is left intact.
5926    if run.reviewed_commits.is_some() {
5927        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5928            return strip_answers_block(authored, task).trim() == task.instruction.trim();
5929        }
5930        if let Some(branch) = &task.review_of {
5931            let canonical = format!(
5932                "Review the branch `{branch}` (review-only: no implementation, no judging)."
5933            );
5934            let generated = format!(
5935                "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"
5936            );
5937            return task.instruction == canonical && run.instruction.starts_with(&generated);
5938        }
5939    }
5940    false
5941}
5942
5943/// Compare authored instructions, excluding answer blocks appended by the daemon.
5944pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5945    strip_answers_block(old, task) == task.instruction
5946}
5947
5948/// Which repository a task runs in. A task that names none — the normal case
5949/// for one filed from a phone — runs in the daemon's own default.
5950fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5951    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5952        return fallback.to_path_buf();
5953    }
5954    task.repo.clone()
5955}
5956
5957/// The header [`append_answers`] appends operator answers under. Shared with
5958/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
5959/// rather than grown a new block on every resume.
5960const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5961
5962/// Render the first `count` answers in the block appended to an instruction.
5963fn answers_block(task: &Task, count: usize) -> String {
5964    let mut s = ANSWERS_HEADER.to_owned();
5965    for a in &task.answers[..count] {
5966        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5967    }
5968    s
5969}
5970
5971/// Render the approval independently of transient task state, so historical
5972/// suffixes remain recognizable after another explicit release.
5973fn resumption_block(r: &crate::queue::Resumption) -> String {
5974    format!(
5975        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5976         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5977        r.generation, r.at, r.instruction, r.answers_through,
5978    )
5979}
5980
5981/// Append audit answers and the latest explicit approval to the instruction.
5982fn append_answers(base: &str, task: &Task) -> String {
5983    let mut s = base.to_owned();
5984    if !task.answers.is_empty() {
5985        s.push_str(&answers_block(task, task.answers.len()));
5986    }
5987    if let Some(r) = &task.resumption {
5988        s.push_str(&resumption_block(r));
5989    }
5990    s
5991}
5992
5993/// Drop the prior answer block only when it is exactly the suffix this task
5994/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
5995/// the task author is ordinary instruction text, not a block to remove.
5996fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5997    let mut instruction = instruction;
5998    for approval in task
5999        .resumption
6000        .iter()
6001        .chain(task.resumption_history.iter().rev())
6002    {
6003        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6004            instruction = base;
6005            break;
6006        }
6007    }
6008    for count in (1..=task.answers.len()).rev() {
6009        let block = answers_block(task, count);
6010        if let Some(base) = instruction.strip_suffix(&block) {
6011            return base;
6012        }
6013    }
6014    instruction
6015}
6016
6017/// The instruction handed to `Runner::start`: the task's own text, plus any
6018/// operator answers `crate::conduct` collected for it (see
6019/// [`Task::answers`]), so a decision the operator actually made reaches the
6020/// implementers rather than only clearing the block that was waiting on it.
6021///
6022/// Appended rather than merged into [`Task::instruction`] itself, so the
6023/// task's own record stays exactly what its author wrote.
6024fn instruction_for(task: &Task) -> String {
6025    append_answers(&task.instruction, task)
6026}
6027
6028/// The instruction a resumed run should carry on with: whatever it already
6029/// had, refreshed with the task's *current* operator answers.
6030///
6031/// A resumable run's own `RunState::instruction` predates any answer
6032/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6033/// the behaviour before this function existed — silently drops the very
6034/// decision the operator made to unblock it. Re-stripping any block this
6035/// function appended on an earlier resume before re-appending the current
6036/// list (rather than blindly appending again) is what keeps a task resumed
6037/// three times over three answered questions from carrying the same answer
6038/// three times.
6039fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6040    append_answers(strip_answers_block(old_instruction, task), task)
6041}
6042
6043/// Preserve the producer's verified boundary and target, independent of prose.
6044fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6045    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6046    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6047    if let Some(cause) = task.hold_notice_cause.as_mut() {
6048        cause.target = failure.map(|f| f.target.clone());
6049    }
6050}
6051
6052#[derive(Debug, thiserror::Error)]
6053#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6054struct MissingAttachment {
6055    name: String,
6056    path: PathBuf,
6057}
6058
6059/// The task's attachments as absolute paths, each checked to still exist.
6060fn task_attachments(
6061    queue: &Queue,
6062    task: &Task,
6063) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6064    let paths = queue.attachment_paths(task);
6065    for (name, path) in task.attachments.iter().zip(&paths) {
6066        if !path.is_file() {
6067            return Err(MissingAttachment {
6068                name: name.clone(),
6069                path: path.clone(),
6070            });
6071        }
6072    }
6073    Ok(paths)
6074}
6075
6076/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6077/// answers before handing it to `Runner` — the actual boundary between
6078/// [`choose_starter`]'s routing and the graph, factored out so it is
6079/// assertable without a real repository, git branch, or agent CLI.
6080///
6081/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6082/// instruction from the reviewed branch's own commit log because there is no
6083/// task statement to speak of for hand-written work, and splicing operator
6084/// answers into that text would contradict the very message it sends
6085/// reviewers ("there is no task statement").
6086fn prepare_instruction(
6087    starter: &Starter,
6088    old_instruction: Option<&str>,
6089    task: &Task,
6090) -> Option<String> {
6091    match starter {
6092        Starter::Start => Some(instruction_for(task)),
6093        Starter::Resume(_) => Some(resumed_instruction(
6094            old_instruction.expect("a resumed run always has a prior instruction"),
6095            task,
6096        )),
6097        Starter::Review(_) => None,
6098    }
6099}
6100
6101/// Persist a transition. A queue write failure is logged rather than fatal: the
6102/// run already happened, and taking the daemon down would only add a lost
6103/// backlog to a full disk.
6104fn record(queue: &Queue, task: &mut Task) {
6105    if let Err(e) = queue.put(task) {
6106        tracing::error!("could not record task {}: {e:#}", task.short());
6107        let notice = Notice::error(
6108            "loop:record",
6109            format!(
6110                "Task {} state could not be saved: {}. Check the disk.",
6111                task.id,
6112                e.to_string().lines().next().unwrap_or("unknown save error")
6113            ),
6114        )
6115        .link(Link::Task {
6116            id: task.id.clone(),
6117        });
6118        // The queue lives at `<home>/queue`, so its parent is the home.
6119        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6120            Some(home) => notices::raise_in(home, notice),
6121            None => notices::raise(notice),
6122        }
6123    }
6124}
6125
6126/// Every runnable task, in the order the loop should try them.
6127///
6128/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6129/// tail exists so that a claim somebody else holds costs the loop the next
6130/// candidate rather than a whole poll interval of idleness.
6131fn runnable(queue: &Queue) -> Vec<Task> {
6132    let mut tasks: Vec<Task> = queue
6133        .list()
6134        .into_iter()
6135        .filter(|t| t.status.runnable())
6136        .collect();
6137    tasks.sort_unstable_by(crate::queue::dispatch_order);
6138    tasks
6139}
6140
6141/// Why a run ended where it did, in one line, for [`Task::last_error`].
6142///
6143/// A stalled run names the seats the quota took out: "out of quota" is not
6144/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6145/// agent to replace or which plan to top up.
6146///
6147/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6148/// purpose: unlike `label`'s other callers (an internal log line, an
6149/// already-a-bug fallback message), this string becomes `Task::last_error`
6150/// verbatim, which the phone renders in the same alarm-styled box an
6151/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6152/// `.err` styling. A bare `verified_noop` there would read exactly like the
6153/// failure this whole feature exists to tell apart from one.
6154fn describe(state: &RunState) -> String {
6155    let p = phrases(&state.config.graph.language);
6156    let mut detail = if state.status == RunStatus::Stalled {
6157        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6158        seats.sort_unstable();
6159        seats.dedup();
6160        if seats.is_empty() {
6161            p.quorum_lost.to_owned()
6162        } else {
6163            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6164        }
6165    } else {
6166        format!("{}{}", p.run_ended, state.status.display_label())
6167    };
6168    if let Some(cause) = state.verification_blocking_cause() {
6169        detail.push_str(&format!(" ({cause})"));
6170    } else if let Some(last) = state.events.last() {
6171        // The review loop's "never answered" stop is the one event worth
6172        // translating; it is recognised from structured state, not by
6173        // matching the English event text (which stays as recorded).
6174        let unanswered = state
6175            .reviews
6176            .last()
6177            .filter(|r| {
6178                state.status == RunStatus::Blocked
6179                    && last.node == "review"
6180                    && r.incomplete()
6181                    && r.blocking == 0
6182                    && r.round == state.config.graph.review_rounds
6183                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6184            })
6185            .map(|r| (r.expected - r.answered, r.round));
6186        match unanswered {
6187            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6188                detail.push_str(&format!(
6189                    " ({}: {})",
6190                    last.node,
6191                    (p.reviewers_never_answered)(missing, rounds)
6192                ));
6193            }
6194            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6195        }
6196    }
6197    detail.push_str(&format!(" [run {}]", state.id));
6198    detail
6199}
6200
6201/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6202///
6203/// The task file lives in the backlog indefinitely; a diagnostic is an
6204/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6205/// stay small regardless of how much a gate command or a candidate printed.
6206const DIAGNOSTIC_MAX: usize = 4_000;
6207
6208/// Tail kept from a single failing command's output inside a diagnostic.
6209/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6210/// pointer for a human deciding whether to go read the full artifact by hand,
6211/// not a replacement for reading it.
6212const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6213
6214/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6215/// `magi task show` says more than the one-line reason in [`describe`].
6216///
6217/// The one-liner answers "where did the run stop"; this answers "what would a
6218/// human have found opening `artifacts/` by hand" — the point of the whole
6219/// feature is the case that one-liner actively misleads on: a run held as "no
6220/// candidate produced a change" can mean the implementer actually finished
6221/// the task (opened a PR, merged it, tagged a release) and only left a clean
6222/// local worktree behind, which reads as "nothing happened" unless someone
6223/// goes and reads what the agent actually said. `None` when the run carries
6224/// none of the three shapes this recognises — an ordinary run held for
6225/// something not diagnosable from `RunState` alone still explains itself
6226/// through `Task::last_error`.
6227fn diagnostic(state: &RunState) -> Option<String> {
6228    let mut parts: Vec<String> = Vec::new();
6229
6230    // Gate failure: which check(s), and the tail of what each printed.
6231    for o in state.gate.iter().filter(|o| !o.ok()) {
6232        parts.push(format!(
6233            "gate `{}` failed ({}):\n{}",
6234            o.command,
6235            notices::exit_status(o.code),
6236            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6237        ));
6238    }
6239
6240    // The land loop gave up because the fixer declined while checks were
6241    // still red: the message already names them (see `land::run`).
6242    if let Some(last) = state
6243        .events
6244        .iter()
6245        .rev()
6246        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6247    {
6248        parts.push(last.message.clone());
6249    }
6250
6251    // No viable candidate: every implementer's own final word, sanitized the
6252    // same way a judge would have read it, so a run that actually finished
6253    // the job does not read as an unexplained failure. A verified no-op is
6254    // called out ahead of its own summary and apart from an ordinary
6255    // failure's `why` — this is the one candidate shape whose diagnostic a
6256    // human is expected to actually judge, not just skim.
6257    if state.viable().is_empty() {
6258        for c in &state.candidates {
6259            if let Some(evidence) = &c.verified_noop {
6260                parts.push(format!(
6261                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6262                    c.label
6263                ));
6264            } else if !c.summary.trim().is_empty() {
6265                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6266            } else if let Some(why) = &c.failed {
6267                parts.push(format!("candidate {}: {why}", c.label));
6268            }
6269        }
6270    }
6271
6272    if parts.is_empty() {
6273        return None;
6274    }
6275    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6276    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6277    // back slightly over. Leave it enough room to always land under the
6278    // limit.
6279    Some(crate::run::tail(
6280        &parts.join("\n\n"),
6281        DIAGNOSTIC_MAX.saturating_sub(100),
6282    ))
6283}
6284
6285/// Stable lower-case name for a run status, for an internal log line and the
6286/// "graph stopped without reaching a terminal status" bug message in
6287/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6288/// doc for why that one reads [`RunStatus::display_label`] instead. One
6289/// definition of a status's name, on the type that owns it: this table used
6290/// to live here as a second copy, and a status renamed in one place would
6291/// have gone on reading correctly in the other.
6292fn label(status: RunStatus) -> &'static str {
6293    status.as_str()
6294}
6295
6296/// Parse a merge mode override.
6297pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6298    match mode {
6299        "none" => Ok(MergeMode::None),
6300        "local" => Ok(MergeMode::Local),
6301        "pr" => Ok(MergeMode::Pr),
6302        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6303    }
6304}
6305
6306/// Take the status lock, recovering from a poisoned one.
6307///
6308/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6309/// data, and the worst a poisoned lock can hold is a stale timestamp.
6310fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6311    mutex
6312        .lock()
6313        .unwrap_or_else(std::sync::PoisonError::into_inner)
6314}
6315
6316#[cfg(test)]
6317mod tests {
6318    use super::*;
6319    use crate::queue::{Source, TaskStatus};
6320    use crate::run::{Candidate, CommandOutcome};
6321    use pretty_assertions::assert_eq;
6322
6323    fn task() -> Task {
6324        Task::new(
6325            "add retries".to_owned(),
6326            "add retries".to_owned(),
6327            PathBuf::from("/repo"),
6328            Source::Human,
6329        )
6330    }
6331
6332    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6333        let job = crate::worker::Job {
6334            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6335            sequence: 1,
6336            kind: "task".into(),
6337            key: format!("task:{}", request.task),
6338            payload: serde_json::to_value(request).unwrap(),
6339            generation: "a".repeat(64),
6340            version: None,
6341            status: crate::worker::Status::Starting,
6342            result: None,
6343            pid: None,
6344            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6345            finished_at: None,
6346        };
6347        let dir = home.join("workers/jobs").join(&job.id);
6348        std::fs::create_dir_all(&dir).unwrap();
6349        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6350        job
6351    }
6352
6353    #[test]
6354    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6355        let home = tempfile::tempdir().unwrap();
6356        let request = TaskWorker {
6357            opts: Opts::default(),
6358            queue: home.path().join("queue"),
6359            task: "startup".into(),
6360            lane: PermitKind::Ordinary,
6361            standalone: false,
6362        };
6363        let job = starting_task_reservation(home.path(), &request);
6364        let error = task_worker_spawn_error(
6365            home.path(),
6366            &request,
6367            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6368        )
6369        .expect_err("our own reservation must not turn a failed spawn into a resync");
6370        let active = crate::worker::active(home.path()).unwrap();
6371        assert_eq!(active.len(), 1);
6372        assert_eq!(active[0].id, job.id);
6373        assert_eq!(active[0].status, crate::worker::Status::Starting);
6374        assert!(
6375            crate::worker::control(home.path(), &job.key)
6376                .unwrap()
6377                .is_none()
6378        );
6379        let notices = notices::Notices::at(home.path().join("notifications")).list();
6380        assert_eq!(notices.len(), 1);
6381        assert_eq!(notices[0].key, "loop:worker-startup");
6382        assert!(!notices[0].message.contains("private-error-detail"));
6383        assert!(notices[0].message.contains(&request.task));
6384        assert!(
6385            notices[0]
6386                .message
6387                .contains("could not be started or acknowledged")
6388        );
6389        assert!(notices[0].message.contains("worker.log"));
6390        assert_eq!(
6391            notices[0].link,
6392            Some(Link::Task {
6393                id: request.task.clone()
6394            })
6395        );
6396        assert!(format!("{error:#}").contains("private-error-detail"));
6397    }
6398
6399    #[test]
6400    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6401        let home = tempfile::tempdir().unwrap();
6402        let mut request = TaskWorker {
6403            opts: Opts::default(),
6404            queue: home.path().join("queue"),
6405            task: "handoff".into(),
6406            lane: PermitKind::Ordinary,
6407            standalone: true,
6408        };
6409        let job = starting_task_reservation(home.path(), &request);
6410        request.standalone = false;
6411        task_worker_spawn_error(
6412            home.path(),
6413            &request,
6414            anyhow::anyhow!("operation key is already reserved for a different request"),
6415        )
6416        .expect("a different standalone request is the handoff race, not our startup failure");
6417        let active = crate::worker::active(home.path()).unwrap();
6418        assert_eq!(active.len(), 1);
6419        assert_eq!(active[0].id, job.id);
6420        assert_eq!(active[0].payload, job.payload);
6421        assert!(
6422            notices::Notices::at(home.path().join("notifications"))
6423                .list()
6424                .is_empty()
6425        );
6426    }
6427
6428    #[test]
6429    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6430        let home = tempfile::tempdir().unwrap();
6431        let queue = Queue::at(home.path().join("queue"));
6432        let mut task = task();
6433        task.runs = vec!["previous".into()];
6434        queue.put(&mut task).unwrap();
6435        let request = TaskWorker {
6436            opts: Opts::default(),
6437            queue: home.path().join("queue"),
6438            task: task.id.clone(),
6439            lane: PermitKind::Ordinary,
6440            standalone: false,
6441        };
6442        let job = starting_task_reservation(home.path(), &request);
6443        let claims = current_work(home.path(), Timestamp::now());
6444        assert_eq!(claims.len(), 1);
6445        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6446        assert_eq!(claims[0].run, "previous");
6447        assert!(other_claims_run(&claims, "previous", None));
6448        // Only after confirming the executing caller may admission ignore
6449        // this exact projection. Cleanup continues to observe it as live.
6450        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6451        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6452    }
6453
6454    #[test]
6455    fn admission_excludes_only_the_callers_exact_reservation() {
6456        let own = Current {
6457            worker: Some("own".into()),
6458            task: "same-task".into(),
6459            run: "previous".into(),
6460        };
6461        assert!(!other_claims_run(
6462            std::slice::from_ref(&own),
6463            "previous",
6464            Some("own")
6465        ));
6466        assert!(other_claims_run(
6467            std::slice::from_ref(&own),
6468            "previous",
6469            None
6470        ));
6471        for worker in [None, Some("other".into())] {
6472            let other = Current {
6473                worker,
6474                ..own.clone()
6475            };
6476            assert!(other_claims_run(
6477                &[own.clone(), other],
6478                "previous",
6479                Some("own")
6480            ));
6481        }
6482        let legacy: Current =
6483            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6484        assert!(other_claims_run(&[legacy], "previous", Some("own")));
6485    }
6486
6487    #[test]
6488    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6489        let mut task = task();
6490        let mut run = run_state(RunStatus::Reviewing);
6491        run.task_instruction = Some(task.instruction.clone());
6492        run.reviewed_commits = Some(vec!["committed-fix".into()]);
6493        let branch = "magi/test/B";
6494        run.candidates.push(crate::run::Candidate {
6495            branch: branch.into(),
6496            ..candidate('B', "preserved work", false, None)
6497        });
6498        task.runs = vec![run.id.clone()];
6499        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6500        assert_eq!(
6501            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6502            Starter::Resume(run.id.clone())
6503        );
6504        assert!(matches!(
6505            review_retry_starter(
6506                &task,
6507                Some(&run),
6508                Some("different"),
6509                true,
6510                unfinished.as_deref()
6511            ),
6512            Starter::Review(_)
6513        ));
6514        assert_eq!(
6515            review_retry_starter(
6516                &task,
6517                Some(&run),
6518                Some(branch),
6519                false,
6520                unfinished.as_deref()
6521            ),
6522            Starter::Start
6523        );
6524        task.instruction.push_str(" changed criteria");
6525        assert!(matches!(
6526            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6527            Starter::Review(_)
6528        ));
6529        assert!(matches!(
6530            review_retry_starter(&task, Some(&run), Some(branch), true, None),
6531            Starter::Review(_)
6532        ));
6533    }
6534
6535    #[test]
6536    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6537        let dir = tempfile::tempdir().unwrap();
6538        let queue = Queue::at(dir.path().join("queue"));
6539        let mut task = task();
6540        task.status = TaskStatus::Running;
6541        task.attempts = 1;
6542        queue.put(&mut task).unwrap();
6543        let live = std::collections::BTreeSet::from([task.id.clone()]);
6544        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6545        drop(queue.claim(&task.id).unwrap());
6546        let saved = queue.get(&task.id).unwrap();
6547        assert_eq!(saved.status, TaskStatus::Running);
6548        assert_eq!(saved.attempts, 1);
6549        assert!(saved.last_error.is_none());
6550    }
6551
6552    #[test]
6553    fn standalone_workers_do_not_consume_scheduler_lanes() {
6554        let request = |task: &str, lane, standalone| TaskWorker {
6555            opts: Opts::default(),
6556            queue: PathBuf::from("/queue"),
6557            task: task.to_owned(),
6558            lane,
6559            standalone,
6560        };
6561        let mut jobs = vec![
6562            request("ordinary", PermitKind::Ordinary, false),
6563            request("standalone-urgent", PermitKind::Urgent, true),
6564            request("standalone-ordinary", PermitKind::Ordinary, true),
6565            request("decision", PermitKind::None, false),
6566        ];
6567        assert_eq!(available_slots(&jobs, 2), (1, 1));
6568        jobs.push(request("urgent", PermitKind::Urgent, false));
6569        assert_eq!(available_slots(&jobs, 2), (1, 0));
6570        assert_eq!(available_slots(&jobs, 0), (0, 0));
6571    }
6572
6573    #[test]
6574    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6575        let now = Timestamp::now();
6576        let mut reading = Reading {
6577            pid: Some(std::process::id()),
6578            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6579            ..Reading::default()
6580        };
6581        assert!(!reading.running(now));
6582        assert!(legacy_scheduler_running(&reading, now, 0));
6583        reading.worker_protocol = Some(1);
6584        assert!(!legacy_scheduler_running(&reading, now, 0));
6585    }
6586
6587    #[test]
6588    fn selected_public_head_overrides_historical_resume_and_pin() {
6589        let mut t = task();
6590        let mut old = run_state(RunStatus::Blocked);
6591        let selection = crate::pr_recovery::Selection {
6592            url: "url".into(),
6593            branch: format!("magi/task-{}", t.id),
6594            head: "a".repeat(40),
6595            source_head: None,
6596            source_run: None,
6597            source_proof: None,
6598            disposition: Some(crate::pr_recovery::Disposition::Review),
6599            instruction: t.instruction.clone(),
6600            approved_at: Timestamp::now(),
6601        };
6602        t.resume_override = Some(crate::queue::OperatorResume {
6603            pinned_run: Some(old.id.clone()),
6604            question_id: "choice".into(),
6605            at: Timestamp::now(),
6606            conductor_rehold: None,
6607            forced: false,
6608        });
6609        assert_eq!(
6610            selected_starter(&selection, Some(&old), Some(&old.id)),
6611            Starter::Review(selection.branch.clone())
6612        );
6613        old.pr_recovery = Some(selection.clone());
6614        assert_eq!(
6615            selected_starter(&selection, Some(&old), Some(&old.id)),
6616            Starter::Review(selection.branch.clone())
6617        );
6618        old.reviewed_commits = Some(vec!["implementation".into()]);
6619        assert_eq!(
6620            selected_starter(&selection, Some(&old), Some(&old.id)),
6621            Starter::Resume(old.id.clone())
6622        );
6623        let mut changed = selection.clone();
6624        changed.head = "b".repeat(40);
6625        assert_eq!(
6626            selected_starter(&changed, Some(&old), Some(&old.id)),
6627            Starter::Review(changed.branch)
6628        );
6629    }
6630
6631    #[test]
6632    fn candidate_transplant_failure_is_one_actionable_hold() {
6633        let dir = tempfile::tempdir().unwrap();
6634        let q = Queue::at(dir.path().join("queue"));
6635        let mut t = task();
6636        let mut state = run_state(RunStatus::Blocked);
6637        state.event("prep", "cannot apply referenced commit: conflict");
6638        state.prep_failure = Some("conflict".into());
6639        t.start(state.id.clone());
6640        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6641        assert_eq!(t.attempts, 1);
6642        assert_eq!(t.status, TaskStatus::Held);
6643        assert!(t.operator_held());
6644        assert!(!t.status.runnable());
6645        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6646        let first = t.chat_notice_key().unwrap();
6647        t.chat_notices.push(first.clone());
6648        t.release_operator("test", None);
6649        state.id = "another-unprepared-run".into();
6650        t.start(state.id.clone());
6651        finish_attempt(
6652            3,
6653            &q,
6654            &mut t,
6655            &state,
6656            &[],
6657            Err(anyhow::anyhow!("still conflicts")),
6658        );
6659        assert_eq!(
6660            t.chat_notice_key().as_ref(),
6661            Some(&first),
6662            "no work happened"
6663        );
6664        t.release_operator("test", None);
6665        state.prep_failure = None;
6666        state.status = RunStatus::Failed;
6667        state.begin_pass();
6668        t.start(state.id.clone());
6669        finish_attempt(
6670            1,
6671            &q,
6672            &mut t,
6673            &state,
6674            &[],
6675            Err(anyhow::anyhow!("new gate failure")),
6676        );
6677        let failure = t.chat_notice_key().unwrap();
6678        assert_ne!(failure, first, "approved recovery reached a real failure");
6679        t.release_operator("test", None);
6680        state.begin_pass();
6681        t.start(state.id.clone());
6682        finish_attempt(
6683            1,
6684            &q,
6685            &mut t,
6686            &state,
6687            &[],
6688            Err(anyhow::anyhow!("new failure on resume")),
6689        );
6690        assert_ne!(
6691            t.chat_notice_key().as_ref(),
6692            Some(&failure),
6693            "a new settled pass"
6694        );
6695    }
6696
6697    #[test]
6698    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6699        for source in ["cli", "web"] {
6700            let mut t = task();
6701            let mut run = run_state(RunStatus::Blocked);
6702            run.instruction = "Run A original criteria".into();
6703            run.task_instruction = Some(run.instruction.clone());
6704            t.start(run.id.clone());
6705            t.release_operator("choice", Some("resume-question"));
6706            t.resume_override = Some(crate::queue::OperatorResume {
6707                question_id: "resume-question".into(),
6708                at: Timestamp::now(),
6709                conductor_rehold: None,
6710                forced: true,
6711                pinned_run: Some(run.id.clone()),
6712            });
6713            t.hold_machine(Some("not enough free space to start a run".into()));
6714            let mut unchanged = t.clone();
6715            unchanged
6716                .edit("title changed".into(), unchanged.instruction.clone())
6717                .unwrap();
6718            unchanged.release_operator(source, None);
6719            assert_eq!(
6720                unchanged
6721                    .resume_override
6722                    .as_ref()
6723                    .unwrap()
6724                    .pinned_run
6725                    .as_deref(),
6726                Some(run.id.as_str())
6727            );
6728            assert!(!compatible_run_instruction(&run, &unchanged));
6729            assert!(may_resume_run(&run, &unchanged));
6730
6731            t.edit(
6732                "approved recovery".into(),
6733                "Reuse measured PR head B; fix Clippy; review".into(),
6734            )
6735            .unwrap();
6736            assert!(t.resume_override.is_none());
6737            t.release_operator(source, None);
6738            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6739            assert!(reloaded.resume_override.is_none());
6740            assert!(!may_resume_run(&run, &reloaded));
6741            let unfinished =
6742                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6743                    .filter(|_| may_resume_run(&run, &reloaded));
6744            assert_eq!(
6745                choose_starter(None, false, unfinished.as_deref()),
6746                Starter::Start
6747            );
6748            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
6749            assert_eq!(
6750                reloaded.resumption_history[0].question_id.as_deref(),
6751                Some("resume-question")
6752            );
6753
6754            // A revision already persisted with the old approval/pin is also
6755            // invalidated when the new operator release is recorded.
6756            unchanged.instruction = "Reuse measured PR head B".into();
6757            unchanged.hold_machine(Some("disk hold".into()));
6758            unchanged.release_operator(source, None);
6759            assert!(unchanged.resume_override.is_none());
6760            assert!(!may_resume_run(&run, &unchanged));
6761        }
6762    }
6763
6764    #[test]
6765    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
6766        let mut t = task();
6767        let mut run = run_state(RunStatus::Blocked);
6768        t.review_of = Some("approved-head".into());
6769        t.instruction =
6770            "Review the branch `approved-head` (review-only: no implementation, no judging)."
6771                .into();
6772        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();
6773        run.reviewed_commits = Some(vec!["Commit log".into()]);
6774        t.start(run.id.clone());
6775        t.hold_machine(Some("interrupted review".into()));
6776        t.release_operator("cli", None);
6777        assert!(
6778            compatible_run_instruction(&run, &t),
6779            "legacy explicit review remains resumable"
6780        );
6781        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
6782            .filter(|_| compatible_run_instruction(&run, &t));
6783        assert_eq!(
6784            choose_starter(None, false, unfinished.as_deref()),
6785            Starter::Resume(run.id.clone())
6786        );
6787        run.task_instruction = Some(t.instruction.clone());
6788        assert!(compatible_run_instruction(&run, &t));
6789        let reloaded: RunState =
6790            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
6791        assert!(compatible_run_instruction(&reloaded, &t));
6792        t.edit(
6793            "new approved head".into(),
6794            "Reuse measured PR head B".into(),
6795        )
6796        .unwrap();
6797        assert!(!compatible_run_instruction(&run, &t));
6798
6799        // Legacy recovery reviews retain the task criteria ahead of the log.
6800        t.review_of = None;
6801        t.instruction = "Fix Clippy on approved head".into();
6802        run.task_instruction = None;
6803        run.instruction = format!(
6804            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
6805            t.instruction
6806        );
6807        assert!(compatible_run_instruction(&run, &t));
6808        t.instruction.push('\n');
6809        assert!(
6810            compatible_run_instruction(&run, &t),
6811            "legacy generated review trimmed the original criteria"
6812        );
6813        t.hold_for_handover(Some("approved-head".into()), "refused".into());
6814        let mut unchanged = t.clone();
6815        assert_eq!(
6816            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
6817            Some("approved-head")
6818        );
6819        t.edit("new plan".into(), "Reuse measured PR head B".into())
6820            .unwrap();
6821        assert!(take_review_branch(&mut t, Some(&run)).is_none());
6822        assert!(!compatible_run_instruction(&run, &t));
6823        t.review_branch = Some("approved-head".into());
6824        t.review_instruction = None;
6825        assert!(
6826            take_review_branch(&mut t, Some(&run)).is_none(),
6827            "legacy retained candidate cannot replace a revised approved head"
6828        );
6829    }
6830
6831    #[test]
6832    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
6833        let home = crate::run::test_home();
6834        crate::run::pin_test_home();
6835        let dir = tempfile::tempdir().unwrap();
6836        let queue = Queue::at(dir.path().join("queue"));
6837        for resume in [true, false] {
6838            let state = run_state(RunStatus::Blocked);
6839            let mut t = task();
6840            t.start(state.id.clone());
6841            let action = if resume {
6842                ask::ChoiceAction::Resume {
6843                    run: state.id.clone(),
6844                }
6845            } else {
6846                ask::ChoiceAction::Requeue
6847            };
6848            let mut q = action_question(&state.id, action);
6849            q.status = ask::QuestionStatus::Open;
6850            q.answer = None;
6851            q.answered_at = None;
6852            t.fail("run stopped with a question", 3);
6853            hold_if_runnable(&queue, &mut t);
6854            assert!(t.operator_decided_at.is_none());
6855            assert!(t.operator_held());
6856            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
6857            let expected = if resume {
6858                ActionDecision::Resume(state.id.clone())
6859            } else {
6860                ActionDecision::Requeue
6861            };
6862            assert_eq!(
6863                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
6864                expected
6865            );
6866            t.hold_manual(Some("later explicit hold".into()));
6867            assert_eq!(
6868                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
6869                ActionDecision::Stale
6870            );
6871        }
6872    }
6873
6874    #[test]
6875    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
6876        let mut t = task();
6877        t.answers.push(crate::queue::AnsweredQuestion {
6878            question: "Inspect the remote?".into(),
6879            answer: "Inspect then wait".into(),
6880        });
6881        let old = instruction_for(&t);
6882        assert!(compatible_instruction(&old, &t));
6883        t.instruction = "Reuse approved PR head and review".into();
6884        t.release_operator("cli", None);
6885        assert!(!compatible_instruction(&old, &t));
6886        let approved = instruction_for(&t);
6887        assert!(approved.contains("waiting premises are superseded"));
6888        assert!(compatible_instruction(&approved, &t));
6889        assert_eq!(resumed_instruction(&approved, &t), approved);
6890        t.release_operator("web", None);
6891        assert!(compatible_instruction(&approved, &t));
6892        assert_eq!(t.resumption_history.len(), 1);
6893        t.start("run".into());
6894        assert!(instruction_for(&t).contains("Explicit operator resumption"));
6895    }
6896
6897    /// A run that stopped on an infrastructure wait asked no agent anything:
6898    /// the task is held by the machine under a `[resource]` reason (resumable,
6899    /// re-checked by triage), and the attempt it started is given back.
6900    #[test]
6901    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
6902        let mut state = RunState::new(
6903            PathBuf::from("/repo"),
6904            "main".into(),
6905            "base".into(),
6906            "task".into(),
6907            Config::default(),
6908        );
6909        state.status = RunStatus::Landing;
6910        state.parked = true;
6911        state.pr_pushed_head = Some("head".into());
6912        state.land_unrelated = Some(
6913            serde_json::from_value(serde_json::json!({
6914                "head": "head", "question": "ci-question",
6915                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
6916            }))
6917            .unwrap(),
6918        );
6919        let mut t = task();
6920        t.start(state.id.clone());
6921        let verdict = Verdict {
6922            status: RunStatus::Landing,
6923            left_pr: true,
6924            quota_hit: false,
6925            parked: true,
6926            no_viable_candidates: false,
6927        };
6928        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6929        assert_eq!(t.attempts, 0);
6930        assert_eq!(t.status, TaskStatus::Held);
6931        assert!(!t.operator_held());
6932        assert!(
6933            t.hold_reason
6934                .as_deref()
6935                .unwrap()
6936                .starts_with("[ci-unrelated]")
6937        );
6938        // A second settlement must not refund an earlier task attempt.
6939        t.attempts = 1;
6940        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6941        assert_eq!(t.attempts, 1);
6942        assert_eq!(t.passes.len(), 1);
6943        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6944        state.pr_pushed_head = Some("new-head".into());
6945        state.parked = false;
6946        state.status = RunStatus::Blocked;
6947        let stale = Verdict {
6948            status: RunStatus::Blocked,
6949            parked: false,
6950            ..verdict
6951        };
6952        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
6953        assert_eq!(t.attempts, 1);
6954        // A new execution pass can refund its own newly charged attempt.
6955        state.begin_pass();
6956        state.begin_pass();
6957        state.status = RunStatus::Landing;
6958        state.parked = true;
6959        state.pr_pushed_head = Some("head".into());
6960        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
6961        assert_eq!(t.attempts, 0);
6962        assert_eq!(t.passes.len(), 2);
6963    }
6964
6965    #[test]
6966    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
6967        let mut state = run_state(RunStatus::Failed);
6968        state
6969            .quota
6970            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
6971        state.begin_pass();
6972        let mut t = task();
6973        t.start(state.id.clone());
6974        reclaim(&mut t, Some(state), 2, "en");
6975        assert_eq!(t.attempts, 1);
6976    }
6977
6978    #[test]
6979    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
6980        let mut state = run_state(RunStatus::Blocked);
6981        let losses: Vec<_> = ["alpha", "beta"]
6982            .into_iter()
6983            .enumerate()
6984            .map(|(i, agent)| {
6985                QuotaLoss::from_report(
6986                    format!("advisor-{i}"),
6987                    "advise",
6988                    Some(&crate::agent::Quota {
6989                        cause: crate::agent::QuotaCause::Authentication,
6990                        agent: agent.to_owned(),
6991                        reset: None,
6992                    }),
6993                )
6994            })
6995            .collect();
6996        crate::graph::block_machine_outage(&mut state, "advise", &losses);
6997        state.quota = losses;
6998        let mut t = task();
6999        t.start(state.id.clone());
7000        let verdict = Verdict {
7001            status: state.status,
7002            left_pr: false,
7003            quota_hit: true,
7004            parked: false,
7005            no_viable_candidates: true,
7006        };
7007        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7008        assert_eq!(t.attempts, 0);
7009        assert_eq!(t.status, TaskStatus::Held);
7010        assert!(!t.operator_held());
7011        let reason = t.hold_reason.as_deref().unwrap();
7012        assert!(reason.starts_with("[authentication]"));
7013        assert!(
7014            reason.contains("alpha")
7015                && reason.contains("beta")
7016                && reason.contains("re-authenticate")
7017        );
7018        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7019        // Orphan recovery uses the same settlement and cannot spend an attempt.
7020        let mut orphan = task();
7021        orphan.start(state.id.clone());
7022        reclaim(&mut orphan, Some(state), 2, "en");
7023        assert_eq!(orphan.attempts, 0);
7024        assert_eq!(orphan.status, TaskStatus::Held);
7025    }
7026
7027    #[test]
7028    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7029        let mut state = RunState::new(
7030            PathBuf::from("/repo"),
7031            "main".to_owned(),
7032            "abc1234".to_owned(),
7033            "task".to_owned(),
7034            Config::default(),
7035        );
7036        state.status = RunStatus::Blocked;
7037        state.resource_block = Some(crate::run::ResourceBlock {
7038            cause: crate::run::ResourceBlockCause::Other,
7039            node: "graft".to_owned(),
7040            kind: "shared build cache".to_owned(),
7041            detail: "timed out".to_owned(),
7042            at: jiff::Timestamp::now(),
7043        });
7044        let mut t = task();
7045        t.start("20260902-000000-aaaa".to_owned());
7046        assert_eq!(t.attempts, 1);
7047        let verdict = Verdict {
7048            status: RunStatus::Blocked,
7049            left_pr: false,
7050            quota_hit: false,
7051            parked: false,
7052            no_viable_candidates: false,
7053        };
7054        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7055        assert_eq!(t.status, TaskStatus::Held);
7056        assert_eq!(t.attempts, 0, "the attempt is refunded");
7057        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7058        assert!(
7059            !t.operator_held(),
7060            "a machine hold, released without a human"
7061        );
7062
7063        let mut selected = task();
7064        selected.start("20260902-000000-cccc".into());
7065        selected.replacement = Some(crate::merge_decision::Replacement {
7066            question: "fixture".into(),
7067            run: "earlier".into(),
7068            pr: "https://example.invalid/pr/1".into(),
7069            agent: "selected".into(),
7070            context: "fixture".into(),
7071        });
7072        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7073        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7074        assert_eq!(selected.attempts, 0);
7075        assert!(
7076            !selected.operator_held(),
7077            "a selected agent also retains a machine resource hold"
7078        );
7079        assert!(
7080            selected
7081                .hold_reason
7082                .as_deref()
7083                .unwrap()
7084                .starts_with("[resource] ")
7085        );
7086
7087        // A park request outranks it: still the operator's doing.
7088        let mut p = task();
7089        p.start("20260902-000000-bbbb".to_owned());
7090        settle_and_diagnose(
7091            &mut p,
7092            Verdict {
7093                parked: true,
7094                ..verdict
7095            },
7096            "parked",
7097            2,
7098            &state,
7099        );
7100        assert_eq!(p.status, TaskStatus::Parked);
7101        assert_eq!(
7102            p.attempts, 0,
7103            "parking refunds once rather than also settling the resource hold"
7104        );
7105    }
7106
7107    #[test]
7108    fn record_failure_notice_links_the_task() {
7109        let dir = tempfile::tempdir().unwrap();
7110        // A regular file where the queue directory should be makes every
7111        // `put` fail, on every platform and whoever runs the test.
7112        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7113        let queue = Queue::at(dir.path().join("queue"));
7114        let mut t = interrupt_task("rec-fail-1");
7115        record(&queue, &mut t);
7116
7117        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7118        assert_eq!(found.len(), 1);
7119        assert_eq!(found[0].key, "loop:record");
7120        assert_eq!(
7121            found[0].link,
7122            Some(Link::Task {
7123                id: "rec-fail-1".to_owned()
7124            })
7125        );
7126    }
7127
7128    /// A runnable task marked to interrupt, with an id fixed for assertions
7129    /// rather than the random one [`Task::new`] mints.
7130    fn interrupt_task(id: &str) -> Task {
7131        let mut t = task();
7132        t.id = id.to_owned();
7133        t.interrupt = true;
7134        t
7135    }
7136
7137    /// An ordinary runnable task with an id fixed for assertions.
7138    fn task_with_id(id: &str) -> Task {
7139        let mut t = task();
7140        t.id = id.to_owned();
7141        t
7142    }
7143
7144    /// A runnable task marked `--urgent`, with an id fixed for assertions.
7145    fn urgent_task(id: &str) -> Task {
7146        let mut t = task();
7147        t.id = id.to_owned();
7148        t.urgent = true;
7149        t
7150    }
7151
7152    #[test]
7153    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7154        let dir = tempfile::tempdir().unwrap();
7155        let queue = Queue::at(dir.path().join("queue"));
7156        let mut parked = task_with_id("parked");
7157        parked.start("run".into());
7158        parked.park("upgrade");
7159        parked.record_pass_at(
7160            "run",
7161            0,
7162            Some(Timestamp::now()),
7163            1,
7164            Some(crate::run::ParkCause::Upgrade {
7165                from: "old".into(),
7166                to: None,
7167            }),
7168        );
7169        let mut fresh = task_with_id("fresh");
7170        fresh.priority = 100;
7171        let mut urgent_task = urgent_task("urgent");
7172        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7173            queue.put(t).unwrap();
7174        }
7175        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7176        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7177        let candidates = runnable(&queue);
7178        assert_eq!(candidates[0].id, parked.id);
7179        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7180        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7181        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7182        drop(first);
7183        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7184        let next = runnable(&queue)
7185            .into_iter()
7186            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7187            .unwrap();
7188        assert_eq!(next.task.id, fresh.id);
7189        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7190        drop(claimed_elsewhere);
7191        drop(next);
7192        assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7193    }
7194
7195    #[test]
7196    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7197        let dir = tempfile::tempdir().unwrap();
7198        let queue = Queue::at(dir.path().join("queue"));
7199        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7200        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7201        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7202        let mut first = task();
7203        queue.put(&mut first).unwrap();
7204        let stale_plain = queue.get(&first.id).unwrap();
7205        first.set_urgent(true).unwrap();
7206        queue.put(&mut first).unwrap();
7207        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7208        let mut second = urgent_task("second");
7209        queue.put(&mut second).unwrap();
7210        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7211        drop(queue.claim(&second.id).unwrap());
7212        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7213        drop(dispatched);
7214        let stale_urgent = queue.get(&first.id).unwrap();
7215        first.set_urgent(false).unwrap();
7216        queue.put(&mut first).unwrap();
7217        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7218        assert_eq!(urgent.available_permits(), 1);
7219        drop(queue.claim(&first.id).unwrap());
7220        drop(occupied);
7221    }
7222
7223    #[test]
7224    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7225        let dir = tempfile::tempdir().unwrap();
7226        let queue = Queue::at(dir.path().join("queue"));
7227        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7228        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7229        let mut t = task();
7230        queue.put(&mut t).unwrap();
7231        for enabled in [true, false] {
7232            let stale = queue.get(&t.id).unwrap();
7233            t.set_urgent(enabled).unwrap();
7234            queue.put(&mut t).unwrap();
7235            assert_ne!(stale.urgent, enabled);
7236            let DispatchClaim {
7237                task: fresh,
7238                claim,
7239                permit,
7240            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7241            assert_eq!(fresh.urgent, enabled);
7242            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7243            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7244            assert!(queue.claim(&t.id).is_err());
7245            assert_eq!(fresh.attempts, stale.attempts);
7246            drop((claim, permit));
7247            assert_eq!(ordinary.available_permits(), 1);
7248            assert_eq!(urgent.available_permits(), 1);
7249        }
7250        t.set_urgent(true).unwrap();
7251        queue.put(&mut t).unwrap();
7252        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7253        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7254        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7255        drop(queue.claim(&t.id).unwrap());
7256        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7257        drop(occupied);
7258        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7259        drop(queue.claim(&t.id).unwrap());
7260        let held = queue.claim(&t.id).unwrap();
7261        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7262        drop(held);
7263        t.status = TaskStatus::Held;
7264        queue.put(&mut t).unwrap();
7265        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7266        drop(queue.claim(&t.id).unwrap());
7267        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7268        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7269        drop(queue.claim(&t.id).unwrap());
7270        assert_eq!(urgent.available_permits(), 1);
7271    }
7272
7273    /// The land-resume exemption wins outright, whether or not the candidate
7274    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7275    /// queue behind anything" guarantee cannot be weaker just because the
7276    /// same task was also filed with `--urgent`.
7277    #[test]
7278    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7279        assert_eq!(permit_kind(true, false), PermitKind::None);
7280        assert_eq!(permit_kind(true, true), PermitKind::None);
7281    }
7282
7283    /// The one property this whole feature exists for: `--urgent` draws from
7284    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7285    /// ordinary candidate draws from the ordinary pool exactly as before,
7286    /// untouched by the urgent slot's existence.
7287    #[test]
7288    fn permit_kind_separates_urgent_from_ordinary() {
7289        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7290        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7291    }
7292
7293    /// The exact wiring `attempt` runs before minting anything: a config's
7294    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7295    /// Free space is injected rather than asked of the real disk - the point
7296    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7297    /// is deterministic on every machine this test runs on, never dependent
7298    /// on how full the CI runner's own disk happens to be.
7299    #[test]
7300    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7301        let cfg = Config::default();
7302        let repo = Path::new("/any/repo/path");
7303
7304        let reason =
7305            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7306        assert!(reason.contains("1024"), "{reason}");
7307        assert!(
7308            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7309            "{reason}"
7310        );
7311
7312        assert_eq!(
7313            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7314            None,
7315            "exactly at the floor is open"
7316        );
7317        assert_eq!(
7318            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7319            None,
7320            "comfortably above the floor is open"
7321        );
7322    }
7323
7324    #[test]
7325    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7326        let mut cfg = Config::default();
7327        cfg.disk.min_free_bytes = 0;
7328        let repo = Path::new("/any/repo/path");
7329        assert_eq!(
7330            disk_gate_with(repo, &cfg, |_| Ok(0)),
7331            None,
7332            "a zero floor never measures at all"
7333        );
7334    }
7335
7336    #[test]
7337    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7338        let cfg = Config::default();
7339        let repo = Path::new("/any/repo/path");
7340        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7341            .expect("a measurement failure must close the gate, not open it");
7342        assert!(reason.contains("could not measure"), "{reason}");
7343    }
7344
7345    #[test]
7346    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7347        let ordinary = task();
7348        let next = advance_interrupt(
7349            Interrupt::Idle,
7350            std::slice::from_ref(&ordinary.id),
7351            std::slice::from_ref(&ordinary),
7352        );
7353        assert_eq!(next, Interrupt::Idle);
7354    }
7355
7356    #[test]
7357    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7358        // Nothing to interrupt - this is just an ordinary candidate, and the
7359        // loop's normal dispatch will pick it up like any other.
7360        let marked = interrupt_task("marked");
7361        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7362        assert_eq!(next, Interrupt::Idle);
7363    }
7364
7365    #[test]
7366    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7367        let marked = interrupt_task("marked");
7368        let next = advance_interrupt(
7369            Interrupt::Idle,
7370            &["running".to_owned()],
7371            std::slice::from_ref(&marked),
7372        );
7373        assert_eq!(
7374            next,
7375            Interrupt::Parking {
7376                parked: vec!["running".to_owned()],
7377                interrupt_task: "marked".to_owned(),
7378            }
7379        );
7380    }
7381
7382    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
7383    /// one run can be in flight when a task becomes runnable and marked.
7384    /// Parking all of them would mean `Resuming` later has more than one id
7385    /// to release back to ordinary dispatch, which cannot be made safe
7386    /// against that same setting's own extra concurrency slots letting two
7387    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
7388    /// The simplification the task's own constraints ask for: do not begin
7389    /// a sequence at all until the herd settles back to exactly one.
7390    #[test]
7391    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7392        let marked = interrupt_task("marked");
7393
7394        let two = advance_interrupt(
7395            Interrupt::Idle,
7396            &["a".to_owned(), "b".to_owned()],
7397            std::slice::from_ref(&marked),
7398        );
7399        assert_eq!(two, Interrupt::Idle);
7400
7401        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7402        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7403    }
7404
7405    #[test]
7406    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7407        let state = Interrupt::Parking {
7408            parked: vec!["running".to_owned()],
7409            interrupt_task: "marked".to_owned(),
7410        };
7411        // Still in flight: no change.
7412        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7413        assert_eq!(still_going, state);
7414
7415        // Left flight, but the interrupt task has not been dispatched yet on
7416        // this tick - stays `Parking` so `interrupt_gate` can let it through,
7417        // as long as it is still runnable.
7418        let stopped_but_not_yet_dispatched =
7419            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7420        assert_eq!(stopped_but_not_yet_dispatched, state);
7421
7422        // Left flight, and the interrupt task is now in flight itself.
7423        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7424        assert_eq!(
7425            dispatched,
7426            Interrupt::Running {
7427                parked: vec!["running".to_owned()],
7428                interrupt_task: "marked".to_owned(),
7429            }
7430        );
7431    }
7432
7433    #[test]
7434    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7435        let state = Interrupt::Running {
7436            parked: vec!["running".to_owned()],
7437            interrupt_task: "marked".to_owned(),
7438        };
7439        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7440        assert_eq!(still_running, state);
7441
7442        // Whatever it ended as - merged, failed, held - is not this
7443        // function's concern: leaving flight is the only trigger, driven
7444        // straight off the same in-flight list `poll` already reaps. It does
7445        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
7446        // why that would let an unrelated task start ahead of, or alongside,
7447        // the guaranteed resume.
7448        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7449        assert_eq!(
7450            ended,
7451            Interrupt::Resuming {
7452                parked: vec!["running".to_owned()]
7453            }
7454        );
7455    }
7456
7457    #[test]
7458    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7459        let state = Interrupt::Resuming {
7460            parked: vec!["running".to_owned()],
7461        };
7462        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7463        assert_eq!(still_waiting, state);
7464
7465        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7466        assert_eq!(dispatched, Interrupt::Idle);
7467    }
7468
7469    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
7470    /// or otherwise moved on by an operator with no claim standing in the
7471    /// way - must not wedge the sequence (and so the whole loop's dispatch,
7472    /// via `interrupt_gate`) waiting forever for a dispatch that can never
7473    /// come. The parked run still gets its resume.
7474    #[test]
7475    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7476    {
7477        let state = Interrupt::Parking {
7478            parked: vec!["running".to_owned()],
7479            interrupt_task: "marked".to_owned(),
7480        };
7481        // `marked` has been held/blocked/deleted since the sequence began:
7482        // it no longer appears in `runnable` at all.
7483        let next = advance_interrupt(state, &[], &[]);
7484        assert_eq!(
7485            next,
7486            Interrupt::Resuming {
7487                parked: vec!["running".to_owned()]
7488            },
7489            "abandoning the interrupt must not abandon the resume it owes"
7490        );
7491    }
7492
7493    /// The same abandonment, one step later: `Resuming` itself must not wait
7494    /// forever for a parked task that has since become unrunnable.
7495    #[test]
7496    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7497        let state = Interrupt::Resuming {
7498            parked: vec!["running".to_owned()],
7499        };
7500        let next = advance_interrupt(state, &[], &[]);
7501        assert_eq!(
7502            next,
7503            Interrupt::Idle,
7504            "nothing is left to wait for; the loop must not stay wedged"
7505        );
7506    }
7507
7508    #[test]
7509    fn disabled_by_config_the_sequence_can_never_leave_idle() {
7510        let marked = interrupt_task("marked");
7511        let next = advance_interrupt_tick(
7512            false,
7513            Interrupt::Idle,
7514            &["running".to_owned()],
7515            std::slice::from_ref(&marked),
7516        );
7517        assert_eq!(
7518            next,
7519            Interrupt::Idle,
7520            "an unmarked, unconfigured daemon must behave exactly as before"
7521        );
7522    }
7523
7524    #[test]
7525    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7526        let state = Interrupt::Parking {
7527            parked: vec!["running".to_owned()],
7528            interrupt_task: "marked".to_owned(),
7529        };
7530        let candidates = vec![interrupt_task("marked"), task()];
7531        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7532        assert!(
7533            allowed.is_empty(),
7534            "nothing may dispatch - not even the interrupt task itself - \
7535             until the parked run has actually stopped"
7536        );
7537    }
7538
7539    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
7540    /// grow a special case for it: an urgent candidate that is not the
7541    /// interrupt task withholds exactly like an ordinary one for as long as
7542    /// the parked run it is racing has not actually left flight. A version
7543    /// of this feature once bypassed the gate for urgent candidates, on the
7544    /// theory that a genuinely separate concurrency lane could not collide
7545    /// with 75dd's own; it could, and did - the bypassed task dispatched
7546    /// alongside a run 75dd's own state machine had only *asked* to park,
7547    /// not yet confirmed gone, which is exactly the second run
7548    /// `Interrupt::Parking`'s own doc says must never happen. There is no
7549    /// tick during Parking/Running/Resuming where letting an extra
7550    /// candidate through is safe, urgent or not - the parked run may still
7551    /// be genuinely mid-call.
7552    #[test]
7553    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7554        for state in [
7555            Interrupt::Parking {
7556                parked: vec!["running".to_owned()],
7557                interrupt_task: "marked".to_owned(),
7558            },
7559            Interrupt::Running {
7560                parked: vec!["running".to_owned()],
7561                interrupt_task: "marked".to_owned(),
7562            },
7563            Interrupt::Resuming {
7564                parked: vec!["running".to_owned()],
7565            },
7566        ] {
7567            let candidates = vec![
7568                interrupt_task("marked"),
7569                urgent_task("hot"),
7570                task_with_id("ordinary"),
7571            ];
7572            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7573            assert!(
7574                !allowed.iter().any(|t| t.id == "hot"),
7575                "an urgent candidate must wait out the same gate as anything \
7576                 else while the run it would run alongside has not actually \
7577                 left flight, for state {state:?}: {allowed:?}"
7578            );
7579        }
7580    }
7581
7582    /// The one case where marking a task `--urgent` and `interrupt` at once
7583    /// is not redundant: once the interrupt sequence's own guaranteed
7584    /// resume/dispatch actually admits the task, it is unaffected by also
7585    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
7586    /// never on the urgent flag.
7587    #[test]
7588    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7589        let state = Interrupt::Resuming {
7590            parked: vec!["hot".to_owned()],
7591        };
7592        let candidates = vec![urgent_task("hot"), task()];
7593        let allowed = interrupt_gate(&state, &[], candidates);
7594        assert_eq!(
7595            allowed.iter().filter(|t| t.id == "hot").count(),
7596            1,
7597            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7598        );
7599    }
7600
7601    #[test]
7602    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7603        let state = Interrupt::Parking {
7604            parked: vec!["running".to_owned()],
7605            interrupt_task: "marked".to_owned(),
7606        };
7607        let other = task();
7608        let candidates = vec![interrupt_task("marked"), other.clone()];
7609        let allowed = interrupt_gate(&state, &[], candidates);
7610        assert_eq!(allowed.len(), 1);
7611        assert_eq!(allowed[0].id, "marked");
7612    }
7613
7614    #[test]
7615    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7616        let state = Interrupt::Running {
7617            parked: vec!["running".to_owned()],
7618            interrupt_task: "marked".to_owned(),
7619        };
7620        let candidates = vec![task(), task()];
7621        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7622        assert!(allowed.is_empty());
7623    }
7624
7625    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
7626    /// sequence began (only reachable above the default
7627    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
7628    /// never both in the same tick, which is what "exactly one resume, no
7629    /// simultaneous run" actually requires structurally rather than by
7630    /// coincidence of how many ordinary slots happen to be free.
7631    #[test]
7632    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7633        let state = Interrupt::Resuming {
7634            parked: vec!["a".to_owned(), "c".to_owned()],
7635        };
7636        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7637        let allowed = interrupt_gate(&state, &[], candidates);
7638        assert_eq!(
7639            allowed.len(),
7640            1,
7641            "at most one candidate may be offered while resuming: {allowed:?}"
7642        );
7643        assert_eq!(allowed[0].id, "a");
7644    }
7645
7646    #[test]
7647    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7648        let state = Interrupt::Resuming {
7649            parked: vec!["a".to_owned()],
7650        };
7651        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7652        assert!(allowed.is_empty());
7653    }
7654
7655    /// The invariant the completion criteria ask for by name: across a whole
7656    /// simulated sequence, there is never a tick where the gate would let
7657    /// through both the parked run's resume and the interrupt task, and
7658    /// exactly one candidate resumes the instant the interrupt task's run
7659    /// ends - never zero, never more than one.
7660    #[test]
7661    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7662        let running = task(); // id: whatever `Task::new` minted
7663        let marked = interrupt_task("marked");
7664
7665        let mut state = Interrupt::Idle;
7666        // Tick 1: `running` is in flight, `marked` becomes runnable.
7667        let in_flight = vec![running.id.clone()];
7668        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7669        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7670        assert!(gated.is_empty(), "still waiting on `running` to park");
7671
7672        // Tick 2: `running` parked and left flight; nothing dispatched yet.
7673        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7674        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7675        assert_eq!(
7676            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7677            vec!["marked"],
7678            "only the interrupt task may be offered to the dispatcher now"
7679        );
7680
7681        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
7682        state = advance_interrupt_tick(
7683            true,
7684            state,
7685            &["marked".to_owned()],
7686            std::slice::from_ref(&running),
7687        );
7688        let gated = interrupt_gate(
7689            &state,
7690            &["marked".to_owned()],
7691            vec![marked.clone(), running.clone()],
7692        );
7693        assert!(
7694            gated.is_empty(),
7695            "the parked run must not be offered back while the interrupt \
7696             task is still running"
7697        );
7698
7699        // Tick 4: `marked`'s run reached a terminal status and left flight.
7700        // A higher-priority ordinary task `other` is also runnable now - it
7701        // must not be let through instead of, or alongside, `running`.
7702        let other = task_with_id("other");
7703        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7704        assert_eq!(
7705            state,
7706            Interrupt::Resuming {
7707                parked: vec![running.id.clone()]
7708            }
7709        );
7710        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7711        assert_eq!(
7712            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7713            vec![running.id.as_str()],
7714            "exactly the parked run resumes - not the unrelated task, even \
7715             though it was offered first"
7716        );
7717
7718        // Tick 5: `running` is now in flight (dispatched from tick 4's
7719        // gate). Only now does the sequence end and ordinary dispatch fully
7720        // resume.
7721        state = advance_interrupt_tick(
7722            true,
7723            state,
7724            std::slice::from_ref(&running.id),
7725            std::slice::from_ref(&other),
7726        );
7727        assert_eq!(state, Interrupt::Idle);
7728        let gated = interrupt_gate(
7729            &state,
7730            std::slice::from_ref(&running.id),
7731            vec![other.clone()],
7732        );
7733        assert_eq!(
7734            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7735            vec![other.id.as_str()],
7736            "ordinary dispatch is unrestricted again"
7737        );
7738    }
7739
7740    #[test]
7741    fn every_run_status_settles_the_task_it_came_from() {
7742        // run status, resulting task status, attempts still standing after one
7743        let table = [
7744            (RunStatus::Merged, TaskStatus::Done, 1),
7745            (RunStatus::Ready, TaskStatus::Done, 1),
7746            (RunStatus::Stalled, TaskStatus::Failed, 0),
7747            (RunStatus::Blocked, TaskStatus::Failed, 1),
7748            (RunStatus::Failed, TaskStatus::Failed, 1),
7749            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
7750            (RunStatus::Prep, TaskStatus::Failed, 1),
7751            (RunStatus::Implementing, TaskStatus::Failed, 1),
7752            (RunStatus::Judging, TaskStatus::Failed, 1),
7753            (RunStatus::Deliberating, TaskStatus::Failed, 1),
7754            (RunStatus::Voting, TaskStatus::Failed, 1),
7755            (RunStatus::Reviewing, TaskStatus::Failed, 1),
7756            (RunStatus::Gating, TaskStatus::Failed, 1),
7757        ];
7758        for (run, want, attempts) in table {
7759            let mut t = task();
7760            t.start("20260902-000000-aaaa".to_owned());
7761            settle(
7762                &mut t,
7763                Verdict {
7764                    status: run,
7765                    left_pr: false,
7766                    parked: false,
7767                    quota_hit: matches!(run, RunStatus::Stalled),
7768                    no_viable_candidates: false,
7769                },
7770                "why",
7771                2,
7772            );
7773            assert_eq!(t.status, want, "task status after {}", label(run));
7774            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
7775        }
7776    }
7777
7778    #[test]
7779    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
7780        let mut stalled = task();
7781        stalled.start("20260902-000000-aaaa".to_owned());
7782        settle(
7783            &mut stalled,
7784            Verdict {
7785                status: RunStatus::Stalled,
7786                left_pr: false,
7787                parked: false,
7788                quota_hit: true,
7789                no_viable_candidates: false,
7790            },
7791            "quota",
7792            1,
7793        );
7794        assert_eq!(stalled.attempts, 0);
7795        assert!(
7796            stalled.status.runnable(),
7797            "a machine problem must leave the task in line"
7798        );
7799
7800        let mut blocked = task();
7801        blocked.start("20260902-000000-aaaa".to_owned());
7802        settle(
7803            &mut blocked,
7804            Verdict {
7805                status: RunStatus::Blocked,
7806                left_pr: false,
7807                parked: false,
7808                quota_hit: false,
7809                no_viable_candidates: false,
7810            },
7811            "findings open",
7812            1,
7813        );
7814        assert_eq!(blocked.attempts, 1);
7815        assert_eq!(
7816            blocked.status,
7817            TaskStatus::Held,
7818            "the last attempt hands the task to a human"
7819        );
7820    }
7821
7822    #[test]
7823    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
7824        // Attempts to spare: without the pull request this task would go
7825        // straight back in line and run the whole competition again.
7826        let mut delivered = task();
7827        delivered.start("20260903-080619-01c2".to_owned());
7828        settle(
7829            &mut delivered,
7830            Verdict {
7831                status: RunStatus::Blocked,
7832                left_pr: true,
7833                parked: false,
7834                quota_hit: false,
7835                no_viable_candidates: false,
7836            },
7837            "no check status",
7838            4,
7839        );
7840        assert_eq!(
7841            delivered.status,
7842            TaskStatus::Held,
7843            "a pull request waiting on CI or a person is not a retryable failure"
7844        );
7845        assert!(
7846            !delivered.status.runnable(),
7847            "the loop must not pick this task up again"
7848        );
7849        assert_eq!(
7850            delivered.last_error.as_deref(),
7851            Some("no check status"),
7852            "the operator needs to be told what the gate was waiting for"
7853        );
7854
7855        // The same status without a pull request is a plain failure, and with
7856        // attempts left it is retried.
7857        let mut empty_handed = task();
7858        empty_handed.start("20260903-080619-01c2".to_owned());
7859        settle(
7860            &mut empty_handed,
7861            Verdict {
7862                status: RunStatus::Blocked,
7863                left_pr: false,
7864                parked: false,
7865                quota_hit: false,
7866                no_viable_candidates: false,
7867            },
7868            "findings open",
7869            4,
7870        );
7871        assert_eq!(empty_handed.status, TaskStatus::Failed);
7872        assert!(empty_handed.status.runnable());
7873    }
7874
7875    #[test]
7876    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
7877        // Every candidate agreed, with evidence, that nothing belonged in the
7878        // worktree. That is not a confirmed success to close automatically -
7879        // a human still has to check the claim - and it is not an ordinary
7880        // failure either, so this settles exactly like a pull request nobody
7881        // merged yet: `Held`, same as `Blocked` with a PR.
7882        let mut noop = task();
7883        noop.start("20260912-131304-391f".to_owned());
7884        settle(
7885            &mut noop,
7886            Verdict {
7887                status: RunStatus::VerifiedNoop,
7888                left_pr: false,
7889                parked: false,
7890                quota_hit: false,
7891                no_viable_candidates: true,
7892            },
7893            "candidate A: already fixed by b32cfc4, on main",
7894            4,
7895        );
7896        assert_eq!(
7897            noop.status,
7898            TaskStatus::Held,
7899            "an unverified claim is a request for a human, not a failure"
7900        );
7901        assert!(
7902            !noop.status.runnable(),
7903            "the loop must not requeue this on the same unverified claim"
7904        );
7905        // `Task::release` resets attempts to zero the moment a human looks at
7906        // the evidence and lets it run again, so it does not matter here
7907        // whether the one attempt already spent stays spent - what matters is
7908        // that nothing retries this task unattended in the meantime.
7909        assert_eq!(noop.attempts, 1);
7910    }
7911
7912    #[test]
7913    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
7914        // Parking is the operator asking for the process back - to replace the
7915        // binary, most of all. The run's work is intact on disk, so this is
7916        // not a failed attempt, and charging for it would mean a few upgrades
7917        // could exhaust a budget meant for agents that misbehaved.
7918        let mut parked = task();
7919        parked.start("20260903-183634-2d98".to_owned());
7920        settle(
7921            &mut parked,
7922            Verdict {
7923                status: RunStatus::Implementing,
7924                left_pr: false,
7925                quota_hit: false,
7926                parked: true,
7927                no_viable_candidates: false,
7928            },
7929            "parked after `implementing`",
7930            2,
7931        );
7932        assert_eq!(parked.attempts, 0, "a park is refunded");
7933        assert!(
7934            parked.status.runnable(),
7935            "and the task stays in line so the next loop resumes its run"
7936        );
7937        assert_eq!(parked.status, TaskStatus::Parked);
7938        assert_eq!(
7939            parked.park_reason.as_deref(),
7940            Some("parked after `implementing`"),
7941            "the card says where it stopped"
7942        );
7943        assert_eq!(parked.last_error, None, "nothing failed");
7944
7945        // Without the park flag the same non-terminal status is what it always
7946        // was: `execute` returning mid-flight, which is a bug and spends an
7947        // attempt so a task cannot loop on it forever.
7948        let mut broken = task();
7949        broken.start("20260903-183634-2d98".to_owned());
7950        settle(
7951            &mut broken,
7952            Verdict {
7953                status: RunStatus::Implementing,
7954                left_pr: false,
7955                quota_hit: false,
7956                parked: false,
7957                no_viable_candidates: false,
7958            },
7959            "returned mid-flight",
7960            2,
7961        );
7962        assert_eq!(broken.attempts, 1);
7963    }
7964
7965    #[test]
7966    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
7967        // Run e633: quorum lost because two judges answered with the wrong
7968        // JSON shape, `quota: []`. Refunding that takes the bound off the
7969        // retry loop, and each retry pays for a fresh hour-long implement
7970        // wave before it can fail the same way.
7971        let mut flaky = task();
7972        flaky.start("20260903-123023-e633".to_owned());
7973        settle(
7974            &mut flaky,
7975            Verdict {
7976                status: RunStatus::Stalled,
7977                left_pr: false,
7978                parked: false,
7979                quota_hit: false,
7980                no_viable_candidates: false,
7981            },
7982            "verdict rests on 1 of 3 judges",
7983            2,
7984        );
7985        assert_eq!(
7986            flaky.attempts, 1,
7987            "flakiness spends an attempt, so `max_attempts` still bounds it"
7988        );
7989        assert!(flaky.status.runnable(), "and it is still worth retrying");
7990
7991        // The same status, lost to a rate limit, is the machine's fault.
7992        let mut limited = task();
7993        limited.start("20260903-123023-e633".to_owned());
7994        settle(
7995            &mut limited,
7996            Verdict {
7997                status: RunStatus::Stalled,
7998                left_pr: false,
7999                parked: false,
8000                quota_hit: true,
8001                no_viable_candidates: false,
8002            },
8003            "judge-2, judge-3 out of quota",
8004            2,
8005        );
8006        assert_eq!(limited.attempts, 0, "a quota window is refunded");
8007        assert!(limited.status.runnable());
8008
8009        // And the bound really binds: a task that keeps stalling on flakiness
8010        // reaches a human instead of running the roster forever.
8011        let mut worn = task();
8012        for _ in 0..2 {
8013            worn.release();
8014        }
8015        worn.start("20260903-123023-e633".to_owned());
8016        worn.attempts = 2;
8017        settle(
8018            &mut worn,
8019            Verdict {
8020                status: RunStatus::Stalled,
8021                left_pr: false,
8022                parked: false,
8023                quota_hit: false,
8024                no_viable_candidates: false,
8025            },
8026            "no quorum again",
8027            2,
8028        );
8029        assert_eq!(worn.status, TaskStatus::Held);
8030        assert!(!worn.status.runnable());
8031    }
8032
8033    #[test]
8034    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8035        // The implement wave loses every seat to the same rate limit and
8036        // `after_implement` bails with nothing viable, which surfaces as
8037        // `Failed` rather than `Stalled`. That is the same machine fact the
8038        // `Stalled`-quota row already refunds, and must be refunded the same
8039        // way, or a quota outage quietly holds every task it touches instead
8040        // of leaving them in line for the reset.
8041        let mut wiped_out = task();
8042        wiped_out.start("20260907-025000-a1b2".to_owned());
8043        settle(
8044            &mut wiped_out,
8045            Verdict {
8046                status: RunStatus::Failed,
8047                left_pr: false,
8048                parked: false,
8049                quota_hit: true,
8050                no_viable_candidates: true,
8051            },
8052            "no candidate produced a change; nothing to judge",
8053            2,
8054        );
8055        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8056        assert!(
8057            wiped_out.status.runnable(),
8058            "a machine problem must leave the task in line"
8059        );
8060
8061        // This is the exemption that must stay narrow: a candidate that did
8062        // produce a change, and then failed for some other reason, still
8063        // spends the attempt even though a seat elsewhere hit its quota.
8064        // Otherwise every ordinary failure that happens to share a run with
8065        // an unrelated rate limit would be refunded for free.
8066        let mut partial_progress = task();
8067        partial_progress.start("20260907-025500-c3d4".to_owned());
8068        settle(
8069            &mut partial_progress,
8070            Verdict {
8071                status: RunStatus::Failed,
8072                left_pr: false,
8073                parked: false,
8074                quota_hit: true,
8075                no_viable_candidates: false,
8076            },
8077            "gate failed on the winning candidate",
8078            2,
8079        );
8080        assert_eq!(
8081            partial_progress.attempts, 1,
8082            "a candidate that actually produced a change spends the attempt \
8083             even though some other seat hit its quota"
8084        );
8085        assert!(partial_progress.status.runnable());
8086    }
8087
8088    #[test]
8089    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8090        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
8091        // disk, and that construction must reach the same conclusion as the
8092        // one `attempt` builds from a live run, or a crash at exactly the
8093        // wrong moment gives a recovered task a different policy than one a
8094        // daemon finished settling itself.
8095        let mut t = task();
8096        t.start("20260907-025000-a1b2".to_owned());
8097        let mut state = run_state(RunStatus::Failed);
8098        state.quota.push(QuotaLoss {
8099            cause: crate::agent::QuotaCause::UsageLimit,
8100            agent: String::new(),
8101            seat: "cand-a".to_owned(),
8102            node: "implement".to_owned(),
8103            at: Timestamp::now(),
8104            reset: None,
8105        });
8106        assert!(
8107            state.viable().is_empty(),
8108            "no candidate was added, so nothing is viable"
8109        );
8110        reclaim(&mut t, Some(state), 2, "en");
8111        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8112        assert!(t.status.runnable());
8113    }
8114
8115    #[test]
8116    fn a_held_task_is_never_offered_to_the_loop() {
8117        let dir = tempfile::tempdir().unwrap();
8118        let queue = Queue::at(dir.path().to_path_buf());
8119        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8120            let mut t = task();
8121            t.id = format!("2026090{n}-000000-000{n}");
8122            t.priority = priority;
8123            queue.put(&mut t).unwrap();
8124        }
8125        let mut held = task();
8126        held.id = "20260909-000000-9999".to_owned();
8127        held.priority = 99;
8128        held.hold_machine(None);
8129        queue.put(&mut held).unwrap();
8130
8131        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8132        assert_eq!(order.len(), 3);
8133        assert!(!order.contains(&held.id));
8134        assert_eq!(
8135            order.first().cloned(),
8136            queue.next_runnable().map(|t| t.id),
8137            "the loop's first candidate is exactly what the queue offers"
8138        );
8139        assert_eq!(
8140            order,
8141            vec![
8142                "20260902-000000-0002".to_owned(),
8143                "20260903-000000-0003".to_owned(),
8144                "20260901-000000-0001".to_owned(),
8145            ],
8146            "priority first, then oldest, so nothing starves"
8147        );
8148    }
8149
8150    #[test]
8151    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8152        let dir = tempfile::tempdir().unwrap();
8153        let queue = Queue::at(dir.path().to_path_buf());
8154        let mut old = task();
8155        old.id = "20260101-000000-old0".to_owned();
8156        queue.put(&mut old).unwrap();
8157        let mut fresh = task();
8158        fresh.id = "20260101-000000-new0".to_owned();
8159        queue.put(&mut fresh).unwrap();
8160
8161        // No parseable pid at all, so age is the only signal there is to
8162        // check - unlike a real `Queue::claim`, which always names a real,
8163        // and therefore alive, pid this test cannot fake as dead.
8164        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8165        std::thread::sleep(Duration::from_millis(60));
8166        let live = queue.claim(&fresh.id).unwrap();
8167
8168        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8169        assert_eq!(swept, vec![old.id.clone()]);
8170        assert!(
8171            queue.claim(&old.id).is_ok(),
8172            "an unparseable lock older than the threshold is swept"
8173        );
8174        assert!(
8175            queue.claim(&fresh.id).is_err(),
8176            "a live pid protects its lock regardless of age"
8177        );
8178        drop(live);
8179    }
8180
8181    #[test]
8182    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8183        // A live worker's claim remains authoritative even beyond the sweep's
8184        // age limit. Sweeping it would permit a second competing attempt.
8185        let dir = tempfile::tempdir().unwrap();
8186        let queue = Queue::at(dir.path().to_path_buf());
8187        let mut t = task();
8188        t.id = "20260101-000000-live".to_owned();
8189        queue.put(&mut t).unwrap();
8190
8191        let claim = queue.claim(&t.id).unwrap();
8192        std::thread::sleep(Duration::from_millis(60));
8193
8194        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8195        assert!(
8196            swept.is_empty(),
8197            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8198        );
8199        assert!(
8200            queue.claim(&t.id).is_err(),
8201            "the lock still protects its task"
8202        );
8203        drop(claim);
8204    }
8205
8206    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8207    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8208    fn injected_dead_pid() -> u32 {
8209        std::process::id().checked_add(1).unwrap_or(1)
8210    }
8211
8212    #[test]
8213    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8214        let dir = tempfile::tempdir().unwrap();
8215        let queue = Queue::at(dir.path().to_path_buf());
8216        let mut t = task();
8217        t.id = "20260101-000000-dead".to_owned();
8218        queue.put(&mut t).unwrap();
8219        let dead_pid = injected_dead_pid();
8220
8221        // Written directly rather than through `Queue::claim`, which would
8222        // stamp this test process's own very much alive pid and defeat the
8223        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8224        // like moments after it died, not six hours later.
8225        std::fs::write(
8226            dir.path().join(format!("{}.lock", t.id)),
8227            dead_pid.to_string(),
8228        )
8229        .unwrap();
8230
8231        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8232            pid != dead_pid
8233        });
8234        assert_eq!(
8235            swept,
8236            vec![t.id.clone()],
8237            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8238        );
8239        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8240    }
8241
8242    #[test]
8243    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8244        let dir = tempfile::tempdir().unwrap();
8245        let queue = Queue::at(dir.path().to_path_buf());
8246        let mut t = task();
8247        t.id = "20260101-000000-late".to_owned();
8248        queue.put(&mut t).unwrap();
8249        let dead_pid = injected_dead_pid();
8250
8251        // Tick one, standing in for the sweep `poll` already runs at
8252        // startup: nothing to find yet.
8253        assert!(
8254            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8255            "nothing has claimed the task yet"
8256        );
8257
8258        // A second daemon claims the task and dies before it ever writes
8259        // `running`, well after this loop's own startup sweep already ran.
8260        std::fs::write(
8261            dir.path().join(format!("{}.lock", t.id)),
8262            dead_pid.to_string(),
8263        )
8264        .unwrap();
8265
8266        // Tick two, standing in for a poll long into this daemon's uptime:
8267        // the same function, called again, notices what only just appeared -
8268        // proving the sweep is not a one-shot startup check.
8269        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8270            pid != dead_pid
8271        });
8272        assert_eq!(swept, vec![t.id.clone()]);
8273    }
8274
8275    #[test]
8276    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8277        // `reclaim_orphaned_running` looks up the task's last run, which
8278        // touches `run::home()`; the first call anywhere in this binary wins,
8279        // so this is a no-op if another test already pinned one, and either
8280        // way the run id below is never written under it.
8281        crate::run::pin_test_home();
8282        let dir = tempfile::tempdir().unwrap();
8283        let queue = Queue::at(dir.path().to_path_buf());
8284        let mut t = task();
8285        t.id = "20260101-000000-crsh".to_owned();
8286        t.status = TaskStatus::Running;
8287        t.attempts = 1;
8288        // No `run.json` behind this id: standing in for a run this test does
8289        // not need to make readable, since the point is the lock, not the
8290        // recovery table `reclaim` already has its own tests for.
8291        t.runs.push("20260904-000000-4043".to_owned());
8292        queue.put(&mut t).unwrap();
8293        let dead_pid = injected_dead_pid();
8294
8295        // The crashed daemon's own claim, naming a pid nothing on the
8296        // machine holds anymore.
8297        std::fs::write(
8298            dir.path().join(format!("{}.lock", t.id)),
8299            dead_pid.to_string(),
8300        )
8301        .unwrap();
8302
8303        // Before the lock is swept the task looks claimed, and
8304        // `reclaim_orphaned_running` must leave it alone - this is exactly
8305        // the bug: a `running` task stranded behind a dead daemon's lock,
8306        // invisible to the claim-as-proof check because the lock outlived
8307        // the process that wrote it.
8308        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8309        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8310
8311        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8312            pid != dead_pid
8313        });
8314        assert_eq!(swept, vec![t.id.clone()]);
8315
8316        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8317        assert_eq!(reclaimed, vec![t.id.clone()]);
8318        let after = queue.get(&t.id).unwrap();
8319        assert_eq!(
8320            after.status,
8321            TaskStatus::Held,
8322            "no run.json to recover from, so a human is asked"
8323        );
8324        assert_eq!(
8325            after.runs,
8326            vec!["20260904-000000-4043".to_owned()],
8327            "the crashed run's id is kept as evidence, not discarded"
8328        );
8329    }
8330
8331    #[test]
8332    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8333        let dir = tempfile::tempdir().unwrap();
8334        let queue = Queue::at(dir.path().to_path_buf());
8335        let mut t = task();
8336        t.id = "20260101-000000-unknown".to_owned();
8337        queue.put(&mut t).unwrap();
8338        let dead_pid = injected_dead_pid();
8339        std::fs::write(
8340            dir.path().join(format!("{}.lock", t.id)),
8341            dead_pid.to_string(),
8342        )
8343        .unwrap();
8344
8345        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8346        assert!(swept.is_empty(), "an unknown pid must keep its lock");
8347        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8348    }
8349
8350    fn run_state_in(status: RunStatus, language: &str) -> RunState {
8351        let mut s = run_state(status);
8352        s.config.graph.language = language.to_owned();
8353        s
8354    }
8355
8356    fn unstarted_verdict(status: RunStatus) -> Verdict {
8357        Verdict {
8358            status,
8359            left_pr: false,
8360            quota_hit: false,
8361            parked: false,
8362            no_viable_candidates: false,
8363        }
8364    }
8365
8366    #[test]
8367    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8368        let mut t = task();
8369        t.attempts = 1;
8370        settle_in(
8371            &mut t,
8372            unstarted_verdict(RunStatus::AlreadyInBase),
8373            "already in main",
8374            1,
8375            phrases("en"),
8376        );
8377        assert_eq!(t.status, TaskStatus::Done);
8378        assert_eq!(t.attempts, 0);
8379    }
8380
8381    #[test]
8382    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8383        let reason = |language: &str| {
8384            let mut t = task();
8385            settle_in(
8386                &mut t,
8387                unstarted_verdict(RunStatus::Judging),
8388                "boom",
8389                1,
8390                phrases(language),
8391            );
8392            t.last_error.or(t.hold_reason).unwrap_or_default()
8393        };
8394        assert!(
8395            reason("en").starts_with("the graph stopped at `"),
8396            "{}",
8397            reason("en")
8398        );
8399        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8400        assert!(reason("日本語").contains("boom"));
8401        assert_eq!(reason("fr"), reason("en"));
8402    }
8403
8404    #[test]
8405    fn describe_follows_the_run_language_and_keeps_the_run_id() {
8406        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8407        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8408        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8409        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8410        assert!(ja.contains("[run "), "{ja}");
8411        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8412        assert!(ended.starts_with("run 終了: "), "{ended}");
8413        let mut de = run_state_in(RunStatus::Failed, "de");
8414        let mut en = run_state_in(RunStatus::Failed, "en");
8415        de.id = "same".to_owned();
8416        en.id = "same".to_owned();
8417        assert_eq!(describe(&de), describe(&en));
8418    }
8419
8420    #[test]
8421    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8422        use crate::handover::Refused;
8423        let cases = [
8424            Refused::Foreign {
8425                branch: "b".into(),
8426                path: "/w/x".into(),
8427                why: "made by hand".into(),
8428            },
8429            Refused::Unsafe {
8430                branch: "b".into(),
8431                path: "/w/x".into(),
8432                why: "its worktree has uncommitted changes (a.rs)".into(),
8433            },
8434            Refused::ReleaseFailed {
8435                branch: "b".into(),
8436                path: "/w/x".into(),
8437                run: "ab12".into(),
8438            },
8439        ];
8440        for r in &cases {
8441            let en = (phrases("en").handover_refused)(r);
8442            assert_eq!(en, r.to_string());
8443            let ja = (phrases("ja").handover_refused)(r);
8444            assert!(
8445                !ja.contains("is checked out") && !ja.contains("try again"),
8446                "{ja}"
8447            );
8448            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8449            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8450                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8451            }
8452        }
8453        assert!(phrases("en").handover_hint.contains("release the task"));
8454        assert!(phrases("ja").handover_hint.contains("解放"));
8455    }
8456
8457    #[test]
8458    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8459        let build = |lang: &str| {
8460            let mut s = run_state_in(RunStatus::Blocked, lang);
8461            s.id = "same".to_owned();
8462            s.config.graph.review_rounds = 3;
8463            let mut r = review_round(3);
8464            r.expected = 3;
8465            r.answered = 1;
8466            s.reviews.push(r);
8467            s.event(
8468                "review",
8469                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8470            );
8471            s
8472        };
8473        let en = describe(&build("en"));
8474        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8475        let ja = describe(&build("ja"));
8476        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8477        assert!(!ja.contains("never answered"), "{ja}");
8478        assert!(ja.contains("[run "), "{ja}");
8479
8480        // An incomplete panel whose verification failed is a different stop:
8481        // the real event must survive in ja too.
8482        let mut failed = build("ja");
8483        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8484            command: "cargo test".to_owned(),
8485            code: Some(1),
8486            output_tail: String::new(),
8487            duration_ms: 0,
8488            resource_blocked: false,
8489        });
8490        failed.event("review", "stopped; e2e failed: cargo test");
8491        let ja = describe(&failed);
8492        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8493        assert!(!ja.contains("席のレビュアー"), "{ja}");
8494    }
8495
8496    #[test]
8497    fn refusals_and_recovery_prose_follow_the_language() {
8498        let home = crate::run::test_home();
8499        let t = held_task_with("r1");
8500        let q = action_question(
8501            "r1",
8502            ask::ChoiceAction::Resume {
8503                run: "r1".to_owned(),
8504            },
8505        );
8506        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
8507            ActionDecision::Refuse(s) => s,
8508            other => panic!("{other:?}"),
8509        };
8510        assert!(refuse(phrases("en")).contains("could not be read: gone"));
8511        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8512        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8513
8514        let mut held = task();
8515        reclaim(&mut held, None, 2, "ja");
8516        assert!(held.hold_reason.unwrap().contains("保留にしました"));
8517        let mut held = task();
8518        reclaim(&mut held, None, 2, "xx");
8519        assert!(held.hold_reason.unwrap().contains("held for a human"));
8520    }
8521
8522    fn run_state(status: RunStatus) -> RunState {
8523        let mut state = RunState::new(
8524            PathBuf::from("/repo"),
8525            "main".to_owned(),
8526            "abc1234def".to_owned(),
8527            "add retries".to_owned(),
8528            Config::default(),
8529        );
8530        state.status = status;
8531        state
8532    }
8533
8534    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8535        Candidate {
8536            index: 0,
8537            label,
8538            agent: "claude".to_owned(),
8539            branch: format!("magi/x/{label}"),
8540            worktree: PathBuf::from("/repo"),
8541            summary: summary.to_owned(),
8542            stat: String::new(),
8543            files: 0,
8544            commits: usize::from(!empty),
8545            empty,
8546            failed: failed.map(str::to_owned),
8547            verified_noop: None,
8548            duration_ms: 0,
8549            folded: false,
8550        }
8551    }
8552
8553    #[test]
8554    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8555        let mut state = run_state(RunStatus::Blocked);
8556        state.gate = vec![
8557            CommandOutcome {
8558                command: "cargo make check".to_owned(),
8559                code: Some(0),
8560                output_tail: "ok".to_owned(),
8561                duration_ms: 0,
8562                resource_blocked: false,
8563            },
8564            CommandOutcome {
8565                command: "cargo test".to_owned(),
8566                code: Some(101),
8567                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8568                duration_ms: 0,
8569                resource_blocked: false,
8570            },
8571        ];
8572        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8573        assert!(d.contains("cargo test"), "{d}");
8574        assert!(
8575            !d.contains("cargo make check"),
8576            "a passing check is not a diagnostic: {d}"
8577        );
8578        assert!(d.contains("assertion failed"), "{d}");
8579    }
8580
8581    #[test]
8582    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8583        let mut state = run_state(RunStatus::Blocked);
8584        state.event(
8585            "land",
8586            "stopped: the fixer produced no commit while 2 check(s) were failing \
8587             (build, lint); stopping instead of looping on an unchanged tree",
8588        );
8589        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8590        assert!(d.contains("build"), "{d}");
8591        assert!(d.contains("lint"), "{d}");
8592        assert!(d.contains("fixer produced no commit"), "{d}");
8593    }
8594
8595    #[test]
8596    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8597        // `describe`'s output becomes `Task::last_error` verbatim, and the
8598        // phone renders that in the same alarm-styled box an ordinary
8599        // failure gets. A bare `verified_noop` there would read exactly like
8600        // the failure this status exists to be told apart from.
8601        let state = run_state(RunStatus::VerifiedNoop);
8602        let d = describe(&state);
8603        assert!(
8604            d.contains("agent-verified no-op"),
8605            "expected the display label, not the wire spelling: {d}"
8606        );
8607        assert!(!d.contains("verified_noop"), "{d}");
8608    }
8609
8610    #[test]
8611    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
8612        let mut state = run_state(RunStatus::Failed);
8613        state.gate.push(crate::run::CommandOutcome {
8614            command: "cargo test".into(),
8615            code: Some(101),
8616            output_tail: format!(
8617                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8618                "  41: 0x1234 - backtrace frame\n".repeat(10000)
8619            ),
8620            duration_ms: 1,
8621            resource_blocked: false,
8622        });
8623        let d = diagnostic(&state).unwrap();
8624        assert!(d.contains("panicked at widget.rs:12"), "{d}");
8625        assert!(d.contains("assertion failed: widget missing"));
8626        assert!(d.contains("widget log"));
8627    }
8628
8629    #[test]
8630    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8631        // The whole point of the feature: a run held as "no candidate produced
8632        // a change" can mean the implementer actually finished the task and
8633        // only left a clean local tree behind - see AGENTS.md on this exact
8634        // failure mode. The diagnostic has to carry what the agent actually
8635        // said, not just the fact that nothing was there to judge.
8636        let mut state = run_state(RunStatus::Failed);
8637        state.candidates = vec![candidate(
8638            'A',
8639            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8640            true,
8641            None,
8642        )];
8643        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8644        assert!(d.contains("candidate A"), "{d}");
8645        assert!(d.contains("tagged v1.2.3"), "{d}");
8646    }
8647
8648    #[test]
8649    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8650        let mut state = run_state(RunStatus::Failed);
8651        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8652        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8653        assert!(d.contains("candidate A"), "{d}");
8654        assert!(d.contains("agent timed out"), "{d}");
8655    }
8656
8657    #[test]
8658    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8659        // A viable candidate existed, the gate never ran, and nothing land
8660        // said matches - `Task::last_error` is left to explain this one alone.
8661        let mut state = run_state(RunStatus::Failed);
8662        state.candidates = vec![candidate('A', "did the work", false, None)];
8663        assert!(diagnostic(&state).is_none());
8664    }
8665
8666    #[test]
8667    fn diagnostic_is_bounded_however_much_a_run_printed() {
8668        let mut state = run_state(RunStatus::Blocked);
8669        state.gate = vec![
8670            CommandOutcome {
8671                command: "cargo test".to_owned(),
8672                code: Some(101),
8673                output_tail: "x".repeat(50_000),
8674                duration_ms: 0,
8675                resource_blocked: false,
8676            },
8677            CommandOutcome {
8678                command: "cargo clippy".to_owned(),
8679                code: Some(1),
8680                output_tail: "y".repeat(50_000),
8681                duration_ms: 0,
8682                resource_blocked: false,
8683            },
8684        ];
8685        state.candidates = vec![
8686            candidate('A', &"z".repeat(50_000), true, None),
8687            candidate('B', &"w".repeat(50_000), true, None),
8688        ];
8689        let d = diagnostic(&state).expect("plenty here to diagnose");
8690        assert!(
8691            d.len() <= DIAGNOSTIC_MAX,
8692            "diagnostic grew to {} bytes, unbounded",
8693            d.len()
8694        );
8695    }
8696
8697    #[test]
8698    fn selected_delivery_guards_survive_recovery_failure_accounting() {
8699        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8700            let mut t = task();
8701            let mut state = run_state(status);
8702            t.pr_recovery = Some(crate::pr_recovery::Selection {
8703                url: "url".into(),
8704                branch: format!("magi/task-{}", t.id),
8705                head: "a".repeat(40),
8706                source_head: None,
8707                source_run: None,
8708                source_proof: None,
8709                disposition: Some(crate::pr_recovery::Disposition::Land),
8710                instruction: t.instruction.clone(),
8711                approved_at: Timestamp::now(),
8712            });
8713            state.pr_recovery = t.pr_recovery.clone();
8714            t.start(state.id.clone());
8715            settle_and_diagnose(
8716                &mut t,
8717                Verdict {
8718                    status,
8719                    left_pr: false,
8720                    quota_hit: false,
8721                    parked: false,
8722                    no_viable_candidates: false,
8723                },
8724                "delivery stopped",
8725                5,
8726                &state,
8727            );
8728            assert_eq!(t.status, TaskStatus::Held);
8729            let reason = t.hold_reason.as_deref().unwrap();
8730            if status == RunStatus::Ready {
8731                assert!(reason.contains("Selected PR delivery is incomplete"));
8732                assert!(t.recovery_budget.is_none());
8733            } else {
8734                assert!(reason.contains("Selected recovery stopped"));
8735                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8736            }
8737            assert!(t.pr_recovery.is_some());
8738        }
8739    }
8740
8741    #[test]
8742    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
8743        let mut state = run_state(RunStatus::Voting);
8744        state.base_sync = Some(crate::run::BaseSync {
8745            tip: "base-tip".into(),
8746            behind: 3,
8747            attempts: 4,
8748            conflict: Some("base stopped".into()),
8749            already_in: None,
8750        });
8751        state.record_base_sync_stop("candidate-head");
8752        let mut t = task();
8753        t.start(state.id.clone());
8754        let verdict = Verdict {
8755            status: RunStatus::Blocked,
8756            left_pr: false,
8757            quota_hit: false,
8758            parked: false,
8759            no_viable_candidates: false,
8760        };
8761        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8762        assert_eq!(
8763            t.status,
8764            TaskStatus::Held,
8765            "unspent task attempts cannot start another competition"
8766        );
8767        let at = t.held_at;
8768        let cause = t.hold_notice_cause.clone();
8769        state.begin_pass();
8770        t.release_operator("test-resume", None);
8771        t.start(state.id.clone());
8772        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
8773        assert_eq!(t.status, TaskStatus::Held);
8774        assert_eq!(t.held_at, at);
8775        assert_eq!(t.hold_notice_cause, cause);
8776    }
8777
8778    #[test]
8779    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8780        let mut state = run_state(RunStatus::Blocked);
8781        state.gate = vec![CommandOutcome {
8782            command: "cargo test".to_owned(),
8783            code: Some(101),
8784            output_tail: "assertion failed".to_owned(),
8785            duration_ms: 0,
8786            resource_blocked: false,
8787        }];
8788        let verdict = Verdict {
8789            status: RunStatus::Blocked,
8790            left_pr: false,
8791            quota_hit: false,
8792            parked: false,
8793            no_viable_candidates: false,
8794        };
8795
8796        // Attempt one of two still has a retry coming: no diagnostic yet, the
8797        // task is going to run again and this run's evidence would go stale.
8798        let mut t = task();
8799        t.start("run-1".to_owned());
8800        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8801        assert_eq!(t.status, TaskStatus::Failed);
8802        assert!(t.diagnostic.is_none());
8803
8804        // Attempt two exhausts the budget: now it is held, and the
8805        // diagnostic is what `magi task show` has to say more than one line.
8806        t.start("run-2".to_owned());
8807        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8808        assert_eq!(t.status, TaskStatus::Held);
8809        let d = t.diagnostic.expect("a held task must carry its diagnostic");
8810        assert!(d.contains("cargo test"), "{d}");
8811    }
8812
8813    #[test]
8814    fn a_held_task_names_the_open_question_it_is_waiting_on() {
8815        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
8816        // `magi ask` question settled Held with `hold_reason: null`, so the
8817        // notification said nothing actionable. `note_open_question` should
8818        // append the question id to whatever `handed_off` already wrote.
8819        crate::run::pin_test_home();
8820        let home = crate::run::home();
8821        let state = run_state(RunStatus::VerifiedNoop);
8822        let mut q = ask::Question::new(
8823            state.id.clone(),
8824            "implement".to_owned(),
8825            "impl-A".to_owned(),
8826            "is this really a no-op?".to_owned(),
8827            String::new(),
8828            Vec::new(),
8829        );
8830        Questions::at(home.join("questions")).put(&mut q).unwrap();
8831
8832        let verdict = Verdict {
8833            status: RunStatus::VerifiedNoop,
8834            left_pr: false,
8835            quota_hit: false,
8836            parked: false,
8837            no_viable_candidates: false,
8838        };
8839        let mut t = task();
8840        t.start(state.id.clone());
8841        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8842
8843        assert_eq!(t.status, TaskStatus::Held);
8844        let reason = t.hold_reason.expect("a held task must record why");
8845        assert!(
8846            reason.starts_with("run ended agent-verified no-op"),
8847            "the original settle reason must survive unchanged: {reason}"
8848        );
8849        assert!(
8850            reason.contains(q.short()),
8851            "the open question's id must be named so the notice is actionable: {reason}"
8852        );
8853    }
8854
8855    #[test]
8856    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8857        crate::run::pin_test_home();
8858        let state = run_state(RunStatus::VerifiedNoop);
8859
8860        let verdict = Verdict {
8861            status: RunStatus::VerifiedNoop,
8862            left_pr: false,
8863            quota_hit: false,
8864            parked: false,
8865            no_viable_candidates: false,
8866        };
8867        let mut t = task();
8868        t.start(state.id.clone());
8869        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8870
8871        assert_eq!(t.status, TaskStatus::Held);
8872        assert_eq!(
8873            t.hold_reason.as_deref(),
8874            Some("run ended agent-verified no-op"),
8875            "nothing to append when the question was already answered or never asked"
8876        );
8877    }
8878
8879    #[test]
8880    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8881        crate::run::pin_test_home();
8882        let mut first = run_state(RunStatus::Blocked);
8883        first.id = "20260101-000000-sup1".to_owned();
8884        first.save().unwrap();
8885        let mut second = run_state(RunStatus::Merged);
8886        second.id = "20260101-000000-sup2".to_owned();
8887        second.save().unwrap();
8888
8889        let mut t = task();
8890        t.runs = vec![first.id.clone(), second.id.clone()];
8891        t.status = TaskStatus::Done;
8892
8893        supersede_prior_runs(&t, &crate::run::home());
8894
8895        assert_eq!(
8896            RunState::load(&first.id).unwrap().status,
8897            RunStatus::Superseded,
8898            "the first attempt's Blocked no longer needs anyone's attention"
8899        );
8900        assert_eq!(
8901            RunState::load(&second.id).unwrap().status,
8902            RunStatus::Merged,
8903            "the run that actually succeeded is left exactly as it was"
8904        );
8905    }
8906
8907    #[test]
8908    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
8909        // `is_working_on` alone only proves a *daemon* claim; a `magi run
8910        // --resume` invoked by hand outside the daemon never touches
8911        // `daemon.json` at all, so it would look identical to a genuinely
8912        // idle run without also consulting `RunState::liveness`, which reads
8913        // this run's own recorded `driver_pid` instead.
8914        crate::run::pin_test_home();
8915        let mut first = run_state(RunStatus::Blocked);
8916        first.id = "20260101-000000-sup9".to_owned();
8917        // This test process's own pid: guaranteed alive without needing a
8918        // real second process or daemon.
8919        first.driver_pid = Some(std::process::id());
8920        first.driver_started_at = Some(
8921            crate::proc::process_started_at(std::process::id())
8922                .expect("this test process's own start time must be queryable"),
8923        );
8924        first.save().unwrap();
8925        let mut second = run_state(RunStatus::Merged);
8926        second.id = "20260101-000000-supa".to_owned();
8927        second.save().unwrap();
8928
8929        let mut t = task();
8930        t.runs = vec![first.id.clone(), second.id.clone()];
8931        t.status = TaskStatus::Done;
8932
8933        supersede_prior_runs(&t, &crate::run::home());
8934
8935        assert_eq!(
8936            RunState::load(&first.id).unwrap().status,
8937            RunStatus::Blocked,
8938            "a live driver_pid means something is still actually working this run, \
8939             even though no daemon claims it - rewriting under it would just be \
8940             undone the next time that process saves"
8941        );
8942    }
8943
8944    #[test]
8945    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
8946        // The first resweep must skip a still-live attempt exactly like
8947        // `supersede_prior_runs` itself does; a later resweep, once that
8948        // process is no longer actually driving it, is what closes the gap
8949        // `supersede_prior_runs` alone leaves - a task only ever reaches
8950        // `Done` once, so nothing else would ever look at this run again.
8951        let dir = tempfile::tempdir().unwrap();
8952        let home = dir.path().to_path_buf();
8953        let queue = Queue::at(dir.path().join("queue"));
8954
8955        let mut first = run_state(RunStatus::Blocked);
8956        first.id = "20260101-000000-supd".to_owned();
8957        first.driver_pid = Some(std::process::id());
8958        first.driver_started_at = Some(
8959            crate::proc::process_started_at(std::process::id())
8960                .expect("this test process's own start time must be queryable"),
8961        );
8962        first.save_under(&home).unwrap();
8963        let mut second = run_state(RunStatus::Merged);
8964        second.id = "20260101-000000-supe".to_owned();
8965        second.save_under(&home).unwrap();
8966
8967        let mut t = task();
8968        t.runs = vec![first.id.clone(), second.id.clone()];
8969        t.status = TaskStatus::Done;
8970        queue.put(&mut t).unwrap();
8971
8972        resweep_superseded_attempts(&queue, &home);
8973        assert_eq!(
8974            RunState::load_under(&first.id, &home).unwrap().status,
8975            RunStatus::Blocked,
8976            "still live on the first pass, so still untouched"
8977        );
8978
8979        // Stand in for the manual process no longer being the one driving
8980        // this run: same pid (this test process really is still alive), but
8981        // an identity marker that no longer matches it - see
8982        // `RunState::liveness`'s own doc for why a mismatched
8983        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
8984        let mut stale = RunState::load_under(&first.id, &home).unwrap();
8985        stale.driver_started_at = Some("1".to_owned());
8986        stale.save_under(&home).unwrap();
8987
8988        resweep_superseded_attempts(&queue, &home);
8989        assert_eq!(
8990            RunState::load_under(&first.id, &home).unwrap().status,
8991            RunStatus::Superseded,
8992            "the second pass catches up what the first one correctly skipped"
8993        );
8994    }
8995
8996    #[test]
8997    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
8998        crate::run::pin_test_home();
8999        let mut first = run_state(RunStatus::Blocked);
9000        first.id = "20260101-000000-sup3".to_owned();
9001        first.save().unwrap();
9002        let mut second = run_state(RunStatus::Blocked);
9003        second.id = "20260101-000000-sup4".to_owned();
9004        second.save().unwrap();
9005
9006        let mut t = task();
9007        t.runs = vec![first.id.clone(), second.id.clone()];
9008        // Still retrying: nothing about this task's story is settled yet, so
9009        // neither Blocked run may be relabelled, even though a later attempt
9010        // already exists.
9011        t.status = TaskStatus::Failed;
9012
9013        supersede_prior_runs(&t, &crate::run::home());
9014
9015        assert_eq!(
9016            RunState::load(&first.id).unwrap().status,
9017            RunStatus::Blocked
9018        );
9019        assert_eq!(
9020            RunState::load(&second.id).unwrap().status,
9021            RunStatus::Blocked
9022        );
9023    }
9024
9025    #[test]
9026    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9027        // `magi task done` (or the API's equivalent) can close a task with no
9028        // run of its own ever having succeeded - there is nothing here that
9029        // counts as "the attempt that finished it", so nothing is rewritten.
9030        crate::run::pin_test_home();
9031        let mut first = run_state(RunStatus::Blocked);
9032        first.id = "20260101-000000-sup5".to_owned();
9033        first.save().unwrap();
9034
9035        let mut t = task();
9036        t.runs = vec![first.id.clone()];
9037        t.status = TaskStatus::Done;
9038
9039        supersede_prior_runs(&t, &crate::run::home());
9040
9041        assert_eq!(
9042            RunState::load(&first.id).unwrap().status,
9043            RunStatus::Blocked,
9044            "a single-attempt task has no earlier run to supersede"
9045        );
9046    }
9047
9048    #[test]
9049    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9050        // `magi task done` (or the web/conductor equivalents) can close a
9051        // task in any status, including one whose *last* recorded attempt is
9052        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
9053        // never watched, say. `runs.last()` being `Done`-adjacent is not
9054        // proof it actually succeeded, so nothing earlier may be relabelled
9055        // on its say-so alone.
9056        crate::run::pin_test_home();
9057        let mut first = run_state(RunStatus::Blocked);
9058        first.id = "20260101-000000-supb".to_owned();
9059        first.save().unwrap();
9060        let mut second = run_state(RunStatus::Failed);
9061        second.id = "20260101-000000-supc".to_owned();
9062        second.save().unwrap();
9063
9064        let mut t = task();
9065        t.runs = vec![first.id.clone(), second.id.clone()];
9066        t.status = TaskStatus::Done;
9067
9068        supersede_prior_runs(&t, &crate::run::home());
9069
9070        assert_eq!(
9071            RunState::load(&first.id).unwrap().status,
9072            RunStatus::Blocked,
9073            "the task's last attempt never landed, so there is nothing here \
9074             actually superseding it"
9075        );
9076    }
9077
9078    #[test]
9079    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9080        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
9081        // to look" - `Failed` and `VerifiedNoop` are already their own
9082        // terminal answers and must not be relabelled into a third one.
9083        crate::run::pin_test_home();
9084        let mut failed = run_state(RunStatus::Failed);
9085        failed.id = "20260101-000000-sup6".to_owned();
9086        failed.save().unwrap();
9087        let mut noop = run_state(RunStatus::VerifiedNoop);
9088        noop.id = "20260101-000000-sup7".to_owned();
9089        noop.save().unwrap();
9090        let mut winner = run_state(RunStatus::Ready);
9091        winner.id = "20260101-000000-sup8".to_owned();
9092        winner.save().unwrap();
9093
9094        let mut t = task();
9095        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9096        t.status = TaskStatus::Done;
9097
9098        supersede_prior_runs(&t, &crate::run::home());
9099
9100        assert_eq!(
9101            RunState::load(&failed.id).unwrap().status,
9102            RunStatus::Failed
9103        );
9104        assert_eq!(
9105            RunState::load(&noop.id).unwrap().status,
9106            RunStatus::VerifiedNoop
9107        );
9108    }
9109
9110    fn approval_question(run: &str) -> ask::Question {
9111        ask::Question::new(
9112            run.to_owned(),
9113            land::APPROVAL_NODE.to_owned(),
9114            "land".to_owned(),
9115            "merge?".to_owned(),
9116            String::new(),
9117            vec!["merge".to_owned(), "hold".to_owned()],
9118        )
9119    }
9120
9121    #[test]
9122    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9123        crate::run::pin_test_home();
9124        let mut state = run_state(RunStatus::Landing);
9125        state.id = "20260101-000000-fre1".to_owned();
9126        state.parked = true;
9127        state.save().unwrap();
9128        ask::Questions::open()
9129            .put(&mut approval_question(&state.id))
9130            .unwrap();
9131
9132        let mut t = task();
9133        t.runs.push(state.id.clone());
9134        assert_eq!(
9135            land_resume_state(&t),
9136            LandResume::StillWaiting,
9137            "nobody has answered and the timeout has not passed"
9138        );
9139    }
9140
9141    #[test]
9142    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9143        crate::run::pin_test_home();
9144        let mut state = run_state(RunStatus::Gating);
9145        state.id = "20260101-000000-gt01".to_owned();
9146        state.parked = true;
9147        state.config.graph.answer_timeout = 60;
9148        state.github_text = Some(crate::run::GithubTextAsk {
9149            rewrite: None,
9150            fingerprint: "f".into(),
9151            title: true,
9152            body: false,
9153            categories: vec!["title-language".into()],
9154            question: None,
9155            asks: 1,
9156            resolved: false,
9157            chosen_title: None,
9158            choice: None,
9159        });
9160        state.save().unwrap();
9161        let store = ask::Questions::open();
9162        let mut q = ask::Question::new(
9163            state.id.clone(),
9164            crate::github_text::ASK_NODE.to_owned(),
9165            crate::github_text::ASK_SEAT.to_owned(),
9166            "s".into(),
9167            String::new(),
9168            vec!["use fallback".into()],
9169        );
9170        store.put(&mut q).unwrap();
9171        let mut t = task();
9172        t.runs.push(state.id.clone());
9173        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9174        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9175        store.put(&mut q).unwrap();
9176        assert_eq!(land_resume_state(&t), LandResume::Ready);
9177        assert!(!store.get(&q.id).unwrap().status.open());
9178        // Once decided, a parked run is an ordinary candidate again.
9179        state.github_text.as_mut().unwrap().resolved = true;
9180        state.save().unwrap();
9181        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9182    }
9183
9184    #[test]
9185    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9186        // `ask::ask_and_wait`'s own deadline used to retire a question
9187        // nobody answered; land's approval bypasses that wait (see
9188        // `land::approval_gate`), so this is now the only place
9189        // `graph.answer_timeout` is enforced for a land approval at all.
9190        crate::run::pin_test_home();
9191        let mut state = run_state(RunStatus::Landing);
9192        state.id = "20260101-000000-exp1".to_owned();
9193        state.parked = true;
9194        state.config.graph.answer_timeout = 60;
9195        state.save().unwrap();
9196
9197        let store = ask::Questions::open();
9198        let mut q = approval_question(&state.id);
9199        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9200        store.put(&mut q).unwrap();
9201
9202        let mut t = task();
9203        t.runs.push(state.id.clone());
9204        assert_eq!(
9205            land_resume_state(&t),
9206            LandResume::Ready,
9207            "an expired question must not be waited on forever"
9208        );
9209
9210        let after = store.get(&q.id).unwrap();
9211        assert!(
9212            !after.status.open(),
9213            "the question is abandoned, not silently ignored"
9214        );
9215        assert!(
9216            after.resolution().is_none(),
9217            "an abandoned question is not read as a decision"
9218        );
9219    }
9220
9221    #[test]
9222    fn reclaim_settles_a_running_task_against_its_last_run() {
9223        let mut t = task();
9224        t.start("20260904-000000-4043".to_owned());
9225        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9226        assert_eq!(
9227            t.status,
9228            TaskStatus::Done,
9229            "a run that actually finished must not stay `running` forever"
9230        );
9231    }
9232
9233    #[test]
9234    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9235        let mut t = task();
9236        t.start("20260904-000000-4043".to_owned());
9237        t.last_error = Some("earlier trouble".to_owned());
9238        let mut state = run_state(RunStatus::Judging);
9239        state.parked = true;
9240        reclaim(&mut t, Some(state), 1, "en");
9241        assert_eq!(t.status, TaskStatus::Parked);
9242        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9243        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9244        assert!(t.park_reason.is_some());
9245        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9246        assert!(!t.fresh_start);
9247        assert!(t.status.runnable());
9248    }
9249
9250    #[test]
9251    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9252        let mut t = task();
9253        t.start("20260904-000000-4043".to_owned());
9254        t.last_error = Some("earlier trouble".to_owned());
9255        settle(
9256            &mut t,
9257            Verdict {
9258                status: RunStatus::Judging,
9259                left_pr: false,
9260                quota_hit: false,
9261                parked: true,
9262                no_viable_candidates: false,
9263            },
9264            "parked after `judging`",
9265            1,
9266        );
9267        assert_eq!(t.status, TaskStatus::Parked);
9268        assert_eq!(t.attempts, 0);
9269        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9270        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9271        assert_eq!(t.schema, crate::queue::SCHEMA);
9272        assert!(
9273            crate::notices::task_held(&t).is_none(),
9274            "a park is not news"
9275        );
9276        t.start("20260904-000000-4043".to_owned());
9277        assert_eq!(t.park_reason, None);
9278    }
9279
9280    #[test]
9281    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9282        // A blocked run with attempts left goes back to `Failed`, exactly as
9283        // it would from `attempt` itself - `reclaim` must not invent a second
9284        // policy for a task a daemon merely stopped without reporting.
9285        let mut t = task();
9286        t.start("20260904-000000-4043".to_owned());
9287        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9288        assert_eq!(t.status, TaskStatus::Failed);
9289        assert!(t.status.runnable());
9290    }
9291
9292    #[test]
9293    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9294        let mut t = task();
9295        t.start("20260904-000000-4043".to_owned());
9296        assert_eq!(t.attempts, 1);
9297        let mut run = run_state(RunStatus::Implementing);
9298        run.id = "20260904-000000-4043".to_owned();
9299        run.begin_pass();
9300        let cause = crate::run::ParkCause::Upgrade {
9301            from: "0.121.0".to_owned(),
9302            to: Some("0.121.1".to_owned()),
9303        };
9304        run.end_pass_parked(cause.clone());
9305        run.parked = true;
9306        let verdict = Verdict {
9307            status: run.status,
9308            left_pr: false,
9309            quota_hit: false,
9310            parked: true,
9311            no_viable_candidates: false,
9312        };
9313        // A crash after the checkpoint but before queue settlement must
9314        // recover exactly the same scheduling evidence and refund.
9315        let mut orphan = t.clone();
9316        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9317        assert_eq!(orphan.status, TaskStatus::Parked);
9318        assert_eq!(orphan.attempts, 0);
9319        assert_eq!(
9320            orphan.upgrade_resume_key(),
9321            Some((run.passes[0].started_at, orphan.id.as_str()))
9322        );
9323        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9324        assert_eq!(t.attempts, 0);
9325        assert_eq!(t.passes.len(), 1);
9326        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9327        assert_eq!(t.passes[0].parked, Some(cause));
9328        assert_eq!(t.passes[0].pass_index, 0);
9329        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9330        assert!(t.upgrade_resume_key().is_some());
9331
9332        // A resumed pass that then fails spends its attempt, and the earlier
9333        // pass's entry is untouched.
9334        t.start("20260904-000000-4043".to_owned());
9335        run.begin_pass();
9336        run.status = RunStatus::Failed;
9337        let verdict = Verdict {
9338            status: RunStatus::Failed,
9339            left_pr: false,
9340            quota_hit: false,
9341            parked: false,
9342            no_viable_candidates: false,
9343        };
9344        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9345        assert_eq!(t.passes.len(), 2);
9346        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9347        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9348        assert_eq!(t.passes[1].pass_index, 1);
9349        assert_eq!(t.attempts, 1);
9350    }
9351
9352    #[test]
9353    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9354        let mut t = task();
9355        t.start("20260904-000000-4043".to_owned());
9356        reclaim(&mut t, None, 2, "en");
9357        assert_eq!(t.status, TaskStatus::Held);
9358        assert!(
9359            t.last_error
9360                .as_deref()
9361                .is_some_and(|e| e.contains("running")),
9362            "the operator needs to know why this task was held"
9363        );
9364    }
9365
9366    #[test]
9367    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9368        let dir = tempfile::tempdir().unwrap();
9369        let queue = Queue::at(dir.path().to_path_buf());
9370
9371        // No run recorded, so this never has to touch `RunState::load`.
9372        let mut orphaned = task();
9373        orphaned.id = "20260904-000000-orph".to_owned();
9374        orphaned.status = TaskStatus::Running;
9375        orphaned.attempts = 1;
9376        queue.put(&mut orphaned).unwrap();
9377
9378        let mut alive = task();
9379        alive.id = "20260904-000000-live".to_owned();
9380        alive.status = TaskStatus::Running;
9381        alive.attempts = 1;
9382        queue.put(&mut alive).unwrap();
9383        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9384
9385        let mut queued = task();
9386        queued.id = "20260904-000000-wait".to_owned();
9387        queue.put(&mut queued).unwrap();
9388
9389        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9390        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9391
9392        assert_eq!(
9393            queue.get(&orphaned.id).unwrap().status,
9394            TaskStatus::Held,
9395            "nothing was driving it and there was no run to recover"
9396        );
9397        assert_eq!(
9398            queue.get(&alive.id).unwrap().status,
9399            TaskStatus::Running,
9400            "a live claim must protect the task it belongs to"
9401        );
9402        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9403    }
9404
9405    /// Read a run.json back from an explicit `home`, the same way
9406    /// `reclaim_abandoned_runs` itself does - never through the
9407    /// process-global `RunState::load`, which this test's own `home` (an
9408    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
9409    /// use at all.
9410    fn read_run_under(home: &Path, id: &str) -> RunState {
9411        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9412        serde_json::from_str(&body).unwrap()
9413    }
9414
9415    #[test]
9416    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9417        let dir = tempfile::tempdir().unwrap();
9418        let home = dir.path().to_path_buf();
9419        let now = Timestamp::now();
9420        let overrun_seat = || crate::run::ActiveSeat {
9421            node: "implement".to_owned(),
9422            started_at: now - jiff::SignedDuration::new(21_000, 0),
9423            timeout_secs: 3_600,
9424            attempt: 0,
9425            task: None,
9426            command: None,
9427            index: None,
9428            total: None,
9429        };
9430
9431        let mut dead = run_state(RunStatus::Implementing);
9432        dead.id = "20260101-000000-dead".to_owned();
9433        dead.active.insert("impl-A".to_owned(), overrun_seat());
9434        // A `driver_pid` the injected query below confirms gone outright —
9435        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
9436        dead.driver_pid = Some(4242);
9437        dead.save_under(&home).unwrap();
9438
9439        // Same shape, but a live daemon's heartbeat names it: must be left
9440        // exactly alone, however far past its own timeout the seat sits.
9441        let mut alive = run_state(RunStatus::Implementing);
9442        alive.id = "20260101-000000-aliv".to_owned();
9443        alive.active.insert("impl-A".to_owned(), overrun_seat());
9444        alive.save_under(&home).unwrap();
9445        let mut status = Status::new();
9446        status.current = vec![Current {
9447            worker: None,
9448            task: "20260101-000000-task".to_owned(),
9449            run: alive.id.clone(),
9450        }];
9451        write_status_to(&home.join("daemon.json"), &status).unwrap();
9452
9453        // The abandoned seat left an open question behind: nobody is left to
9454        // read an answer once the run is failed, and this must not wait for
9455        // some later daemon startup's own sweep to notice that.
9456        let questions = Questions::at(home.join("questions"));
9457        let mut q = ask::Question::new(
9458            dead.id.clone(),
9459            "implement".to_owned(),
9460            "impl-A".to_owned(),
9461            "Which storage backend?".to_owned(),
9462            String::new(),
9463            vec!["SQLite".to_owned(), "Redis".to_owned()],
9464        );
9465        questions.put(&mut q).unwrap();
9466
9467        let abandoned = reclaim_abandoned_runs_with(
9468            &home,
9469            now,
9470            |pid| if pid == 4242 { Some(false) } else { None },
9471            |_| panic!("a query answering Dead outright needs no identity corroboration"),
9472        );
9473        assert_eq!(abandoned, vec![dead.id.clone()]);
9474
9475        let reloaded = read_run_under(&home, &dead.id);
9476        assert_eq!(reloaded.status, RunStatus::Failed);
9477        assert!(reloaded.active.is_empty());
9478        assert!(
9479            !questions.get(&q.id).unwrap().status.open(),
9480            "the failed run's own open question must be settled in the same pass"
9481        );
9482
9483        let still_alive = read_run_under(&home, &alive.id);
9484        assert_eq!(
9485            still_alive.status,
9486            RunStatus::Implementing,
9487            "a live daemon's claim protects it"
9488        );
9489        assert!(!still_alive.active.is_empty());
9490    }
9491
9492    /// The exact shape a review round flagged as broken: `magi serve` running
9493    /// in this same `home` scans *every* run on disk, including a manual
9494    /// `magi review` / `magi run` this daemon never started and that
9495    /// therefore claims no heartbeat of its own. Before this scan asked
9496    /// `liveness` rather than just `is_working_on`, a manual run whose active
9497    /// seat merely ran a little past its own timeout — the CLI finishing up,
9498    /// its result still being collected — got wiped and failed by a daemon
9499    /// that had nothing to do with it, out from under a process that was
9500    /// still very much running.
9501    #[test]
9502    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9503        let dir = tempfile::tempdir().unwrap();
9504        let home = dir.path().to_path_buf();
9505        let now = Timestamp::now();
9506
9507        let mut manual = run_state(RunStatus::Reviewing);
9508        manual.id = "20260101-000000-manl".to_owned();
9509        manual.active.insert(
9510            "review-1".to_owned(),
9511            crate::run::ActiveSeat {
9512                node: "review".to_owned(),
9513                started_at: now - jiff::SignedDuration::new(21_000, 0),
9514                timeout_secs: 3_600,
9515                attempt: 0,
9516                task: None,
9517                command: None,
9518                index: None,
9519                total: None,
9520            },
9521        );
9522        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
9523        // but a real, still-running process: `liveness` must corroborate this
9524        // as `Live`, not read the missing daemon claim as death.
9525        manual.driver_pid = Some(4242);
9526        manual.driver_started_at = Some("1790000000".to_owned());
9527        manual.save_under(&home).unwrap();
9528
9529        let abandoned = reclaim_abandoned_runs_with(
9530            &home,
9531            now,
9532            |pid| if pid == 4242 { Some(true) } else { None },
9533            |pid| {
9534                if pid == 4242 {
9535                    Some("1790000000".to_owned())
9536                } else {
9537                    None
9538                }
9539            },
9540        );
9541        assert!(
9542            abandoned.is_empty(),
9543            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9544        );
9545
9546        let reloaded = read_run_under(&home, &manual.id);
9547        assert_eq!(reloaded.status, RunStatus::Reviewing);
9548        assert!(!reloaded.active.is_empty());
9549    }
9550
9551    #[test]
9552    fn an_already_claimed_task_is_skipped_rather_than_failed() {
9553        let dir = tempfile::tempdir().unwrap();
9554        let queue = Queue::at(dir.path().to_path_buf());
9555        let mut only = task();
9556        queue.put(&mut only).unwrap();
9557
9558        let _elsewhere = queue.claim(&only.id).unwrap();
9559        let candidates = runnable(&queue);
9560        assert_eq!(candidates.len(), 1, "the task is still runnable");
9561        assert!(
9562            queue.claim(&candidates[0].id).is_err(),
9563            "the loop cannot take a claim somebody else holds"
9564        );
9565
9566        let after = queue.get(&only.id).unwrap();
9567        assert_eq!(after.status, TaskStatus::Queued);
9568        assert_eq!(
9569            after.attempts, 0,
9570            "losing the race is not an attempt at the task"
9571        );
9572        assert_eq!(after.last_error, None);
9573    }
9574
9575    #[test]
9576    fn the_status_file_round_trips_and_its_heartbeat_advances() {
9577        let dir = tempfile::tempdir().unwrap();
9578        let path = dir.path().join("daemon.json");
9579
9580        let mut status = Status::new();
9581        status.idle = false;
9582        status.completed = 7;
9583        status.current = vec![Current {
9584            worker: None,
9585            task: "20260902-000000-t111".to_owned(),
9586            run: "20260902-000001-r111".to_owned(),
9587        }];
9588        write_status_to(&path, &status).unwrap();
9589        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9590        assert_eq!(first.schema, SCHEMA);
9591        assert_eq!(first.pid, std::process::id());
9592        assert!(!first.idle);
9593        assert_eq!(first.completed, 7);
9594        assert_eq!(first.current, status.current);
9595        assert!(
9596            !path.with_extension("json.tmp").exists(),
9597            "the temp file is renamed, not left behind"
9598        );
9599
9600        std::thread::sleep(Duration::from_millis(5));
9601        status.updated_at = Timestamp::now();
9602        status.polls = 3;
9603        write_status_to(&path, &status).unwrap();
9604        let second: Status =
9605            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9606        assert!(
9607            second.updated_at > first.updated_at,
9608            "a reader can only detect staleness if the heartbeat moves"
9609        );
9610        assert_eq!(
9611            second.started_at, first.started_at,
9612            "the start time is not a heartbeat"
9613        );
9614        assert_eq!(second.polls, 3);
9615    }
9616
9617    #[test]
9618    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9619        let dir = tempfile::tempdir().unwrap();
9620
9621        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9622
9623        let mut status = Status::new();
9624        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9625        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9626        let stale = read_status(dir.path()).unwrap();
9627        assert!(
9628            !stale.running(Timestamp::now()),
9629            "a minute without a heartbeat is a dead daemon, not a busy one"
9630        );
9631        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9632
9633        status.updated_at = Timestamp::now();
9634        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9635        let fresh = read_status(dir.path()).unwrap();
9636        assert!(fresh.running(Timestamp::now()));
9637    }
9638
9639    #[test]
9640    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9641        let dir = tempfile::tempdir().unwrap();
9642        let now = Timestamp::now();
9643        let mine = "20260903-080619-01c2";
9644
9645        assert!(
9646            !is_working_on(dir.path(), mine, now),
9647            "no status file means nobody is working on anything"
9648        );
9649
9650        let mut status = Status::new();
9651        status.current = vec![Current {
9652            worker: None,
9653            task: "20260903-080340-0167".to_owned(),
9654            run: mine.to_owned(),
9655        }];
9656        status.updated_at = now;
9657        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9658        assert!(is_working_on(dir.path(), mine, now));
9659        assert!(
9660            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9661            "a daemon busy with one run is not working on another"
9662        );
9663
9664        // A killed daemon stops writing heartbeats but leaves the file behind
9665        // naming the run it died in. That run must not be undeletable forever.
9666        status.updated_at = now - jiff::SignedDuration::from_secs(600);
9667        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9668        assert!(
9669            !is_working_on(dir.path(), mine, now),
9670            "a stale heartbeat is a dead daemon, so its run is a leftover"
9671        );
9672    }
9673
9674    #[test]
9675    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9676        let dir = tempfile::tempdir().unwrap();
9677        let now = Timestamp::now();
9678
9679        assert!(
9680            !is_working_on_short(dir.path(), "01c2", now),
9681            "no status file means nobody is working on anything"
9682        );
9683
9684        let mut status = Status::new();
9685        status.current = vec![Current {
9686            worker: None,
9687            task: "20260903-080340-0167".to_owned(),
9688            run: "20260903-080619-01c2".to_owned(),
9689        }];
9690        status.updated_at = now;
9691        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9692        assert!(
9693            is_working_on_short(dir.path(), "01c2", now),
9694            "the run's short id is the last block of its full id"
9695        );
9696        assert!(
9697            !is_working_on_short(dir.path(), "3cbf", now),
9698            "a daemon busy with one worktree bay is not working on another"
9699        );
9700    }
9701
9702    #[test]
9703    fn a_newer_status_file_still_yields_a_reading() {
9704        let dir = tempfile::tempdir().unwrap();
9705        // A field this build has never heard of must not turn the reading into
9706        // nothing at all; that is the whole reason the reader is permissive.
9707        std::fs::write(
9708            dir.path().join("daemon.json"),
9709            serde_json::json!({
9710                "schema": 2,
9711                "updated_at": Timestamp::now().to_string(),
9712                "idle": true,
9713                "surprise": { "nested": [1, 2, 3] },
9714            })
9715            .to_string(),
9716        )
9717        .unwrap();
9718
9719        let reading = read_status(dir.path()).expect("a forward-compatible read");
9720        assert!(reading.running(Timestamp::now()));
9721        assert!(reading.idle);
9722        assert!(reading.current.is_empty());
9723    }
9724
9725    #[test]
9726    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9727        // A daemon started before `current` became a list keeps writing this
9728        // shape on every heartbeat until it is restarted. A rolling upgrade
9729        // - a newer `magi web` or `magi doctor` reading an older `magi
9730        // serve`'s heartbeat - must still see the run it is on, not "no
9731        // daemon" from a type mismatch failing the whole struct.
9732        let dir = tempfile::tempdir().unwrap();
9733        std::fs::write(
9734            dir.path().join("daemon.json"),
9735            serde_json::json!({
9736                "schema": 1,
9737                "pid": 4242,
9738                "updated_at": Timestamp::now().to_string(),
9739                "idle": false,
9740                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9741                "completed": 3,
9742                "polls": 9,
9743            })
9744            .to_string(),
9745        )
9746        .unwrap();
9747
9748        let reading = read_status(dir.path()).expect("an older shape must still parse");
9749        assert!(reading.running(Timestamp::now()));
9750        assert_eq!(
9751            reading.current,
9752            vec![Current {
9753                worker: None,
9754                task: "20260902-140501-aaaa".to_owned(),
9755                run: "20260902-140502-bbbb".to_owned(),
9756            }]
9757        );
9758    }
9759
9760    #[test]
9761    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9762        let dir = tempfile::tempdir().unwrap();
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                "current": null,
9770            })
9771            .to_string(),
9772        )
9773        .unwrap();
9774        let with_null = read_status(dir.path()).expect("null must still parse");
9775        assert!(with_null.current.is_empty());
9776
9777        std::fs::write(
9778            dir.path().join("daemon.json"),
9779            serde_json::json!({
9780                "schema": 1,
9781                "updated_at": Timestamp::now().to_string(),
9782                "idle": true,
9783            })
9784            .to_string(),
9785        )
9786        .unwrap();
9787        let absent = read_status(dir.path()).expect("a missing field must still parse");
9788        assert!(absent.current.is_empty());
9789    }
9790
9791    #[test]
9792    fn a_task_without_a_repository_runs_in_the_daemons_default() {
9793        let fallback = Path::new("/default");
9794        let mut blank = task();
9795        blank.repo = PathBuf::new();
9796        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9797        let mut dot = task();
9798        dot.repo = PathBuf::from(".");
9799        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9800        assert_eq!(
9801            repo_for(&task(), fallback),
9802            PathBuf::from("/repo"),
9803            "a task that names a repository keeps it"
9804        );
9805    }
9806
9807    #[test]
9808    fn task_implementers_edit_inherits_daemon_config_and_merge() {
9809        let dir = tempfile::tempdir().unwrap();
9810        let path = dir.path().join("explicit.toml");
9811        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9812        let opts = Opts {
9813            config: Some(path),
9814            merge: Some("none".into()),
9815            ..Default::default()
9816        };
9817        let mut t = task();
9818        t.set_implementers(
9819            2,
9820            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9821                .unwrap(),
9822        )
9823        .unwrap();
9824        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9825        assert_eq!(cfg.graph.implementers, 2);
9826        assert_eq!(cfg.graph.judges, 1);
9827        assert_eq!(cfg.merge.mode, MergeMode::None);
9828        t.set_implementers(1, &cfg).unwrap();
9829        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9830        apply_task_implementers(&mut cfg, &t);
9831        assert_eq!(cfg.graph.implementers, 1);
9832        assert_eq!(cfg.graph.judges, 1);
9833        assert_eq!(cfg.merge.mode, MergeMode::None);
9834    }
9835
9836    #[test]
9837    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9838        let dir = tempfile::tempdir().unwrap();
9839        let repo = dir.path().join("repo");
9840        std::fs::create_dir(&repo).unwrap();
9841        std::fs::write(
9842            repo.join("magi.toml"),
9843            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
9844        )
9845        .unwrap();
9846        let daemon_config = dir.path().join("daemon.toml");
9847        std::fs::write(
9848            &daemon_config,
9849            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
9850        )
9851        .unwrap();
9852        let opts = Opts {
9853            config: Some(daemon_config),
9854            merge: Some("pr".into()),
9855            ..Default::default()
9856        };
9857        let q = Queue::at(dir.path().join("queue"));
9858        let validation: Config =
9859            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9860                .unwrap();
9861        // No provenance field on legacy direct tasks: both shapes stay isolated.
9862        for record in ["{}", r#"{"candidates":2}"#] {
9863            let overrides = serde_json::from_str(record).unwrap();
9864            let filing = crate::direct::Filing {
9865                instruction: "work".into(),
9866                title: "direct".into(),
9867                repo: repo.clone(),
9868                source: crate::queue::Source::Human,
9869                solo: false,
9870                overrides,
9871                review_of: None,
9872                sources: Default::default(),
9873            };
9874            let filed =
9875                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
9876            let crate::direct::Filed::Standalone {
9877                mut task,
9878                claim: _claim,
9879            } = filed
9880            else {
9881                panic!("local filing")
9882            };
9883            let before = prepare_for(&repo, &opts, &task).unwrap();
9884            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
9885            assert_eq!(
9886                before.merge.mode,
9887                MergeMode::None,
9888                "daemon --merge must not leak"
9889            );
9890            for n in [2, 1, 2] {
9891                task.set_implementers(n, &validation).unwrap();
9892                q.put(&mut task).unwrap();
9893                task = q.get(&task.id).unwrap();
9894                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
9895                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
9896                apply_task_implementers(&mut cfg, &task);
9897                assert_eq!(cfg.graph.implementers, usize::from(n));
9898                assert_eq!(cfg.graph.judges, 2);
9899                assert_eq!(cfg.merge.mode, MergeMode::None);
9900            }
9901        }
9902    }
9903
9904    #[test]
9905    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
9906        let cfg: Config =
9907            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9908                .unwrap();
9909        let mut t = task();
9910        t.review_of = Some("review-target".into());
9911        t.hold_manual(Some("retry".into()));
9912        let mut previous = RunState::new(
9913            PathBuf::from("/repo"),
9914            "main".into(),
9915            "abc1234".into(),
9916            "review".into(),
9917            cfg.clone(),
9918        );
9919        previous.config.graph.implementers = 2;
9920        for count in [1, 3] {
9921            t.set_implementers(count, &cfg).unwrap();
9922            t.release();
9923            assert_eq!(t.review_of.as_deref(), Some("review-target"));
9924            for proposed in [
9925                Starter::Resume(previous.id.clone()),
9926                Starter::Review("recovery-target".into()),
9927            ] {
9928                assert_eq!(
9929                    starter_with_implementers(&t, Some(&previous), proposed),
9930                    Starter::Review("review-target".into())
9931                );
9932            }
9933            let mut configured = cfg.clone();
9934            apply_task_implementers(&mut configured, &t);
9935            assert_eq!(configured.graph.implementers, usize::from(count));
9936            assert_eq!(previous.config.graph.implementers, 2);
9937        }
9938    }
9939
9940    #[test]
9941    fn task_implementers_dispatch_and_resume_agree() {
9942        let mut t = task();
9943        let cfg: crate::config::Config =
9944            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9945                .unwrap();
9946        let mut run = RunState::new(
9947            PathBuf::from("/repo"),
9948            "main".into(),
9949            "abc1234".into(),
9950            "work".into(),
9951            cfg.clone(),
9952        );
9953        run.config.graph.implementers = 2;
9954        for n in [2, 1, 3, 2] {
9955            t.set_implementers(n, &cfg).unwrap();
9956            let mut dispatched = cfg.clone();
9957            apply_task_implementers(&mut dispatched, &t);
9958            assert_eq!(dispatched.graph.implementers, usize::from(n));
9959            assert_eq!(implementers_match(&t, &run), n == 2);
9960            for proposed in [
9961                Starter::Resume(run.id.clone()),
9962                Starter::Review("old-branch".into()),
9963            ] {
9964                let expected = if n == 2 {
9965                    proposed.clone()
9966                } else {
9967                    Starter::Start
9968                };
9969                assert_eq!(
9970                    starter_with_implementers(&t, Some(&run), proposed),
9971                    expected
9972                );
9973            }
9974            assert_eq!(
9975                run.config.graph.implementers, 2,
9976                "history must not be rewritten"
9977            );
9978        }
9979        t.solo = false;
9980        t.overrides = None;
9981        assert!(implementers_match(&t, &run));
9982    }
9983
9984    #[test]
9985    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
9986        // Three seats said out loud. What `solo` promises is one candidate
9987        // *whatever the config asks for*, so the contrast has to be a number
9988        // this test owns - it used to be `Config::default()`'s, which became
9989        // 1 when one implementation became the default and left the two
9990        // halves of this test asserting the same thing.
9991        let mut solo_cfg = Config::default();
9992        solo_cfg.graph.implementers = 3;
9993        let mut solo_task = task();
9994        solo_task.solo = true;
9995        apply_task_implementers(&mut solo_cfg, &solo_task);
9996        assert_eq!(solo_cfg.graph.implementers, 1);
9997
9998        let mut plain_cfg = Config::default();
9999        plain_cfg.graph.implementers = 3;
10000        let plain_task = task();
10001        assert!(!plain_task.solo);
10002        apply_task_implementers(&mut plain_cfg, &plain_task);
10003        assert_eq!(
10004            plain_cfg.graph.implementers, 3,
10005            "a task that did not ask to run alone keeps the config's candidates"
10006        );
10007    }
10008
10009    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
10010        QuotaLoss {
10011            cause: crate::agent::QuotaCause::UsageLimit,
10012            agent: String::new(),
10013            seat: seat.into(),
10014            node: "judge".into(),
10015            at: at.parse().unwrap(),
10016            reset: reset.map(str::to_string),
10017        }
10018    }
10019
10020    #[test]
10021    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
10022        let now = Timestamp::now();
10023        for reset in [None, Some("in 1h")] {
10024            let auth = crate::agent::Quota {
10025                cause: crate::agent::QuotaCause::Authentication,
10026                agent: "alpha".into(),
10027                reset: reset.map(str::to_owned),
10028            };
10029            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
10030            assert_eq!(cooldown_until(&[loss], now), None);
10031        }
10032    }
10033
10034    #[test]
10035    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
10036        let old: Vec<QuotaLoss> = (1..=4)
10037            .map(|i| {
10038                loss(
10039                    &format!("judge-{i}"),
10040                    "2026-09-23T05:23:00Z",
10041                    Some("2:40pm (Asia/Tokyo)"),
10042                )
10043            })
10044            .collect();
10045        let fresh = losses_this_attempt(&old, &old);
10046        assert!(fresh.is_empty());
10047        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
10048        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
10049    }
10050
10051    #[test]
10052    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
10053        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
10054        let now = Timestamp::now();
10055        let mut after = old.clone();
10056        after.push(loss("judge-2", &now.to_string(), None));
10057        let fresh = losses_this_attempt(&old, &after);
10058        assert_eq!(fresh, vec![after[1].clone()]);
10059        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
10060        assert_eq!(
10061            until,
10062            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
10063        );
10064    }
10065
10066    #[test]
10067    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
10068        // `recover_stall` removes judge-1's loss and the retry then hits quota
10069        // again: the vector is the same length, so an index diff sees nothing.
10070        let before = vec![
10071            loss("judge-1", "2026-09-23T05:23:00Z", None),
10072            loss("judge-2", "2026-09-23T05:24:00Z", None),
10073        ];
10074        let after = vec![
10075            loss("judge-2", "2026-09-23T05:24:00Z", None),
10076            loss("judge-1", "2026-09-24T01:00:00Z", None),
10077        ];
10078        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
10079    }
10080
10081    #[test]
10082    fn merge_overrides_are_parsed_or_refused() {
10083        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
10084        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
10085        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
10086        assert!(merge_mode("squash").is_err());
10087    }
10088
10089    #[test]
10090    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
10091        let now = Timestamp::now();
10092        let fallback = Duration::from_secs(300);
10093        let cap = Duration::from_secs(1800);
10094
10095        // No reset hint at all: the fallback.
10096        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
10097
10098        // A reset ten minutes out, well inside the cap: waited for exactly.
10099        let soon = now + jiff::SignedDuration::from_secs(600);
10100        assert_eq!(
10101            quota_wait(Some(soon), now, fallback, cap),
10102            Duration::from_secs(600)
10103        );
10104
10105        // A reset already in the past is not trusted: the fallback, not a
10106        // zero or negative wait that would spin the loop right back around.
10107        let past = now - jiff::SignedDuration::from_secs(60);
10108        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
10109
10110        // A reset further out than the cap is trusted for direction but not
10111        // for magnitude: a parsing slip must not sleep the loop for a day.
10112        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
10113        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
10114    }
10115
10116    #[test]
10117    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
10118        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10119
10120        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
10121        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
10122
10123        // Same clock reading, but it has already gone by today: read as
10124        // tomorrow's, since the CLI would not still be reporting a limit past
10125        // its own stated reset.
10126        let already_past =
10127            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
10128        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
10129
10130        assert!(
10131            parse_reset_hint("session limit reached", now, now).is_none(),
10132            "free text with no recognised shape is not guessed at"
10133        );
10134        assert!(
10135            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
10136            "an unresolvable zone name is not guessed at either"
10137        );
10138    }
10139
10140    #[test]
10141    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
10142        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10143
10144        let at = parse_reset_hint(
10145            "You've hit your usage limit. Visit \
10146             https://chatgpt.com/codex/settings/usage to purchase more \
10147             credits or try again at Sep 19th, 2026 5:10 PM.",
10148            now,
10149            now,
10150        )
10151        .expect("the codex reset wording is a recognised shape");
10152        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
10153
10154        // The month is explicit, so a date already earlier in the same
10155        // sentence-implied year than `now` is trusted as written rather than
10156        // rolled forward a year the way the bracketed shape rolls a
10157        // same-day clock reading to tomorrow.
10158        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
10159            .expect("an explicit year needs no rollover");
10160        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
10161
10162        assert!(
10163            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
10164            "a two-digit year is not the documented shape and is not guessed at"
10165        );
10166        assert!(
10167            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
10168            "a four-letter month name is not the documented three-letter abbreviation"
10169        );
10170        assert!(
10171            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10172            "an explicit zone on the dated shape is a format nobody has \
10173             documented, and is refused rather than guessed at as UTC"
10174        );
10175    }
10176
10177    #[test]
10178    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10179        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10180        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10181
10182        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10183        assert_eq!(at.as_second() - recorded.as_second(), 3769);
10184
10185        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10186        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10187
10188        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10189            assert!(
10190                parse_reset_hint(bad, now, recorded).is_none(),
10191                "{bad:?} must not be guessed at"
10192            );
10193        }
10194    }
10195
10196    /// A loop whose queue lives in a temp tree and whose poll interval is far
10197    /// longer than the test's patience, so anything that waits out a poll
10198    /// instead of noticing the stop fails rather than merely being slow.
10199    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10200        let config = dir.join("magi.toml");
10201        std::fs::write(
10202            &config,
10203            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10204        )
10205        .unwrap();
10206        let opts = Opts {
10207            poll: Duration::from_secs(30),
10208            config: Some(config),
10209            // The explicit fixture config keeps startup cleanup from reading
10210            // machine configuration. This fictional repository likewise
10211            // keeps any best-effort git cleanup away from this checkout.
10212            repo: dir.join("repo"),
10213            ..Opts::default()
10214        };
10215        // The status file goes in a directory that does not exist yet, so its
10216        // creation is itself evidence the loop published one. `worktrees`
10217        // must be just as fictional: the janitor reclaims worktrees under it
10218        // for real, and a test that let it fall through to
10219        // `crate::run::default_worktree_root()` would have it reclaim
10220        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
10221        // which is exactly what happened before this function took the
10222        // parameter at all.
10223        let home = dir.join("home");
10224        // These control-only fixtures do not launch native workers. Give the
10225        // independently tested maintenance services a fresh cadence receipt.
10226        let stamps = home.join("service-ticks");
10227        std::fs::create_dir_all(&stamps).unwrap();
10228        for service in ["waiter", "deputies", "release-watch"] {
10229            std::fs::write(
10230                stamps.join(service),
10231                Timestamp::now().as_second().to_string(),
10232            )
10233            .unwrap();
10234        }
10235        for operation in [
10236            "conductor",
10237            "maintenance",
10238            "housekeeping",
10239            "disk-pressure",
10240            "cache",
10241            "fetch",
10242        ] {
10243            std::fs::write(
10244                stamps.join(format!("daemon-{operation}")),
10245                serde_json::to_vec(&Timestamp::now()).unwrap(),
10246            )
10247            .unwrap();
10248        }
10249        let worktrees = dir.join("wt");
10250        (
10251            opts,
10252            Queue::at(dir.join("queue")),
10253            home.join("daemon.json"),
10254            home,
10255            worktrees,
10256        )
10257    }
10258
10259    #[test]
10260    fn a_stop_is_idempotent_and_once_set_stays_set() {
10261        let stop = Stop::new();
10262        assert!(!stop.stopped());
10263
10264        stop.stop();
10265        assert!(stop.stopped());
10266        stop.stop();
10267        assert!(stop.stopped(), "a second stop is not a toggle");
10268
10269        let shared = stop.clone();
10270        assert!(
10271            shared.stopped(),
10272            "a clone is the same stop; that is how the loop and its caller share one"
10273        );
10274    }
10275
10276    #[tokio::test]
10277    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10278        for operation in ["conductor", "maintenance", "housekeeping"] {
10279            let dir = tempfile::tempdir().unwrap();
10280            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10281            opts.once = true;
10282            opts.poll = Duration::from_millis(1);
10283            let mut task = task();
10284            task.runs.push("fixture-run".into());
10285            queue.put(&mut task).unwrap();
10286            let claim = queue.claim(&task.id).unwrap();
10287
10288            // Model a live service holding the task's claim across the
10289            // scheduler's dispatch scan. No real subprocess or timed race.
10290            let directory = home.join("workers/jobs/abcdef");
10291            std::fs::create_dir_all(&directory).unwrap();
10292            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10293            crate::pr_head::try_lock_file(&lease).unwrap();
10294            let mut job = crate::worker::Job {
10295                id: "abcdef".into(),
10296                sequence: 1,
10297                kind: "daemon-service".into(),
10298                key: format!("service:daemon-{operation}"),
10299                payload: serde_json::Value::Null,
10300                generation: "fixture".into(),
10301                version: None,
10302                status: crate::worker::Status::Running,
10303                result: None,
10304                pid: Some(std::process::id()),
10305                created_at: Timestamp::now().as_second() as u64,
10306                finished_at: None,
10307            };
10308            let record = directory.join("job.json");
10309            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10310
10311            let status = Arc::new(Mutex::new(Status::new()));
10312            let stop = Stop::new();
10313            let mut drain = Box::pin(poll(
10314                &opts,
10315                &queue,
10316                &status,
10317                &home,
10318                &worktrees,
10319                &stop,
10320                DispatchLimits {
10321                    max_concurrent: 1,
10322                    pause_for_interrupts: false,
10323                    recovery_cfg: None,
10324                },
10325            ));
10326            std::future::poll_fn(|cx| {
10327                use std::future::Future;
10328                assert!(
10329                    drain.as_mut().poll(cx).is_pending(),
10330                    "--once must wait for {operation} to release its queue claim"
10331                );
10332                std::task::Poll::Ready(())
10333            })
10334            .await;
10335            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10336
10337            // An answer arrives while the service still owns the claim. A
10338            // fresh scheduling pass must apply it before declaring idle.
10339            let questions = Questions::at(home.join("questions"));
10340            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10341            questions.put(&mut q).unwrap();
10342            drop(claim);
10343            // Model services that took longer than their cadence, without a
10344            // wall-clock sleep. The final scans must not respawn them even
10345            // though their receipts now permit another periodic invocation.
10346            let expired =
10347                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10348            for service in [operation, "housekeeping"] {
10349                std::fs::write(
10350                    home.join("service-ticks").join(format!("daemon-{service}")),
10351                    &expired,
10352                )
10353                .unwrap();
10354            }
10355            job.status = crate::worker::Status::Finished;
10356            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10357            drop(lease);
10358            tokio::time::timeout(Duration::from_secs(2), drain)
10359                .await
10360                .expect("the settled service must allow the drain to finish")
10361                .unwrap();
10362            let after = queue.get(&task.id).unwrap();
10363            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10364            assert!(after.action_applied(&q.id));
10365            for service in [operation, "housekeeping"] {
10366                assert_eq!(
10367                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10368                        .unwrap(),
10369                    expired,
10370                    "the final once rescan must not restart {service}"
10371                );
10372            }
10373        }
10374    }
10375
10376    #[test]
10377    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10378        let stop = Stop::new();
10379        stop.busy.store(1, Ordering::SeqCst);
10380        assert!(
10381            !stop.finishing(),
10382            "a busy loop nobody has asked to stop is just running"
10383        );
10384
10385        stop.stop();
10386        assert!(
10387            stop.finishing(),
10388            "a stop asked for mid-run has not landed until the run is settled"
10389        );
10390
10391        stop.busy.store(0, Ordering::SeqCst);
10392        assert!(
10393            !stop.finishing(),
10394            "once the run is settled the stop has landed and there is nothing to finish"
10395        );
10396    }
10397
10398    #[test]
10399    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10400        let stop = Stop::new();
10401        stop.busy.store(2, Ordering::SeqCst);
10402        stop.stop();
10403        assert!(stop.finishing(), "two runs still in flight");
10404
10405        stop.busy.store(1, Ordering::SeqCst);
10406        assert!(
10407            stop.finishing(),
10408            "one run finished, but a sibling is still working"
10409        );
10410
10411        stop.busy.store(0, Ordering::SeqCst);
10412        assert!(
10413            !stop.finishing(),
10414            "the last run out is what actually lands the stop"
10415        );
10416    }
10417
10418    #[tokio::test]
10419    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10420        let dir = tempfile::tempdir().unwrap();
10421        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10422        let stop = Stop::new();
10423        stop.stop();
10424
10425        let began = std::time::Instant::now();
10426        tokio::time::timeout(
10427            Duration::from_secs(2),
10428            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10429        )
10430        .await
10431        .expect("a stopped loop must return, not sit out its poll interval")
10432        .expect("the loop's own setup and teardown must not fail");
10433        assert!(
10434            began.elapsed() < opts.poll,
10435            "returned only after {:?}, which is a poll interval, not a stop",
10436            began.elapsed()
10437        );
10438    }
10439
10440    #[tokio::test]
10441    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10442        let dir = tempfile::tempdir().unwrap();
10443        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10444        let stop = Stop::new();
10445
10446        // Asked for after the loop is already parked on its empty queue, which
10447        // is the case an operator tapping stop on a phone actually hits.
10448        let asker = {
10449            let stop = stop.clone();
10450            tokio::spawn(async move {
10451                tokio::time::sleep(Duration::from_millis(20)).await;
10452                stop.stop();
10453            })
10454        };
10455
10456        let began = std::time::Instant::now();
10457        tokio::time::timeout(
10458            Duration::from_secs(2),
10459            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10460        )
10461        .await
10462        .expect("a stop asked for while idle must wake the wait")
10463        .expect("the loop's own setup and teardown must not fail");
10464        asker.await.unwrap();
10465        assert!(
10466            began.elapsed() < opts.poll,
10467            "returned only after {:?}, so the stop waited on the sleep",
10468            began.elapsed()
10469        );
10470    }
10471
10472    #[tokio::test]
10473    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10474        let dir = tempfile::tempdir().unwrap();
10475        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10476        let stop = Stop::new();
10477        stop.stop();
10478
10479        tokio::time::timeout(
10480            Duration::from_secs(2),
10481            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10482        )
10483        .await
10484        .expect("a stopped loop must return")
10485        .expect("the loop's own setup and teardown must not fail");
10486
10487        assert!(
10488            home.is_dir(),
10489            "the loop did publish a status file, so its removal is the teardown and not an absence"
10490        );
10491        assert!(
10492            !status_file.exists(),
10493            "a stopped loop clears its status file"
10494        );
10495        assert!(
10496            read_status(&home).is_none(),
10497            "a reader must see no daemon at all, not a heartbeat that merely stopped"
10498        );
10499    }
10500
10501    #[tokio::test]
10502    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10503        let dir = tempfile::tempdir().unwrap();
10504        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10505
10506        let mut settled = RunState::new(
10507            dir.path().join("repo"),
10508            "main".to_owned(),
10509            "abc1234".to_owned(),
10510            "fixture".to_owned(),
10511            Config::default(),
10512        );
10513        settled.status = RunStatus::Ready;
10514        let run_dir = home.join("runs").join(&settled.id);
10515        std::fs::create_dir_all(&run_dir).unwrap();
10516        std::fs::write(
10517            run_dir.join("run.json"),
10518            serde_json::to_string_pretty(&settled).unwrap(),
10519        )
10520        .unwrap();
10521        let questions = Questions::at(home.join("questions"));
10522        let mut question = ask::Question::new(
10523            settled.id.clone(),
10524            "review".to_owned(),
10525            "reviewer-1".to_owned(),
10526            "Continue?".to_owned(),
10527            String::new(),
10528            Vec::new(),
10529        );
10530        questions.put(&mut question).unwrap();
10531
10532        run_service_worker(
10533            &home,
10534            serde_json::to_value(ServiceWorker {
10535                opts,
10536                queue: queue.root().to_path_buf(),
10537                worktrees_root: worktrees,
10538                operation: "housekeeping".to_owned(),
10539            })
10540            .unwrap(),
10541        )
10542        .await
10543        .unwrap();
10544
10545        assert_eq!(
10546            questions.get(&question.id).unwrap().status,
10547            ask::QuestionStatus::Abandoned,
10548            "the independent housekeeping worker settles ended-run questions"
10549        );
10550    }
10551
10552    #[test]
10553    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10554        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10555
10556        assert!(
10557            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10558            "never checked before: due at once"
10559        );
10560
10561        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10562        assert!(
10563            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10564            "well inside the interval: not due yet"
10565        );
10566
10567        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10568        assert!(
10569            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10570            "exactly at the edge: not yet due, same convention as `clean::due`"
10571        );
10572
10573        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10574        assert!(
10575            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10576            "past the interval: due again"
10577        );
10578    }
10579
10580    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
10581    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
10582    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
10583    /// and the congestion test below both need, and must not drift apart.
10584    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10585        let config = dir.join("magi.toml");
10586        // A literal (single-quoted) TOML string, not a basic one: the cache
10587        // path is a Windows path full of backslashes, and a basic string
10588        // would have TOML try to interpret `\U` (from `\Users\...`) as a
10589        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
10590        // `{{ vars.cache }}` rendering documents.
10591        std::fs::write(
10592            &config,
10593            format!(
10594                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10595                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10596                cache_dir.display()
10597            ),
10598        )
10599        .unwrap();
10600        Opts {
10601            config: Some(config),
10602            repo: dir.join("repo"),
10603            ..Opts::default()
10604        }
10605    }
10606
10607    #[tokio::test]
10608    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10609        let dir = tempfile::tempdir().unwrap();
10610        let home = dir.path().join("home");
10611        let cache_dir = dir.path().join("cache");
10612        std::fs::create_dir_all(&cache_dir).unwrap();
10613        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10614        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10615
10616        // Nobody has asked this daemon to stop, which is the ordinary case;
10617        // the skip that a stop buys is asserted by its own test below.
10618        let running = Stop::new();
10619        let mut last_checked = None;
10620        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10621        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10622            .await;
10623        assert_eq!(
10624            crate::disk::dir_size(&cache_dir),
10625            0,
10626            "over the cap on the first check ever: pruned at once, no idle queue required"
10627        );
10628        assert_eq!(last_checked, Some(t0));
10629
10630        // A fresh oversized file lands, but the next check is not due yet.
10631        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10632        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10633        maybe_prune_cache_between_runs(
10634            &opts.repo,
10635            &opts,
10636            &home,
10637            &running,
10638            &mut last_checked,
10639            too_soon,
10640        )
10641        .await;
10642        assert_eq!(
10643            crate::disk::dir_size(&cache_dir),
10644            10,
10645            "too soon since the last check: left alone rather than rescanned every call"
10646        );
10647        assert_eq!(
10648            last_checked,
10649            Some(t0),
10650            "an idle check does not reset the clock"
10651        );
10652
10653        // Once the interval elapses, the same oversized cache is caught again.
10654        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10655        maybe_prune_cache_between_runs(
10656            &opts.repo,
10657            &opts,
10658            &home,
10659            &running,
10660            &mut last_checked,
10661            due_again,
10662        )
10663        .await;
10664        assert_eq!(
10665            crate::disk::dir_size(&cache_dir),
10666            0,
10667            "due again: pruned back under the cap"
10668        );
10669    }
10670
10671    /// A stop must not queue behind housekeeping. The prune below is a
10672    /// synchronous walk of the whole cache with no await point in it, so a
10673    /// loop that entered it could not get back to its own `stopped()` test
10674    /// until the walk finished - and because no run is in flight at this
10675    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
10676    /// the stop had already landed. The idle branch has always made this same
10677    /// check before reaching `janitor`; the between-runs path makes it too.
10678    #[tokio::test]
10679    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10680        let dir = tempfile::tempdir().unwrap();
10681        let home = dir.path().join("home");
10682        let cache_dir = dir.path().join("cache");
10683        std::fs::create_dir_all(&cache_dir).unwrap();
10684        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10685        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10686
10687        let stop = Stop::new();
10688        stop.stop();
10689        assert!(
10690            !stop.finishing(),
10691            "no run is in flight at a between-runs boundary, so nothing else \
10692             would tell the operator this stop had not taken effect yet"
10693        );
10694
10695        let mut last_checked = None;
10696        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10697        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10698            .await;
10699        assert_eq!(
10700            crate::disk::dir_size(&cache_dir),
10701            10,
10702            "over its cap, and due for the first check ever, but a stop outranks \
10703             it: the cap is a standing policy the next start measures again"
10704        );
10705        assert_eq!(
10706            last_checked, None,
10707            "a check that never happened must not claim the interval"
10708        );
10709    }
10710
10711    /// A backlog must not starve cache pruning. The finite cache worker runs
10712    /// independently of queue drain and must not consume any task attempts.
10713    #[tokio::test]
10714    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10715        let dir = tempfile::tempdir().unwrap();
10716        let cache_dir = dir.path().join("cache");
10717        std::fs::create_dir_all(&cache_dir).unwrap();
10718        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10719
10720        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10721        opts.poll = Duration::from_millis(20);
10722        opts.max_attempts = 1_000;
10723
10724        let queue = Queue::at(dir.path().join("queue"));
10725        for i in 0..128 {
10726            let mut task = Task::new(
10727                format!("queued work {i}"),
10728                format!("queued work {i}"),
10729                opts.repo.clone(),
10730                Source::Human,
10731            );
10732            queue.put(&mut task).unwrap();
10733        }
10734
10735        let home = dir.path().join("home");
10736        let worktrees = dir.path().join("wt");
10737        run_service_worker(
10738            &home,
10739            serde_json::to_value(ServiceWorker {
10740                opts,
10741                queue: queue.root().to_path_buf(),
10742                worktrees_root: worktrees,
10743                operation: "cache".to_owned(),
10744            })
10745            .unwrap(),
10746        )
10747        .await
10748        .unwrap();
10749        let after = queue.list();
10750        assert_eq!(after.len(), 128);
10751        assert!(
10752            after
10753                .iter()
10754                .all(|task| task.status.runnable() && task.attempts == 0)
10755        );
10756
10757        assert_eq!(
10758            crate::disk::dir_size(&cache_dir),
10759            0,
10760            "an oversized cache must not be left to grow unboundedly just because the \
10761             queue kept the loop busy the whole time"
10762        );
10763    }
10764
10765    #[test]
10766    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10767        let dir = tempfile::tempdir().unwrap();
10768        let queue = Queue::at(dir.path().join("queue"));
10769        let questions = Questions::at(dir.path().join("questions"));
10770        let mut task = task();
10771        queue.put(&mut task).unwrap();
10772
10773        let mut task_question = ask::Question::new(
10774            task.id.clone(),
10775            crate::conduct::NODE.to_owned(),
10776            "conduct".to_owned(),
10777            "Which backend?".to_owned(),
10778            String::new(),
10779            Vec::new(),
10780        );
10781        questions.put(&mut task_question).unwrap();
10782        task.block(vec![task_question.id.clone()], None);
10783        queue.put(&mut task).unwrap();
10784
10785        let mut run_question = ask::Question::new(
10786            "20260101-000000-run1".to_owned(),
10787            "review".to_owned(),
10788            "reviewer-1".to_owned(),
10789            "Run question".to_owned(),
10790            String::new(),
10791            Vec::new(),
10792        );
10793        questions.put(&mut run_question).unwrap();
10794
10795        // A question from another node whose `run` happens to equal this
10796        // task's id — the same field, filled in for an unrelated reason. Only
10797        // `crate::conduct::NODE` questions use `run` as a task id; this one
10798        // must never be touched by this reconciliation, even after release.
10799        let mut coincidental = ask::Question::new(
10800            task.id.clone(),
10801            "review".to_owned(),
10802            "reviewer-1".to_owned(),
10803            "Unrelated review question".to_owned(),
10804            String::new(),
10805            Vec::new(),
10806        );
10807        questions.put(&mut coincidental).unwrap();
10808
10809        reconcile_task_questions(&queue, &questions);
10810        assert!(questions.get(&task_question.id).unwrap().status.open());
10811        assert!(questions.get(&run_question.id).unwrap().status.open());
10812        assert!(questions.get(&coincidental.id).unwrap().status.open());
10813
10814        task.release();
10815        queue.put(&mut task).unwrap();
10816        reconcile_task_questions(&queue, &questions);
10817        assert_eq!(
10818            questions.get(&task_question.id).unwrap().status,
10819            ask::QuestionStatus::Abandoned
10820        );
10821        assert!(
10822            questions.get(&run_question.id).unwrap().status.open(),
10823            "run questions remain the run janitor's responsibility"
10824        );
10825        assert!(
10826            questions.get(&coincidental.id).unwrap().status.open(),
10827            "a non-conductor question must not be abandoned just because its \
10828             run id coincides with a task id"
10829        );
10830    }
10831
10832    #[test]
10833    fn a_freshly_started_running_task_is_never_stalled() {
10834        let dir = tempfile::tempdir().unwrap();
10835        let mut t = task();
10836        t.start("run-1".to_owned());
10837        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
10838        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
10839        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10840    }
10841
10842    #[test]
10843    fn a_long_running_task_with_no_live_daemon_is_stalled() {
10844        let dir = tempfile::tempdir().unwrap();
10845        let mut t = task();
10846        t.start("run-1".to_owned());
10847        t.updated_at = Timestamp::now()
10848            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10849        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
10850        assert_eq!(
10851            stalled_tasks(
10852                &Queue::at(dir.path().join("q")),
10853                dir.path(),
10854                Timestamp::now()
10855            )
10856            .len(),
10857            0,
10858            "the task was never written to this queue"
10859        );
10860    }
10861
10862    #[test]
10863    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
10864        let dir = tempfile::tempdir().unwrap();
10865        let mut t = task();
10866        t.id = "20260903-080340-0167".to_owned();
10867        t.start("20260903-080619-01c2".to_owned());
10868        t.updated_at = Timestamp::now()
10869            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10870
10871        let mut status = Status::new();
10872        status.current = vec![Current {
10873            worker: None,
10874            task: t.id.clone(),
10875            run: "20260903-080619-01c2".to_owned(),
10876        }];
10877        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10878
10879        assert!(
10880            !is_stalled(&t, dir.path(), Timestamp::now()),
10881            "a live daemon's own heartbeat rules out stalled, however long the task has run"
10882        );
10883    }
10884
10885    /// Rewrite a task's `updated_at` on disk directly, bypassing
10886    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
10887    /// a fixture look like it has genuinely been `running` for a while.
10888    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
10889        let path = queue.path_of(id);
10890        let body = std::fs::read_to_string(&path).unwrap();
10891        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
10892        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
10893        v["updated_at"] = serde_json::Value::String(old.to_string());
10894        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
10895    }
10896
10897    #[test]
10898    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
10899        // The realistic `poll()` ordering, not `is_stalled` in isolation:
10900        // `reclaim_orphaned_running` runs first, on every poll, and settles
10901        // any `running` task whose claim it can actually take. For most
10902        // crashes that is immediate - a dead pid is proof enough for
10903        // `sweep_stale_claims` to drop the lock the same tick, and the very
10904        // next claim attempt succeeds. But a lock whose pid cannot be parsed
10905        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
10906        // `sweep_stale_claims`'s own doc), so the lock - and the claim
10907        // failure behind it - can legitimately outlive many polls. This is
10908        // exactly the gap `stalled_tasks` exists to surface well before that
10909        // six-hour sweep would: reclaim leaves the task `running`, and it
10910        // must still reach the conductor as stalled.
10911        let dir = tempfile::tempdir().unwrap();
10912        let queue = Queue::at(dir.path().join("queue"));
10913        let home = dir.path().join("home");
10914
10915        let mut t = task();
10916        t.id = "20260101-000001-lock".to_owned();
10917        t.start("run-1".to_owned());
10918        queue.put(&mut t).unwrap();
10919        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10920        std::fs::write(
10921            dir.path().join("queue").join(format!("{}.lock", t.id)),
10922            "not a pid",
10923        )
10924        .unwrap();
10925
10926        let now = Timestamp::now();
10927        assert!(
10928            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
10929            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
10930             and reclaim must leave the task alone"
10931        );
10932        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10933
10934        let stalled = stalled_tasks(&queue, &home, now);
10935        assert_eq!(
10936            stalled.len(),
10937            1,
10938            "reclaim's inability to claim it yet must not hide it from the conductor"
10939        );
10940        assert_eq!(stalled[0].id, t.id);
10941    }
10942
10943    #[test]
10944    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
10945        let dir = tempfile::tempdir().unwrap();
10946        crate::run::set_home(dir.path().join("run-home"));
10947        let queue = Queue::at(dir.path().join("queue"));
10948        let home = dir.path().join("home");
10949        let questions = Questions::at(dir.path().join("questions"));
10950
10951        let mut t = task();
10952        t.id = "20260101-000003-dead".to_owned();
10953        t.start("missing-run".to_owned());
10954        queue.put(&mut t).unwrap();
10955        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10956
10957        // This is the real poll ordering: retain the deterministic stalled
10958        // input before a claim proves the owner is gone and reclaims it.
10959        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10960        assert_eq!(
10961            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
10962            [&t.id]
10963        );
10964        assert_eq!(
10965            reclaim_orphaned_running(&queue, 2, &Default::default()),
10966            [t.id.clone()]
10967        );
10968        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10969
10970        // Reclaim drops its guard before conductor decisions are applied, so
10971        // the decision for the captured stalled input has a real write path.
10972        crate::conduct::apply(
10973            &queue,
10974            &questions,
10975            &crate::conduct::Verdict {
10976                decisions: vec![crate::conduct::Decision {
10977                    id: t.id.clone(),
10978                    recovery: Some(crate::conduct::Recovery::Requeue),
10979                    ..crate::conduct::Decision::default()
10980                }],
10981            },
10982        )
10983        .unwrap();
10984        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10985    }
10986
10987    #[test]
10988    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
10989        let dir = tempfile::tempdir().unwrap();
10990        let queue = Queue::at(dir.path().join("queue"));
10991        let home = dir.path().join("home");
10992
10993        let mut fresh = task();
10994        fresh.id = "20260101-000001-aaaa".to_owned();
10995        fresh.start("run-1".to_owned());
10996        queue.put(&mut fresh).unwrap();
10997
10998        let mut old = task();
10999        old.id = "20260101-000002-bbbb".to_owned();
11000        old.start("run-2".to_owned());
11001        queue.put(&mut old).unwrap();
11002        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
11003
11004        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11005        assert_eq!(stalled.len(), 1);
11006        assert_eq!(stalled[0].id, old.id);
11007    }
11008
11009    #[test]
11010    fn queued_and_finished_task_views_partition_by_status() {
11011        let dir = tempfile::tempdir().unwrap();
11012        let queue = Queue::at(dir.path().join("queue"));
11013
11014        let mut queued = task();
11015        queued.id = "20260101-000001-aaaa".to_owned();
11016        queue.put(&mut queued).unwrap();
11017
11018        let mut failed = task();
11019        failed.id = "20260101-000002-bbbb".to_owned();
11020        failed.start("run-1".to_owned());
11021        failed.fail("gate red", 5);
11022        queue.put(&mut failed).unwrap();
11023
11024        let mut held = task();
11025        held.id = "20260101-000003-cccc".to_owned();
11026        held.hold_machine(None);
11027        queue.put(&mut held).unwrap();
11028
11029        let mut running = task();
11030        running.id = "20260101-000004-dddd".to_owned();
11031        running.start("run-2".to_owned());
11032        queue.put(&mut running).unwrap();
11033
11034        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
11035        assert_eq!(queued_ids, [queued.id.clone()]);
11036
11037        let mut finished_ids: Vec<String> =
11038            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
11039        finished_ids.sort_unstable();
11040        let mut want = vec![failed.id.clone(), held.id.clone()];
11041        want.sort_unstable();
11042        assert_eq!(finished_ids, want);
11043    }
11044
11045    #[test]
11046    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
11047        for short in [false, true] {
11048            let dir = tempfile::tempdir().unwrap();
11049            let queue = Queue::at(dir.path().join("queue"));
11050            let questions = ask::Questions::at(dir.path().join("questions"));
11051            let mut running = task();
11052            running.id = "20261013-192213-feb2".into();
11053            running.start("existing-run".into());
11054            queue.put(&mut running).unwrap();
11055            let mut middle = task();
11056            middle.id = "20261013-193611-ca5b".into();
11057            middle.block(
11058                vec![if short {
11059                    "feb2".into()
11060                } else {
11061                    running.id.clone()
11062                }],
11063                None,
11064            );
11065            queue.put(&mut middle).unwrap();
11066            let mut waiting = task();
11067            waiting.id = "20261013-202849-ee37".into();
11068            waiting.block(
11069                vec![if short {
11070                    "ca5b".into()
11071                } else {
11072                    middle.id.clone()
11073                }],
11074                Some("wait for implementation".into()),
11075            );
11076            queue.put(&mut waiting).unwrap();
11077            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
11078            let inv = crate::blockers::Inventory::load(&queue, &questions);
11079            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
11080            assert!(inv.stuck().is_empty());
11081            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11082            assert!(report.quarantined.is_empty());
11083            assert!(report.asked.is_empty());
11084            resolve_blockers(&queue, &questions);
11085            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11086            assert!(questions.list().is_empty());
11087            // Finishing the transitive prerequisite alone does not satisfy
11088            // the task's direct dependency.
11089            running.succeed();
11090            queue.put(&mut running).unwrap();
11091            resolve_blockers(&queue, &questions);
11092            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
11093            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11094            middle = queue.get(&middle.id).unwrap();
11095            middle.succeed();
11096            queue.put(&mut middle).unwrap();
11097            resolve_blockers(&queue, &questions);
11098            let after = queue.get(&waiting.id).unwrap();
11099            assert_eq!(after.status, TaskStatus::Queued);
11100            assert!(after.blocked_by.is_empty());
11101            assert_eq!(after.instruction, waiting.instruction);
11102        }
11103    }
11104
11105    #[test]
11106    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
11107        for future_schema in [false, true] {
11108            let name = "20261013-193611-ca5b";
11109            let mut future = task();
11110            future.id = name.into();
11111            future.schema = crate::queue::SCHEMA + 1;
11112            let contents = if future_schema {
11113                serde_json::to_string(&future).unwrap()
11114            } else {
11115                "corrupt".into()
11116            };
11117            let dir = tempfile::tempdir().unwrap();
11118            let queue = Queue::at(dir.path().join("queue"));
11119            let questions = ask::Questions::at(dir.path().join("questions"));
11120            let mut waiting = task();
11121            waiting.id = "20261013-202849-ee37".into();
11122            waiting.block(vec!["ca5b".into()], None);
11123            queue.put(&mut waiting).unwrap();
11124            std::fs::write(queue.path_of(name), contents).unwrap();
11125            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
11126            assert!(
11127                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
11128            );
11129            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11130            assert!(report.asked.is_empty());
11131            resolve_blockers(&queue, &questions);
11132            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11133            assert!(questions.list().is_empty());
11134        }
11135        let dir = tempfile::tempdir().unwrap();
11136        let queue = Queue::at(dir.path().join("queue"));
11137        let questions = ask::Questions::at(dir.path().join("questions"));
11138        let mut waiting = task();
11139        waiting.id = "20261013-202849-ee37".into();
11140        waiting.block(vec!["ca5b".into()], None);
11141        queue.put(&mut waiting).unwrap();
11142        let mut done = task();
11143        done.id = "20261013-193611-ca5b".into();
11144        done.succeed();
11145        queue.put(&mut done).unwrap();
11146        // An unreadable second match must not disappear from uniqueness
11147        // checks just because Queue::list skips it.
11148        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
11149        assert!(queue.get("ca5b").is_err());
11150        assert_eq!(
11151            crate::queue::dependency(&queue, &questions, "ca5b"),
11152            crate::queue::Dependency::Ambiguous
11153        );
11154        resolve_blockers(&queue, &questions);
11155        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11156        assert!(report.asked.is_empty());
11157        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11158        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
11159    }
11160
11161    #[test]
11162    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
11163        for held in [false, true] {
11164            for question in [false, true] {
11165                for reference in ["ca5b", "20261013-193611-ca5b"] {
11166                    let dir = tempfile::tempdir().unwrap();
11167                    let queue = Queue::at(dir.path().join("queue"));
11168                    let questions = ask::Questions::at(dir.path().join("questions"));
11169                    let mut prerequisite = task();
11170                    prerequisite.id = "20261013-193611-ca5b".into();
11171                    prerequisite.start("existing-run".into());
11172                    queue.put(&mut prerequisite).unwrap();
11173                    let mut waiting = task();
11174                    waiting.id = "20261013-202849-ee37".into();
11175                    if held {
11176                        waiting.hold_machine(Some("waiting for separate consent".into()));
11177                    }
11178                    queue.put(&mut waiting).unwrap();
11179                    let reason = "Deleting saved data requires separate owner consent";
11180                    crate::conduct::apply(
11181                        &queue,
11182                        &questions,
11183                        &crate::conduct::Verdict {
11184                            decisions: vec![crate::conduct::Decision {
11185                                id: waiting.id.clone(),
11186                                blocked_by: vec![reference.into()],
11187                                question: question.then(|| "May the saved data be deleted?".into()),
11188                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11189                                reason: Some(reason.into()),
11190                                ..crate::conduct::Decision::default()
11191                            }],
11192                        },
11193                    )
11194                    .unwrap();
11195                    let before = queue.get(&waiting.id).unwrap();
11196                    if question {
11197                        assert_eq!(before.status, TaskStatus::Blocked);
11198                        let q = questions.get(&before.blocked_by[0]).unwrap();
11199                        assert_eq!(q.summary, "May the saved data be deleted?");
11200                        assert!(q.status.open());
11201                    } else {
11202                        assert_eq!(before.status, TaskStatus::Held);
11203                        let recorded_reason = before.hold_reason.as_deref().unwrap();
11204                        assert!(recorded_reason.starts_with(reason));
11205                        if held {
11206                            assert!(recorded_reason.contains("waiting for separate consent"));
11207                        }
11208                    }
11209                    prerequisite.succeed();
11210                    queue.put(&mut prerequisite).unwrap();
11211                    resolve_blockers(&queue, &questions);
11212                    let after = queue.get(&waiting.id).unwrap();
11213                    assert_eq!(after.status, before.status);
11214                    assert_eq!(after.blocked_by, before.blocked_by);
11215                    assert_eq!(after.hold_reason, before.hold_reason);
11216                    assert_eq!(after.instruction, waiting.instruction);
11217                    if question {
11218                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11219                    }
11220                    assert!(
11221                        queue.next_runnable().is_none(),
11222                        "dependency completion is not consent"
11223                    );
11224                }
11225            }
11226        }
11227    }
11228
11229    #[test]
11230    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11231        let dir = tempfile::tempdir().unwrap();
11232        let queue = Queue::at(dir.path().join("queue"));
11233        let questions = ask::Questions::at(dir.path().join("questions"));
11234
11235        let mut dep = task();
11236        dep.id = "20260101-000001-dep0".to_owned();
11237        dep.succeed();
11238        queue.put(&mut dep).unwrap();
11239
11240        let mut still_going = task();
11241        still_going.id = "20260101-000002-dep1".to_owned();
11242        queue.put(&mut still_going).unwrap();
11243
11244        let mut blocked = task();
11245        blocked.id = "20260101-000003-main".to_owned();
11246        blocked.block(
11247            vec![dep.id.clone(), still_going.id.clone()],
11248            Some("waits on both".to_owned()),
11249        );
11250        queue.put(&mut blocked).unwrap();
11251
11252        resolve_blockers(&queue, &questions);
11253
11254        let after = queue.get(&blocked.id).unwrap();
11255        assert_eq!(
11256            after.status,
11257            TaskStatus::Blocked,
11258            "one dependency is still outstanding"
11259        );
11260        assert_eq!(after.blocked_by, [still_going.id.clone()]);
11261    }
11262
11263    #[test]
11264    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11265        let dir = tempfile::tempdir().unwrap();
11266        let queue = Queue::at(dir.path().join("queue"));
11267        let questions = ask::Questions::at(dir.path().join("questions"));
11268
11269        let mut q = crate::ask::Question::new(
11270            "20260101-000001-main".to_owned(),
11271            crate::conduct::NODE.to_owned(),
11272            "conduct".to_owned(),
11273            "Which backend?".to_owned(),
11274            String::new(),
11275            Vec::new(),
11276        );
11277        questions.put(&mut q).unwrap();
11278        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11279            .unwrap();
11280        questions.put(&mut q).unwrap();
11281
11282        let mut blocked = task();
11283        blocked.id = "20260101-000001-main".to_owned();
11284        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11285        queue.put(&mut blocked).unwrap();
11286
11287        resolve_blockers(&queue, &questions);
11288
11289        let after = queue.get(&blocked.id).unwrap();
11290        assert_eq!(
11291            after.status,
11292            TaskStatus::Queued,
11293            "the only blocker resolved"
11294        );
11295        assert_eq!(after.answers.len(), 1);
11296        assert_eq!(after.answers[0].question, "Which backend?");
11297        assert_eq!(after.answers[0].answer, "SQLite");
11298
11299        // And the run this task starts next is told about it.
11300        let instruction = instruction_for(&after);
11301        assert!(instruction.contains("Which backend?"));
11302        assert!(instruction.contains("SQLite"));
11303    }
11304
11305    #[test]
11306    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11307        let dir = tempfile::tempdir().unwrap();
11308        let queue = Queue::at(dir.path().join("queue"));
11309        let questions = ask::Questions::at(dir.path().join("questions"));
11310
11311        let mut q = crate::ask::Question::new(
11312            "20260101-000001-main".to_owned(),
11313            crate::conduct::NODE.to_owned(),
11314            "conduct".to_owned(),
11315            "Is the setup done?".to_owned(),
11316            String::new(),
11317            Vec::new(),
11318        );
11319        q.abandon("no answer within 60s of asking");
11320        questions.put(&mut q).unwrap();
11321
11322        let mut blocked = task();
11323        blocked.id = "20260101-000001-main".to_owned();
11324        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11325        queue.put(&mut blocked).unwrap();
11326
11327        resolve_blockers(&queue, &questions);
11328
11329        let after = queue.get(&blocked.id).unwrap();
11330        assert_eq!(
11331            after.status,
11332            TaskStatus::Held,
11333            "never left blocked on nothing"
11334        );
11335        assert!(!after.operator_held(), "a machine hold, for triage");
11336        assert!(
11337            after
11338                .hold_reason
11339                .as_deref()
11340                .unwrap_or_default()
11341                .contains("went unanswered")
11342        );
11343    }
11344
11345    #[test]
11346    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11347        // Reproduces the reported bug (task 3958): a task held out of
11348        // attempts, blocked on a `crate::conduct` follow-up question, must
11349        // come back `held` once that question is answered - never `queued`,
11350        // whatever the answer said - or it silently re-enters the
11351        // competition queue with its attempts already exhausted.
11352        let dir = tempfile::tempdir().unwrap();
11353        let queue = Queue::at(dir.path().join("queue"));
11354        let questions = ask::Questions::at(dir.path().join("questions"));
11355
11356        let mut q = crate::ask::Question::new(
11357            "20260101-000001-main".to_owned(),
11358            crate::conduct::NODE.to_owned(),
11359            "conduct".to_owned(),
11360            "How should this be handled?".to_owned(),
11361            String::new(),
11362            Vec::new(),
11363        );
11364        questions.put(&mut q).unwrap();
11365        q.answer(crate::ask::Answer::Text(
11366            "leave it held, a human will look at it later".to_owned(),
11367        ))
11368        .unwrap();
11369        questions.put(&mut q).unwrap();
11370
11371        let mut held = task();
11372        held.id = "20260101-000001-main".to_owned();
11373        held.hold_machine(Some("out of attempts".to_owned()));
11374        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11375        queue.put(&mut held).unwrap();
11376
11377        resolve_blockers(&queue, &questions);
11378
11379        let after = queue.get(&held.id).unwrap();
11380        assert_eq!(after.status, TaskStatus::Held);
11381        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11382        assert_eq!(
11383            after.answers[0].answer,
11384            "leave it held, a human will look at it later"
11385        );
11386    }
11387
11388    #[test]
11389    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11390        let dir = tempfile::tempdir().unwrap();
11391        let queue = Queue::at(dir.path().join("queue"));
11392        let questions = ask::Questions::at(dir.path().join("questions"));
11393        let mut dep = task();
11394        dep.id = "20260101-000001-gone".to_owned();
11395        queue.put(&mut dep).unwrap();
11396        let mut blocked = task();
11397        blocked.id = "20260101-000003-main".to_owned();
11398        blocked.block(vec![dep.id.clone()], None);
11399        queue.put(&mut blocked).unwrap();
11400
11401        // Claimed, so `remove` cannot rewrite it and the resolver must.
11402        let claim = queue.claim(&blocked.id).unwrap();
11403        queue.remove(&dep.id, false, &questions).unwrap();
11404        drop(claim);
11405        resolve_blockers(&queue, &questions);
11406
11407        let after = queue.get(&blocked.id).unwrap();
11408        assert_eq!(after.status, TaskStatus::Queued);
11409        assert!(after.blocked_by.is_empty());
11410    }
11411
11412    #[test]
11413    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11414        // Reproduces the reported bug: a task blocked on a task id that was
11415        // removed (`magi task rm`, or deleted by hand) can never see that id
11416        // reach `Done`, so the ordinary per-id loop has nothing to notice and
11417        // would otherwise leave the task `blocked` forever with no way for an
11418        // operator to find out why.
11419        let dir = tempfile::tempdir().unwrap();
11420        let queue = Queue::at(dir.path().join("queue"));
11421        let questions = ask::Questions::at(dir.path().join("questions"));
11422
11423        let mut still_going = task();
11424        still_going.id = "20260101-000002-dep1".to_owned();
11425        queue.put(&mut still_going).unwrap();
11426
11427        let mut blocked = task();
11428        blocked.id = "20260101-000003-main".to_owned();
11429        blocked.block(
11430            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11431            Some("waits on both".to_owned()),
11432        );
11433        queue.put(&mut blocked).unwrap();
11434
11435        resolve_blockers(&queue, &questions);
11436
11437        let after = queue.get(&blocked.id).unwrap();
11438        assert_eq!(
11439            after.status,
11440            TaskStatus::Held,
11441            "a missing dependency must not leave the task blocked forever"
11442        );
11443        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11444        assert!(after.blocked_by.is_empty());
11445        let reason = after.hold_reason.as_deref().unwrap_or_default();
11446        assert!(
11447            reason.contains("20260101-000001-gone"),
11448            "the missing id must be named so an operator can tell what happened: {reason}"
11449        );
11450        assert!(
11451            reason.contains(&still_going.id),
11452            "the still-valid dependency must not silently vanish from the record: {reason}"
11453        );
11454    }
11455
11456    #[test]
11457    fn instruction_for_is_unchanged_without_any_answers() {
11458        let t = task();
11459        assert_eq!(instruction_for(&t), t.instruction);
11460    }
11461
11462    #[test]
11463    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11464        let dir = tempfile::tempdir().unwrap();
11465        let q = Queue::at(dir.path().join("queue"));
11466        let src = dir.path().join("shot.png");
11467        std::fs::write(&src, "x").unwrap();
11468        let mut t = task();
11469        q.attach(&mut t, &[src]).unwrap();
11470        let paths = task_attachments(&q, &t).unwrap();
11471        assert_eq!(paths.len(), 1);
11472        assert!(paths[0].is_absolute() && paths[0].is_file());
11473        std::fs::remove_file(&paths[0]).unwrap();
11474        let err = task_attachments(&q, &t).unwrap_err().to_string();
11475        assert!(err.contains("shot.png"), "{err}");
11476    }
11477
11478    #[tokio::test]
11479    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11480        let dir = tempfile::tempdir().unwrap();
11481        let queue_path = dir.path().join("queue");
11482        let queue = Queue::at(queue_path.clone());
11483        let mut t = task();
11484        t.source = Source::Agent {
11485            run: "originating-chat".into(),
11486            node: crate::queue::CHAT_NODE.into(),
11487        };
11488        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11489            stage: "config-fetch",
11490            target: "origin/main".into(),
11491        });
11492        record_config_failure(&mut t, &fetch);
11493        t.hold_machine(Some(format!("{fetch:#}")));
11494        let fetch_key = t.chat_notice_due().unwrap();
11495        t.chat_notices.push(fetch_key.clone());
11496        queue.put(&mut t).unwrap();
11497
11498        let queue = Queue::at(queue_path);
11499        let mut t = queue.get(&t.id).unwrap();
11500        let a = dir.path().join("a.toml");
11501        let b = dir.path().join("b.toml");
11502        for (path, text, new_cause) in [
11503            (&a, "[graph", true),
11504            (&a, "[verify", false),
11505            (&a, "[graph]\nimplementers = 'invalid-type'", true),
11506            (&b, "[graph]\nimplementers = 'invalid-type'", true),
11507        ] {
11508            t.release_operator("test", None);
11509            std::fs::write(path, text).unwrap();
11510            let error = Config::discover_fetched(dir.path(), Some(path))
11511                .await
11512                .unwrap_err();
11513            record_config_failure(&mut t, &error);
11514            t.hold_machine(Some(format!("{error:#}")));
11515            let due = t.chat_notice_due();
11516            assert_eq!(due.is_some(), new_cause, "{error:#}");
11517            if let Some(key) = due {
11518                assert_ne!(key, fetch_key);
11519                t.chat_notices.push(key);
11520            }
11521        }
11522        t.succeed();
11523        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11524    }
11525
11526    #[test]
11527    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11528        let dir = tempfile::tempdir().unwrap();
11529        let queue_path = dir.path().join("queue");
11530        let queue = Queue::at(queue_path.clone());
11531        let mut t = task();
11532        t.source = crate::queue::Source::Agent {
11533            run: "originating-chat".into(),
11534            node: crate::queue::CHAT_NODE.into(),
11535        };
11536        let a = dir.path().join("a.png");
11537        let b = dir.path().join("b.png");
11538        std::fs::write(&a, "a").unwrap();
11539        std::fs::write(&b, "b").unwrap();
11540        queue.attach(&mut t, &[a, b]).unwrap();
11541        let paths = task_attachments(&queue, &t).unwrap();
11542        for path in &paths {
11543            std::fs::remove_file(path).unwrap();
11544        }
11545        let missing = task_attachments(&queue, &t).unwrap_err();
11546        t.attempts += 1;
11547        let reason = missing.to_string();
11548        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11549        let first = t.chat_notice_due().expect("first attachment notice");
11550        t.chat_notices.push(first.clone());
11551        queue.put(&mut t).unwrap();
11552
11553        let queue = Queue::at(queue_path.clone());
11554        let mut t = queue.get(&t.id).unwrap();
11555        assert!(t.chat_notice_due().is_none(), "restart does not replay");
11556        t.release_operator("test", None);
11557        t.attempts += 1;
11558        let missing = task_attachments(&queue, &t).unwrap_err();
11559        t.fail_startup_target(
11560            "startup-attachments",
11561            missing.name,
11562            "same missing attachment with regenerated wording",
11563            1,
11564        );
11565        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11566
11567        std::fs::write(&paths[0], "restored").unwrap();
11568        t.release_operator("test", None);
11569        t.attempts += 1;
11570        let missing = task_attachments(&queue, &t).unwrap_err();
11571        let reason = missing.to_string();
11572        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11573        let second = t
11574            .chat_notice_due()
11575            .expect("different attachment must notify");
11576        assert_ne!(first, second);
11577        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11578    }
11579
11580    #[test]
11581    fn resumed_instruction_is_unchanged_without_any_answers() {
11582        let t = task();
11583        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11584    }
11585
11586    #[test]
11587    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11588        let mut t = task();
11589        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11590        // The run's own instruction on disk predates the answer: it is the
11591        // plain original text `Runner::start` saved before the operator was
11592        // ever asked anything.
11593        let old = t.instruction.clone();
11594
11595        let refreshed = resumed_instruction(&old, &t);
11596        assert!(refreshed.starts_with(&old), "the original text is kept");
11597        assert!(refreshed.contains("Which backend?"));
11598        assert!(refreshed.contains("SQLite"));
11599    }
11600
11601    #[test]
11602    fn resumed_instruction_keeps_an_original_answers_heading() {
11603        let mut t = task();
11604        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11605        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11606
11607        let refreshed = resumed_instruction(&t.instruction, &t);
11608
11609        assert!(
11610            refreshed.starts_with(&t.instruction),
11611            "an answers heading in the original instruction is not the appended block"
11612        );
11613        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11614        assert!(refreshed.contains("Which backend?"));
11615        assert!(refreshed.contains("SQLite"));
11616
11617        let repeated = resumed_instruction(&refreshed, &t);
11618        assert_eq!(
11619            repeated, refreshed,
11620            "only the final appended block is refreshed"
11621        );
11622    }
11623
11624    #[test]
11625    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11626        let mut t = task();
11627        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11628
11629        // A first resume appends the block; a second resume of the same run,
11630        // with no new answer in between, must reproduce exactly the same
11631        // text rather than appending the block a second time.
11632        let once = resumed_instruction(&t.instruction, &t);
11633        let twice = resumed_instruction(&once, &t);
11634        assert_eq!(once, twice);
11635        assert_eq!(once.matches("Which backend?").count(), 1);
11636
11637        // A later answer replaces the block wholesale rather than growing it.
11638        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11639        let refreshed = resumed_instruction(&once, &t);
11640        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11641        assert!(refreshed.contains("Which backend?"));
11642        assert!(refreshed.contains("Which cache?"));
11643    }
11644
11645    #[test]
11646    fn prepare_instruction_covers_all_three_starters() {
11647        let mut t = task();
11648        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11649
11650        // Start: a fresh run gets the task text plus every answer so far —
11651        // exactly `instruction_for`.
11652        assert_eq!(
11653            prepare_instruction(&Starter::Start, None, &t),
11654            Some(instruction_for(&t))
11655        );
11656
11657        // Resume: the run's prior instruction is refreshed with the answer,
11658        // not discarded and not left stale.
11659        let old = t.instruction.clone();
11660        assert_eq!(
11661            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11662            Some(resumed_instruction(&old, &t))
11663        );
11664
11665        // Review: a review-only pass builds its own instruction from the
11666        // branch's history in `crate::graph`, with no task statement at all -
11667        // this boundary must leave it alone.
11668        assert_eq!(
11669            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11670            None
11671        );
11672    }
11673
11674    #[test]
11675    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11676        assert_eq!(
11677            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11678            Starter::Review("magi/eba2/A".to_owned())
11679        );
11680    }
11681
11682    #[test]
11683    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11684        assert_eq!(
11685            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11686            Starter::Start,
11687            "a vanished review branch must not fall back to resuming the old run either"
11688        );
11689    }
11690
11691    #[test]
11692    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11693        let mut t = task();
11694        t.start("old-run".to_owned());
11695        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11696        t.release();
11697        let branch = t.review_branch.take();
11698        assert_eq!(
11699            choose_starter(branch.as_deref(), true, Some("old-run")),
11700            Starter::Review("magi/eba2/A".to_owned()),
11701            "a review wins over resuming the old run"
11702        );
11703    }
11704
11705    #[test]
11706    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11707        assert_eq!(
11708            choose_starter(None, false, Some("some-run")),
11709            Starter::Resume("some-run".to_owned())
11710        );
11711        assert_eq!(choose_starter(None, false, None), Starter::Start);
11712    }
11713
11714    #[test]
11715    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11716        let mut released = task();
11717        released.start("stalled-run".to_owned());
11718        released.requeue();
11719        let unfinished = (!released.fresh_start)
11720            .then(|| Some("stalled-run".to_owned()))
11721            .flatten();
11722        assert_eq!(
11723            choose_starter(None, false, unfinished.as_deref()),
11724            Starter::Start,
11725            "release keeps run history but must not resume it"
11726        );
11727        assert_eq!(released.runs, ["stalled-run"]);
11728    }
11729
11730    fn stopped_public_run(status: RunStatus) -> RunState {
11731        let mut state = run_state(status);
11732        state.driver_exited = true;
11733        state.config.graph.land = true;
11734        state.config.graph.review_rounds = 1;
11735        state.reviews = vec![review_round(1)];
11736        state.merge = Some(crate::run::MergeOutcome {
11737            mode: MergeMode::Pr,
11738            ok: false,
11739            detail: "landing stopped".into(),
11740            empty: false,
11741        });
11742        state.pr = Some(crate::run::PrRecord {
11743            url: "https://example.test/pull/1".into(),
11744            number: 1,
11745            state: "open".into(),
11746            checks: "red".into(),
11747            round: 1,
11748            rounds: 1,
11749            red_at_merge: Vec::new(),
11750        });
11751        state
11752    }
11753
11754    #[test]
11755    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11756        for status in [RunStatus::Blocked, RunStatus::Gating] {
11757            let home = tempfile::tempdir().unwrap();
11758            let mut state = stopped_public_run(status);
11759            state.save_under(home.path()).unwrap();
11760            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11761            assert!(!exhausted_review_budget(&state));
11762            let mut task = held_task_with(&state.id);
11763            task.release();
11764            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11765            assert_eq!(
11766                choose_starter(None, false, unfinished.as_deref()),
11767                Starter::Resume(state.id.clone())
11768            );
11769            let question = action_question(&state.id, resume_action(&state.id));
11770            assert_eq!(
11771                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11772                    state.clone()
11773                )),
11774                ActionDecision::Resume(state.id.clone())
11775            );
11776            // The control-plane command uses this same preflight before pinning.
11777            assert_eq!(
11778                crate::resume::validate(home.path(), &state.id).unwrap().id,
11779                state.id
11780            );
11781            let queue = Queue::at(home.path().join("queue"));
11782            let mut controlled = Task::new(
11783                "resume land".into(),
11784                state.instruction.clone(),
11785                state.repo.clone(),
11786                Source::Agent {
11787                    run: "talk".into(),
11788                    node: crate::queue::CHAT_NODE.into(),
11789                },
11790            );
11791            controlled.runs.push(state.id.clone());
11792            controlled.hold_machine(Some("land stopped".into()));
11793            queue.put(&mut controlled).unwrap();
11794            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11795            assert_eq!(resumed.status, TaskStatus::Queued);
11796            assert_eq!(
11797                resumed.resume_override.unwrap().pinned_run,
11798                Some(state.id.clone())
11799            );
11800            assert_eq!(resumed.attempts, 0);
11801        }
11802    }
11803
11804    #[test]
11805    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
11806        for review_rounds in [0, 1] {
11807            let home = tempfile::tempdir().unwrap();
11808            let mut state = run_state(RunStatus::Blocked);
11809            state.config.graph.review_rounds = review_rounds;
11810            if review_rounds > 0 {
11811                let mut review = review_round(1);
11812                review.clean = true;
11813                state.reviews = vec![review];
11814            }
11815            state.gate_ran = true;
11816            state.gate = vec![crate::run::CommandOutcome {
11817                command: "verify".into(),
11818                code: Some(1),
11819                output_tail: "gate failed after repair budget exhausted".into(),
11820                duration_ms: 0,
11821                resource_blocked: false,
11822            }];
11823            state.save_under(home.path()).unwrap();
11824            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11825            assert!(exhausted_review_budget(&state));
11826            let mut task = held_task_with(&state.id);
11827            task.release();
11828            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
11829            let question = action_question(&state.id, resume_action(&state.id));
11830            assert_ne!(
11831                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11832                    state.clone()
11833                )),
11834                ActionDecision::Resume(state.id.clone())
11835            );
11836            let error = crate::resume::validate(home.path(), &state.id)
11837                .unwrap_err()
11838                .to_string();
11839            assert!(!error.contains("review budget exhausted"), "{error}");
11840            assert!(
11841                error.contains(if review_rounds == 0 {
11842                    "review is disabled"
11843                } else {
11844                    "gate already ran"
11845                }),
11846                "{error}"
11847            );
11848
11849            // An unexecuted gate still has work to do with or without reviews.
11850            state.gate_ran = false;
11851            state.gate.clear();
11852            assert!(!exhausted_review_budget(&state));
11853            assert_eq!(
11854                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
11855                Some(state.id)
11856            );
11857        }
11858    }
11859
11860    #[test]
11861    fn resource_blocked_verification_resumes_the_same_run() {
11862        for (kind, stage) in [
11863            ("cache", "clean"),
11864            ("coordination", "clean"),
11865            ("cache", "review-e2e"),
11866            ("coordination", "no-reviews"),
11867            ("coordination", "handoff"),
11868        ] {
11869            let home = tempfile::tempdir().unwrap();
11870            let mut state = run_state(RunStatus::Blocked);
11871            state.config.graph.review_rounds = 1;
11872            let mut review = review_round(1);
11873            review.clean = true;
11874            state.reviews = vec![review];
11875            if stage == "review-e2e" {
11876                let review = &mut state.reviews[0];
11877                review.clean = false;
11878                review.blocking = 1;
11879                review.e2e = vec![crate::run::CommandOutcome {
11880                    command: "verify".into(),
11881                    code: None,
11882                    output_tail: "resource wait expired".into(),
11883                    duration_ms: 0,
11884                    resource_blocked: true,
11885                }];
11886            } else if stage == "no-reviews" {
11887                state.config.graph.review_rounds = 0;
11888                state.reviews.clear();
11889            } else if stage == "handoff" {
11890                // A completed final verification can hand off to the gate
11891                // even when the review still carries contested findings.
11892                let review = &mut state.reviews[0];
11893                review.clean = false;
11894                review.blocking = 1;
11895                review.e2e = vec![crate::run::CommandOutcome {
11896                    command: "verify".into(),
11897                    code: Some(0),
11898                    output_tail: String::new(),
11899                    duration_ms: 0,
11900                    resource_blocked: false,
11901                }];
11902            }
11903            state.gate_ran = false;
11904            state.resource_block = Some(crate::run::ResourceBlock {
11905                cause: crate::run::ResourceBlockCause::Other,
11906                node: if stage == "review-e2e" {
11907                    "review"
11908                } else {
11909                    "gate"
11910                }
11911                .into(),
11912                kind: kind.into(),
11913                detail: "resource wait expired".into(),
11914                at: jiff::Timestamp::now(),
11915            });
11916            state.save_under(home.path()).unwrap();
11917            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11918            assert!(!exhausted_review_budget(&state));
11919            let mut task = held_task_with(&state.id);
11920            task.release();
11921            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11922            assert_eq!(
11923                choose_starter(None, false, unfinished.as_deref()),
11924                Starter::Resume(state.id.clone())
11925            );
11926            let question = action_question(&state.id, resume_action(&state.id));
11927            assert_eq!(
11928                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
11929                    state.clone()
11930                )),
11931                ActionDecision::Resume(state.id.clone())
11932            );
11933            assert_eq!(
11934                crate::resume::validate(home.path(), &state.id).unwrap().id,
11935                state.id
11936            );
11937            let queue = Queue::at(home.path().join("queue"));
11938            let mut controlled = Task::new(
11939                "resume verification".into(),
11940                state.instruction.clone(),
11941                state.repo.clone(),
11942                Source::Agent {
11943                    run: "talk".into(),
11944                    node: crate::queue::CHAT_NODE.into(),
11945                },
11946            );
11947            controlled.runs.push(state.id.clone());
11948            controlled.hold_machine(Some("verification resource unavailable".into()));
11949            queue.put(&mut controlled).unwrap();
11950            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
11951            assert_eq!(resumed.status, TaskStatus::Queued);
11952            assert_eq!(
11953                resumed.resume_override.unwrap().pinned_run,
11954                Some(state.id.clone())
11955            );
11956            assert_eq!(resumed.attempts, 0);
11957
11958            // A genuinely unresolved final review still exhausts the budget.
11959            state.config.graph.review_rounds = 1;
11960            let mut unresolved = review_round(1);
11961            unresolved.blocking = 1;
11962            state.reviews = vec![unresolved];
11963            state.resource_block = None;
11964            state.save_under(home.path()).unwrap();
11965            assert!(exhausted_review_budget(&state));
11966            assert!(crate::resume::validate(home.path(), &state.id).is_err());
11967        }
11968    }
11969
11970    #[tokio::test]
11971    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
11972        if !crate::standalone_test(
11973            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
11974        ) {
11975            return;
11976        }
11977        let home = tempfile::tempdir().unwrap();
11978        let mut owner = stopped_public_run(RunStatus::Blocked);
11979        owner.save_under(home.path()).unwrap();
11980        let history = vec![owner.id.clone()];
11981        let repo = owner.repo.clone();
11982        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
11983        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
11984        let initial =
11985            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
11986        assert!(
11987            initial.is_pending(),
11988            "a busy record must not hold or resume the task"
11989        );
11990        owner.retired_to = Some("20260101-000001-bbbb".into());
11991        owner.save_under(home.path()).unwrap();
11992        drop(lock);
11993        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
11994            .await
11995            .expect("ownership lock released")
11996            .expect("read settled owner");
11997        assert!(
11998            result.is_none(),
11999            "the retired owner must not be resumed from a stale read"
12000        );
12001    }
12002
12003    #[tokio::test]
12004    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
12005        if !crate::standalone_test(
12006            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
12007        ) {
12008            return;
12009        }
12010        let home = tempfile::tempdir().unwrap();
12011        let mut owner = stopped_public_run(RunStatus::Blocked);
12012        let repo = tempfile::tempdir().unwrap();
12013        crate::git::git(repo.path(), &["init"]).await.unwrap();
12014        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
12015        owner.id = "20260101-000000-aaaa".into();
12016        owner.save_under(home.path()).unwrap();
12017        let mut successor = run_state(RunStatus::Blocked);
12018        successor.id = "20260101-000001-bbbb".into();
12019        successor.save_under(home.path()).unwrap();
12020        let runs = vec![owner.id.clone(), successor.id.clone()];
12021        assert_eq!(
12022            public_resume_owner(home.path(), &runs, &owner.repo)
12023                .await
12024                .unwrap()
12025                .unwrap()
12026                .id,
12027            owner.id
12028        );
12029        let subdir = owner.repo.join("nested");
12030        std::fs::create_dir(&subdir).unwrap();
12031        assert_eq!(
12032            public_resume_owner(home.path(), &runs, &subdir)
12033                .await
12034                .unwrap()
12035                .unwrap()
12036                .id,
12037            owner.id
12038        );
12039        #[cfg(unix)]
12040        {
12041            let alias = home.path().join("repo-alias");
12042            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
12043            assert_eq!(
12044                public_resume_owner(home.path(), &runs, &alias.join("nested"))
12045                    .await
12046                    .unwrap()
12047                    .unwrap()
12048                    .id,
12049                owner.id
12050            );
12051        }
12052        let different = tempfile::tempdir().unwrap();
12053        crate::git::git(different.path(), &["init"]).await.unwrap();
12054        assert!(
12055            public_resume_owner(home.path(), &runs, different.path())
12056                .await
12057                .is_err()
12058        );
12059        std::fs::remove_file(
12060            home.path()
12061                .join("runs")
12062                .join(&successor.id)
12063                .join("run.json"),
12064        )
12065        .unwrap();
12066        assert!(
12067            public_resume_owner(home.path(), &runs, &owner.repo)
12068                .await
12069                .is_err()
12070        );
12071    }
12072
12073    #[test]
12074    fn an_ordinary_release_keeps_a_resumable_run_available() {
12075        let mut released = task();
12076        released.start("stalled-run".to_owned());
12077        released.release();
12078        let unfinished = (!released.fresh_start)
12079            .then(|| Some("stalled-run".to_owned()))
12080            .flatten();
12081        assert_eq!(
12082            choose_starter(None, false, unfinished.as_deref()),
12083            Starter::Resume("stalled-run".to_owned()),
12084            "manual release must preserve the normal resume path"
12085        );
12086    }
12087
12088    #[test]
12089    fn resume_refusals_explain_admission_without_changing_task_or_run() {
12090        use crate::handover::{ResumeRefusal, resume_refusal_under};
12091        let home = tempfile::tempdir().unwrap();
12092        let mut exhausted = run_state(RunStatus::Blocked);
12093        exhausted.driver_exited = true;
12094        exhausted.config.graph.review_rounds = 3;
12095        exhausted.reviews = (1..=3).map(review_round).collect();
12096        for refusal in [
12097            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
12098            ResumeRefusal::Status(RunStatus::Ready),
12099            ResumeRefusal::Released("20261022-000000-aaaa".into()),
12100            ResumeRefusal::Retired("retirement-successor".into()),
12101            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
12102        ] {
12103            let mut state = exhausted.clone();
12104            let expected = match refusal {
12105                ResumeRefusal::Status(_) => {
12106                    state.status = RunStatus::Ready;
12107                    "status `ready`"
12108                }
12109                ResumeRefusal::Released(ref target) => {
12110                    state.released_to = Some(target.clone());
12111                    "execution was released"
12112                }
12113                ResumeRefusal::Retired(ref target) => {
12114                    state.retired_to = Some(target.clone());
12115                    "execution was retired"
12116                }
12117                ResumeRefusal::OwnershipTransferred(ref target) => {
12118                    state.pr_taken_over_by = Some(target.clone());
12119                    "PR ownership was transferred"
12120                }
12121                _ => "review budget exhausted (3/3 rounds used)",
12122            };
12123            assert_eq!(
12124                resume_refusal_under(&state, Some(home.path())),
12125                Some(refusal.clone())
12126            );
12127            assert_eq!(
12128                refusal.successor(),
12129                state
12130                    .released_to
12131                    .as_deref()
12132                    .or(state.retired_to.as_deref())
12133                    .or(state.pr_taken_over_by.as_deref())
12134            );
12135            state.save_under(home.path()).unwrap();
12136            let queue = Queue::at(home.path().join("queue"));
12137            let mut task = Task::new(
12138                "retained implementation".into(),
12139                state.instruction.clone(),
12140                state.repo.clone(),
12141                Source::Agent {
12142                    run: "talk".into(),
12143                    node: crate::queue::CHAT_NODE.into(),
12144                },
12145            );
12146            task.runs.push(state.id.clone());
12147            task.hold_machine(Some("stopped".into()));
12148            queue.put(&mut task).unwrap();
12149            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
12150            let before_run = serde_json::to_value(&state).unwrap();
12151            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
12152                .unwrap_err()
12153                .to_string();
12154            assert!(error.contains(expected), "{error}");
12155            assert!(!error.contains("only a stalled or blocked"), "{error}");
12156            if matches!(refusal, ResumeRefusal::Status(_)) {
12157                assert!(
12158                    error.contains("is final; there is nothing left to resume"),
12159                    "{error}"
12160                );
12161            }
12162            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
12163                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
12164                assert!(error.contains("review-only successor with a new review budget"));
12165                assert!(error.contains("does not resume this run"));
12166            }
12167            for target in [
12168                &state.released_to,
12169                &state.retired_to,
12170                &state.pr_taken_over_by,
12171            ]
12172            .into_iter()
12173            .flatten()
12174            {
12175                let short = if state.retired_to.as_ref() == Some(target) {
12176                    target.as_str()
12177                } else {
12178                    crate::run::short_of(target)
12179                };
12180                assert!(
12181                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
12182                    "{error}"
12183                );
12184                if short != target {
12185                    assert!(!error.contains(target), "full successor id leaked: {error}");
12186                }
12187            }
12188            assert_eq!(
12189                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12190                before_task
12191            );
12192            assert_eq!(
12193                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12194                    .unwrap(),
12195                before_run
12196            );
12197            let question = action_question(&state.id, resume_action(&state.id));
12198            for phrases in [&PHRASES_EN, &PHRASES_JA] {
12199                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
12200                    RunState::load_under(id, home.path())
12201                });
12202                let ActionDecision::Refuse(detail) = decision else {
12203                    panic!(
12204                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
12205                        state.id,
12206                        home.path().display()
12207                    );
12208                };
12209                assert!(detail.contains(expected), "{detail}");
12210            }
12211        }
12212        // Preserve predicate ordering, while keeping every recorded destination visible.
12213        exhausted.status = RunStatus::Ready;
12214        exhausted.released_to = Some("released".into());
12215        exhausted.retired_to = Some("retired".into());
12216        exhausted.pr_taken_over_by = Some("owner".into());
12217        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12218        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12219        let detail = reason.diagnostic(&exhausted);
12220        for target in ["released", "retired", "owner"] {
12221            assert!(detail.contains(&format!("magi show {target}")));
12222        }
12223    }
12224
12225    #[test]
12226    fn resume_action_ignores_question_checkpoints_in_another_home() {
12227        crate::run::pin_test_home();
12228        let home = tempfile::tempdir().unwrap();
12229        let mut state = run_state(RunStatus::Blocked);
12230        // The private directory reserves this fixture's identity even while
12231        // other tests write questions into the process-wide store.
12232        state.id = format!(
12233            "resume-context-{}",
12234            home.path().file_name().unwrap().to_str().unwrap()
12235        );
12236        state.driver_exited = true;
12237        state.config.graph.review_rounds = 1;
12238        state.reviews = vec![review_round(1)];
12239        state.save_under(home.path()).unwrap();
12240        let task = held_task_with(&state.id);
12241        let answer = action_question(&state.id, resume_action(&state.id));
12242        let mut checkpoint = approval_question(&state.id);
12243        let foreign = Questions::open();
12244        foreign.put(&mut checkpoint).unwrap();
12245        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
12246        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12247            RunState::load_under(id, home.path())
12248        });
12249        let matching: Vec<_> = foreign
12250            .list()
12251            .into_iter()
12252            .filter(|q| q.run == state.id && q.status.open())
12253            .collect();
12254        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
12255        assert!(
12256            matches!(decision, ActionDecision::Refuse(_)),
12257            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
12258            state.id,
12259            home.path().display(),
12260            crate::run::test_home().display()
12261        );
12262        assert_eq!(
12263            refusal,
12264            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
12265        );
12266        let local = Questions::at(home.path().join("questions"));
12267        for status in [
12268            ask::QuestionStatus::Open,
12269            ask::QuestionStatus::Answered,
12270            ask::QuestionStatus::Abandoned,
12271        ] {
12272            let mut question = checkpoint.clone();
12273            match status {
12274                ask::QuestionStatus::Open => {}
12275                ask::QuestionStatus::Answered => {
12276                    question
12277                        .answer(ask::Answer::Choice(question.choices[0].clone()))
12278                        .unwrap();
12279                }
12280                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
12281            }
12282            local.put(&mut question).unwrap();
12283            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12284                RunState::load_under(id, home.path())
12285            });
12286            if status.open() {
12287                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
12288            } else {
12289                assert!(
12290                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
12291                    "status={status:?}, decision={decision:?}"
12292                );
12293            }
12294        }
12295    }
12296
12297    #[test]
12298    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
12299        let home = tempfile::tempdir().unwrap();
12300        let mut state = run_state(RunStatus::Stalled);
12301        state.id = format!(
12302            "resume-driver-{}",
12303            home.path().file_name().unwrap().to_str().unwrap()
12304        );
12305        state.driver_claimed = Some(false);
12306        state.save_under(home.path()).unwrap();
12307        let task = held_task_with(&state.id);
12308        let question = action_question(&state.id, resume_action(&state.id));
12309        let decide = || {
12310            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
12311                RunState::load_under(id, home.path())
12312            })
12313        };
12314        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
12315        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
12316        assert_eq!(
12317            decide(),
12318            ActionDecision::Refuse("run already has a live driver".into())
12319        );
12320        drop(lease);
12321        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
12322    }
12323
12324    #[test]
12325    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12326        let home = tempfile::tempdir().unwrap();
12327        let mut state = run_state(RunStatus::Blocked);
12328        state.driver_exited = true;
12329        state.config.graph.review_rounds = 1;
12330        state.reviews = vec![review_round(1)];
12331        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12332        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12333            let mut saved = state.clone();
12334            match checkpoint {
12335                "publication" => saved.pr_publication_pending = true,
12336                "approval" => {
12337                    saved.land_approval = Some(crate::run::LandApproval {
12338                        question: "approval".into(),
12339                        head: "head".into(),
12340                    })
12341                }
12342                "armed" => saved.land_armed_head = Some("head".into()),
12343                "landing" => saved.status = RunStatus::Landing,
12344                _ => {
12345                    let mut question = ask::Question::new(
12346                        saved.id.clone(),
12347                        "review".into(),
12348                        "review-1".into(),
12349                        "continue?".into(),
12350                        String::new(),
12351                        vec!["continue".into()],
12352                    );
12353                    ask::Questions::at(home.path().join("questions"))
12354                        .put(&mut question)
12355                        .unwrap();
12356                }
12357            }
12358            saved.save_under(home.path()).unwrap();
12359            assert!(
12360                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12361                "{checkpoint}"
12362            );
12363            assert!(
12364                crate::resume::validate(home.path(), &saved.id).is_ok(),
12365                "{checkpoint}"
12366            );
12367        }
12368    }
12369
12370    #[test]
12371    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12372        let mut state = run_state(RunStatus::Blocked);
12373        state.config.graph.review_rounds = 3;
12374        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12375        assert!(exhausted_review_budget(&state));
12376
12377        // One round still unused: resuming can still ask a reviewer something.
12378        state.reviews.pop();
12379        assert!(!exhausted_review_budget(&state));
12380
12381        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
12382        // count: only a `Blocked` run re-enters the review loop on resume.
12383        let mut stalled = run_state(RunStatus::Stalled);
12384        stalled.config.graph.review_rounds = 1;
12385        stalled.reviews = vec![review_round(1)];
12386        assert!(!exhausted_review_budget(&stalled));
12387    }
12388
12389    fn review_round(round: usize) -> crate::run::ReviewRound {
12390        crate::run::ReviewRound {
12391            round,
12392            head: "deadbeef".to_owned(),
12393            verified_head: None,
12394            verified_at: None,
12395            reviews: Vec::new(),
12396            e2e: Vec::new(),
12397            verify_retried: false,
12398            e2e_deferred: false,
12399            e2e_defer_reason: None,
12400            fix: None,
12401            blocking: 0,
12402            answered: 1,
12403            expected: 1,
12404            clean: false,
12405            progressed: true,
12406            vote_split: false,
12407            reconsideration: Vec::new(),
12408            verdict: None,
12409        }
12410    }
12411
12412    #[test]
12413    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12414        let mut run = RunState::new(
12415            PathBuf::from("/repo"),
12416            "main".to_owned(),
12417            "abc1234def".to_owned(),
12418            "add retries".to_owned(),
12419            Config::default(),
12420        );
12421        run.status = RunStatus::Judging;
12422        run.parked = true;
12423        let mut task = Task::new(
12424            "add retries".to_owned(),
12425            "add retries".to_owned(),
12426            PathBuf::from("/repo"),
12427            crate::queue::Source::Human,
12428        );
12429        task.status = TaskStatus::Failed;
12430        task.runs = vec![run.id.clone()];
12431        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12432        assert!(with(&task, &run), "parked after judging is the case");
12433        let mut parked_task = task.clone();
12434        parked_task.status = TaskStatus::Parked;
12435        assert!(with(&parked_task, &run), "the Parked status is the case");
12436
12437        let mut not_parked = run.clone();
12438        not_parked.parked = false;
12439        not_parked.status = RunStatus::Stalled;
12440        assert!(!with(&task, &not_parked), "a stall is the conductor's");
12441
12442        let mut fresh = task.clone();
12443        fresh.fresh_start = true;
12444        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12445
12446        let mut review = task.clone();
12447        review.review_branch = Some("magi/x/A".to_owned());
12448        assert!(!with(&review, &run), "review is ranked before resume");
12449
12450        let mut held = task.clone();
12451        held.status = TaskStatus::Held;
12452        assert!(!with(&held, &run), "a hold stays visible to the conductor");
12453
12454        let mut released = run.clone();
12455        released.released_to = Some("20260901-000000-new1".to_owned());
12456        assert!(!with(&task, &released), "nothing left to resume into");
12457
12458        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
12459            "unreadable"
12460        )));
12461    }
12462
12463    #[test]
12464    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
12465        let mut released = RunState::new(
12466            PathBuf::from("/repo"),
12467            "main".to_owned(),
12468            "abc1234def".to_owned(),
12469            "add retries".to_owned(),
12470            Config::default(),
12471        );
12472        released.status = RunStatus::Blocked;
12473        assert_eq!(
12474            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12475            Some(released.id.clone())
12476        );
12477        released.released_to = Some("20260901-000000-new1".to_owned());
12478        assert_eq!(
12479            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
12480            None,
12481            "there is nothing left to resume it into"
12482        );
12483    }
12484
12485    #[test]
12486    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
12487        // Mirrors the failure this exists to close: a task's last run ended
12488        // `Blocked` with the review budget spent, `crate::conduct` chose
12489        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
12490        // evidence), and without this check `attempt` would go on treating
12491        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
12492        // review loop iterates zero times over an already-spent budget, so
12493        // the resumed run settles right back to `Blocked` having asked nobody
12494        // anything, and `Requeue`'s promised fresh competition never happens.
12495        let mut exhausted = RunState::new(
12496            PathBuf::from("/repo"),
12497            "main".to_owned(),
12498            "abc1234def".to_owned(),
12499            "add retries".to_owned(),
12500            Config::default(),
12501        );
12502        exhausted.status = RunStatus::Blocked;
12503        exhausted.config.graph.review_rounds = 1;
12504        exhausted.reviews = vec![review_round(1)];
12505
12506        assert_eq!(
12507            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
12508            None,
12509            "an exhausted `Blocked` run must not be offered as resumable"
12510        );
12511
12512        // A `Blocked` run with rounds still unused is genuinely worth
12513        // resuming, and must still be found.
12514        let mut has_budget_left = RunState::new(
12515            PathBuf::from("/repo"),
12516            "main".to_owned(),
12517            "abc1234def".to_owned(),
12518            "add retries".to_owned(),
12519            Config::default(),
12520        );
12521        has_budget_left.status = RunStatus::Blocked;
12522        has_budget_left.config.graph.review_rounds = 3;
12523        has_budget_left.reviews = vec![review_round(1)];
12524
12525        assert_eq!(
12526            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
12527                Ok(has_budget_left.clone())
12528            }),
12529            Some(has_budget_left.id.clone())
12530        );
12531    }
12532
12533    #[test]
12534    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
12535        let mut run = RunState::new(
12536            PathBuf::from("/repo"),
12537            "main".to_owned(),
12538            "abc1234def".to_owned(),
12539            "add retries".to_owned(),
12540            Config::default(),
12541        );
12542        run.status = RunStatus::Blocked;
12543        run.config.graph.review_rounds = 1;
12544        run.reviews = vec![review_round(1)];
12545        run.pr_publication_pending = true;
12546        assert_eq!(
12547            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
12548            Some(run.id.clone()),
12549            "a spent review budget must not turn a failed publication into a re-competition"
12550        );
12551    }
12552
12553    #[test]
12554    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
12555        let mut task = Task::new(
12556            "recover work".into(),
12557            "recover work".into(),
12558            PathBuf::from("/repo"),
12559            crate::queue::Source::Human,
12560        );
12561        let mut history = std::collections::BTreeMap::new();
12562        for index in 0..8 {
12563            let mut run = run_state(RunStatus::Blocked);
12564            run.id = format!("20260101-000000-{index:04}");
12565            run.base_commit = format!("upstream-{index}");
12566            // Seven empty newer attempts must not erase the old recovery owner.
12567            if index > 0 {
12568                run.candidates.clear();
12569            }
12570            task.runs.extend([run.id.clone(), run.id.clone()]);
12571            history.insert(run.id.clone(), run);
12572            task.requeue();
12573        }
12574        let check = |task: &Task, starter: &Starter, limit| {
12575            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12576        };
12577        assert!(
12578            check(&task, &Starter::Start, 8)
12579                .unwrap()
12580                .contains("8 unretired")
12581        );
12582        assert!(check(&task, &Starter::Start, 9).is_none());
12583        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12584        task.release_operator("owner", None);
12585        assert_eq!(task.attempts, 0);
12586        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12587        assert!(check(&restored, &Starter::Start, 8).is_some());
12588        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12589        assert!(check(&restored, &Starter::Start, 0).is_none());
12590    }
12591
12592    #[test]
12593    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
12594        let tmp = tempfile::tempdir().unwrap();
12595        let mut task = Task::new(
12596            "recover selected PR".into(),
12597            "preserve implementation".into(),
12598            tmp.path().join("repo"),
12599            crate::queue::Source::Human,
12600        );
12601        let mut failed = run_state(RunStatus::Failed);
12602        failed.id = "20260101-000000-fail".into();
12603        failed.candidates.clear();
12604        failed.prep_complete = Some(false);
12605        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
12606        failed.startup = Some(crate::run::Startup {
12607            kind: "pr-recovery".into(),
12608            branch: Some("selected-public-head".into()),
12609            stage: "worktree-setup".into(),
12610            complete: false,
12611            failure: Some("setup modified a tracked file and failed".into()),
12612        });
12613        // Setup may fail before a candidate is recorded; its dirty worktree
12614        // still needs protection and consumes the independent retained bound.
12615        let worktree = failed.worktree_root().join("under-review");
12616        std::fs::create_dir_all(&worktree).unwrap();
12617        let retained_edit = worktree.join("implementation");
12618        std::fs::write(&retained_edit, "retained setup edit").unwrap();
12619        task.record_startup_failure(crate::run::StartupFailure {
12620            run: failed.id.clone(),
12621            stage: "worktree-setup".into(),
12622        });
12623        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12624        assert!(task.runs.is_empty() && task.passes.is_empty());
12625        assert_eq!(task.attempts, 0);
12626        let starter = Starter::Review("selected-public-head".into());
12627        assert!(
12628            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
12629                .unwrap()
12630                .contains("1 unretired")
12631        );
12632        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
12633        assert!(
12634            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
12635                .unwrap()
12636                .contains("Cannot verify")
12637        );
12638        // Older or mixed writers can link the same reservation in both lists.
12639        let mut mixed = task.clone();
12640        mixed.runs.push(failed.id.clone());
12641        mixed
12642            .startup_failures
12643            .push(task.startup_failures[0].clone());
12644        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
12645        failed.retired_to = Some("verified-recovery-owner".into());
12646        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
12647        assert!(
12648            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
12649                panic!("resuming the existing owner must not allocate a new attempt")
12650            })
12651            .is_none()
12652        );
12653        assert_eq!(
12654            std::fs::read_to_string(retained_edit).unwrap(),
12655            "retained setup edit"
12656        );
12657        assert!(task.runs.is_empty() && task.passes.is_empty());
12658        assert_eq!(task.attempts, 0);
12659    }
12660
12661    #[test]
12662    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12663        let mut task = Task::new(
12664            "recover work".into(),
12665            "recover work".into(),
12666            PathBuf::from("/repo"),
12667            crate::queue::Source::Human,
12668        );
12669        let mut run = run_state(RunStatus::Superseded);
12670        run.candidates.clear();
12671        task.runs.push(run.id.clone());
12672        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12673        run.retired_to = Some("authority".into());
12674        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12675        run.retired_to = None;
12676        run.released_to = Some("authority".into());
12677        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12678        assert!(
12679            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12680                .unwrap()
12681                .contains("Cannot verify")
12682        );
12683        // Resuming an existing owner needs no new inventory or worktree budget.
12684        assert!(
12685            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12686                panic!("resume must not load historical attempts")
12687            })
12688            .is_none()
12689        );
12690    }
12691
12692    #[test]
12693    fn retired_resume_requires_a_valid_same_repository_authority() {
12694        let mut source = run_state(RunStatus::Blocked);
12695        let mut empty = run_state(RunStatus::Blocked);
12696        empty.retired_to = Some(source.id.clone());
12697        let runs = vec![source.id.clone(), empty.id.clone()];
12698        let resolve = |source: &RunState, empty: &RunState| {
12699            unfinished_run_with(&runs, "fixture", |id| {
12700                if id == source.id {
12701                    Ok(source.clone())
12702                } else if id == empty.id {
12703                    Ok(empty.clone())
12704                } else {
12705                    bail!("unreadable authority")
12706                }
12707            })
12708        };
12709        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12710        assert_eq!(
12711            choose_starter(None, false, resolve(&source, &empty).as_deref()),
12712            Starter::Resume(source.id.clone())
12713        );
12714        source.retired_to = Some(empty.id.clone());
12715        assert!(
12716            resolve(&source, &empty).is_none(),
12717            "cycles do not revive obsolete runs"
12718        );
12719        source.retired_to = None;
12720        source.repo = PathBuf::from("/another-repository");
12721        assert!(resolve(&source, &empty).is_none());
12722        source.repo = empty.repo.clone();
12723        source.released_to = Some("later".into());
12724        assert!(resolve(&source, &empty).is_none());
12725        empty.retired_to = Some("unlisted-run".into());
12726        assert!(resolve(&source, &empty).is_none());
12727    }
12728
12729    #[test]
12730    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12731        // A task whose history holds an *older* run that still looks
12732        // resumable (say, a competition `Runner::review` was started
12733        // alongside after that older run went `Stalled`) and a *newest* run
12734        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
12735        // on this task must mean a fresh competition — falling back to the
12736        // stale, superseded `Stalled` run instead would resurrect history
12737        // nothing asked to revisit and silently defeat the requeue.
12738        let mut older_stalled = RunState::new(
12739            PathBuf::from("/repo"),
12740            "main".to_owned(),
12741            "abc1234def".to_owned(),
12742            "add retries".to_owned(),
12743            Config::default(),
12744        );
12745        older_stalled.status = RunStatus::Stalled;
12746
12747        let mut newest_exhausted = RunState::new(
12748            PathBuf::from("/repo"),
12749            "main".to_owned(),
12750            "abc1234def".to_owned(),
12751            "add retries".to_owned(),
12752            Config::default(),
12753        );
12754        newest_exhausted.status = RunStatus::Blocked;
12755        newest_exhausted.config.graph.review_rounds = 1;
12756        newest_exhausted.reviews = vec![review_round(1)];
12757
12758        assert_eq!(
12759            unfinished_run_with(
12760                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12761                "t",
12762                |_| Ok(newest_exhausted.clone())
12763            ),
12764            None,
12765            "the newest run is exhausted, so nothing here is worth resuming - \
12766             least of all the older, already-superseded run"
12767        );
12768    }
12769
12770    #[test]
12771    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12772        assert_eq!(
12773            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12774                Err(anyhow::anyhow!("fixture is absent"))
12775            }),
12776            None
12777        );
12778    }
12779
12780    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12781        let mut q = ask::Question::new(
12782            run.to_owned(),
12783            "implement".to_owned(),
12784            "impl-A".to_owned(),
12785            "continue?".to_owned(),
12786            String::new(),
12787            vec!["resume で続行する".to_owned(), "other".to_owned()],
12788        );
12789        q.actions.insert("resume で続行する".to_owned(), action);
12790        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12791            .unwrap();
12792        q
12793    }
12794
12795    fn held_task_with(run: &str) -> Task {
12796        let mut t = task();
12797        t.runs = vec![run.to_owned()];
12798        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
12799        t
12800    }
12801
12802    fn resume_action(run: &str) -> ask::ChoiceAction {
12803        ask::ChoiceAction::Resume { run: run.into() }
12804    }
12805
12806    #[test]
12807    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
12808        let home = crate::run::test_home();
12809        for parked in [false, true] {
12810            let mut t = task();
12811            t.start("A".into());
12812            t.start("B".into());
12813            assert_eq!(t.runs, vec!["A", "B"]);
12814            t.start("A".into());
12815            let mut resumed = run_state(RunStatus::Blocked);
12816            resumed.id = "A".into();
12817            resumed.parked = parked;
12818            resumed.driver_exited = true;
12819            t.hold_machine(Some("resumed run stopped".into()));
12820            let q = action_question("A", resume_action("A"));
12821            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12822            assert_eq!(
12823                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
12824                    assert_eq!(id, "A");
12825                    Ok(resumed.clone())
12826                }),
12827                ActionDecision::Resume("A".into())
12828            );
12829            assert_eq!(
12830                action_standing(&t, &action_question("B", resume_action("B"))),
12831                ActionStanding::Stale
12832            );
12833            t.release_operator("cli", None);
12834            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
12835                assert_eq!(id, "A");
12836                Ok(resumed.clone())
12837            });
12838            assert_eq!(
12839                choose_starter(None, false, unfinished.as_deref()),
12840                Starter::Resume("A".into())
12841            );
12842            assert_eq!(t.runs, vec!["B", "A"]);
12843        }
12844    }
12845
12846    #[test]
12847    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
12848        let home = crate::run::test_home();
12849        let mut state = crate::land::tests::repair_state(true, true);
12850        state.status = RunStatus::Landing;
12851        state.parked = true;
12852        state.driver_exited = true;
12853        let mut q = ask::Question::new(
12854            state.id.clone(),
12855            land::APPROVAL_NODE.into(),
12856            "land".into(),
12857            "Merge?".into(),
12858            String::new(),
12859            vec![land::APPROVE.into(), land::HOLD.into()],
12860        );
12861        q.id = state.id.clone();
12862        state.land_approval = Some(crate::run::LandApproval {
12863            question: q.id.clone(),
12864            head: "current-head".into(),
12865        });
12866        assert!(land::upgrade_repair_choice(&mut q, &state));
12867        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12868        let mut task = held_task_with(&state.id);
12869        task.status = TaskStatus::Parked;
12870        assert_eq!(
12871            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12872            ActionDecision::Resume(state.id.clone())
12873        );
12874        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12875        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
12876        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
12877        assert_eq!(
12878            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12879            ActionDecision::Resume(state.id.clone()),
12880            "a repair answer newer than the manual hold resumes the existing owner"
12881        );
12882        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12883        for answered_at in [q.answered_at, None] {
12884            let mut older = q.clone();
12885            older.answered_at = answered_at;
12886            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
12887                panic!("a later manual hold must prevent dispatch")
12888            });
12889            let ActionDecision::Refuse(reason) = refused else {
12890                panic!("expected an actionable refusal, got {refused:?}");
12891            };
12892            assert!(reason.contains("later operator decision"));
12893            assert!(reason.contains(&format!("magi task release {}", task.id)));
12894        }
12895        task.operator_decided_at = None;
12896        let mut superseded = state.clone();
12897        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
12898        assert_eq!(
12899            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
12900            ActionDecision::Stale
12901        );
12902        for case in 1..4 {
12903            let mut changed = state.clone();
12904            match case {
12905                1 => changed.status = RunStatus::Blocked,
12906                2 => changed.released_to = Some("new-owner".into()),
12907                _ => changed.land_approval.as_mut().unwrap().head.clear(),
12908            }
12909            assert!(matches!(
12910                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
12911                ActionDecision::Refuse(_)
12912            ));
12913        }
12914        assert!(matches!(
12915            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
12916                "missing owner"
12917            )),
12918            ActionDecision::Refuse(_)
12919        ));
12920        task.runs.push("replacement".into());
12921        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12922        assert_eq!(
12923            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
12924                "old owner must not load"
12925            )),
12926            ActionDecision::Stale
12927        );
12928    }
12929
12930    #[test]
12931    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
12932        let mut state = crate::land::tests::repair_state(true, true);
12933        state.status = RunStatus::Landing;
12934        state.parked = true;
12935        state.driver_exited = true;
12936        let mut q = ask::Question::new(
12937            state.id.clone(),
12938            land::APPROVAL_NODE.into(),
12939            "land".into(),
12940            "Merge?".into(),
12941            String::new(),
12942            vec![land::APPROVE.into(), land::HOLD.into()],
12943        );
12944        q.id = state.id.clone();
12945        state.land_approval = Some(crate::run::LandApproval {
12946            question: q.id.clone(),
12947            head: "current-head".into(),
12948        });
12949        state.save().unwrap();
12950        land::upgrade_repair_choice(&mut q, &state);
12951        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12952        Questions::open().put(&mut q).unwrap();
12953        let tmp = tempfile::tempdir().unwrap();
12954        let queue = Queue::at(tmp.path().join("queue"));
12955        let mut task = held_task_with(&state.id);
12956        task.status = TaskStatus::Parked;
12957        queue.put(&mut task).unwrap();
12958        let empty = Arc::new(tokio::sync::Semaphore::new(0));
12959        let free = Arc::new(tokio::sync::Semaphore::new(1));
12960        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
12961        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
12962        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
12963        assert!(claim.permit.is_some());
12964        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
12965        drop(claim);
12966        Questions::open()
12967            .update(&q.id, |q| {
12968                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
12969                Ok(())
12970            })
12971            .unwrap();
12972        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
12973        assert!(claim.permit.is_none());
12974        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
12975    }
12976
12977    #[test]
12978    fn decide_action_resumes_only_the_latest_resumable_run() {
12979        let home = crate::run::test_home();
12980        let t = held_task_with("r1");
12981        let q = action_question("r1", resume_action("r1"));
12982        let load = |s: RunState| move |_: &str| Ok(s);
12983        assert_eq!(
12984            decide_action(
12985                &home,
12986                &t,
12987                &q,
12988                &PHRASES_EN,
12989                load(run_state(RunStatus::Blocked))
12990            ),
12991            ActionDecision::Resume("r1".into())
12992        );
12993        // Not the latest run of the task.
12994        let q_other = action_question("r1", resume_action("r0"));
12995        assert!(matches!(
12996            decide_action(
12997                &home,
12998                &t,
12999                &q_other,
13000                &PHRASES_EN,
13001                load(run_state(RunStatus::Blocked))
13002            ),
13003            ActionDecision::Refuse(_)
13004        ));
13005        // A finished run cannot make progress.
13006        assert!(matches!(
13007            decide_action(
13008                &home,
13009                &t,
13010                &q,
13011                &PHRASES_EN,
13012                load(run_state(RunStatus::Ready))
13013            ),
13014            ActionDecision::Refuse(_)
13015        ));
13016        // A released one either.
13017        let mut released = run_state(RunStatus::Blocked);
13018        released.released_to = Some("elsewhere".into());
13019        assert!(matches!(
13020            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
13021            ActionDecision::Refuse(_)
13022        ));
13023        // Unreadable state is a refusal, never a fresh competition.
13024        assert!(matches!(
13025            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
13026            ActionDecision::Refuse(_)
13027        ));
13028    }
13029
13030    #[test]
13031    fn decide_action_ignores_a_question_about_an_earlier_run() {
13032        let home = crate::run::test_home();
13033        let mut t = held_task_with("r1");
13034        t.runs.push("r2".to_owned());
13035        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13036        assert_eq!(
13037            decide_action(
13038                &home,
13039                &t,
13040                &action_question("r1", ask::ChoiceAction::Done),
13041                &PHRASES_EN,
13042                never
13043            ),
13044            ActionDecision::Stale
13045        );
13046    }
13047
13048    #[test]
13049    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
13050        let home = crate::run::test_home();
13051        let mut t = held_task_with("r1");
13052        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13053        assert_eq!(
13054            decide_action(
13055                &home,
13056                &t,
13057                &action_question("r1", ask::ChoiceAction::Requeue),
13058                &PHRASES_EN,
13059                never
13060            ),
13061            ActionDecision::Requeue
13062        );
13063        let done_q = action_question("r1", ask::ChoiceAction::Done);
13064        assert_eq!(
13065            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13066            ActionDecision::Done
13067        );
13068        t.mark_action_applied(&done_q.id);
13069        assert_eq!(
13070            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13071            ActionDecision::Skip
13072        );
13073
13074        // A plain answer (no action for that label) does nothing.
13075        let mut plain = action_question("r1", ask::ChoiceAction::Done);
13076        plain.actions.clear();
13077        assert_eq!(
13078            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
13079            ActionDecision::Skip
13080        );
13081        // A running task is left alone.
13082        let mut running = held_task_with("r1");
13083        running.status = TaskStatus::Running;
13084        assert_eq!(
13085            decide_action(
13086                &home,
13087                &running,
13088                &action_question("r1", ask::ChoiceAction::Done),
13089                &PHRASES_EN,
13090                never
13091            ),
13092            ActionDecision::Skip
13093        );
13094    }
13095
13096    #[test]
13097    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
13098        crate::run::pin_test_home();
13099        for legacy in [false, true] {
13100            let dir = tempfile::tempdir().unwrap();
13101            let queue = Queue::at(dir.path().join("queue"));
13102            let questions = Questions::at(dir.path().join("questions"));
13103            let run = "20260101-000000-hold";
13104            let mut task = held_task_with(run);
13105            task.status = TaskStatus::Parked;
13106            let mut q = ask::Question::new(
13107                run.into(),
13108                land::APPROVAL_NODE.into(),
13109                "land".into(),
13110                "Repair?".into(),
13111                String::new(),
13112                vec![land::REPAIR.into()],
13113            );
13114            q.actions.insert(land::REPAIR.into(), resume_action(run));
13115            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13116            // Deterministically order the answer before the actual manual hold.
13117            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13118            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
13119            questions.put(&mut q).unwrap();
13120            task.hold_manual(Some("Keep this PR paused".into()));
13121            if legacy {
13122                task.hold_source = None;
13123            }
13124            queue.put(&mut task).unwrap();
13125
13126            apply_task_choice_actions(&queue, &questions, dir.path());
13127            let after = queue.get(&task.id).unwrap();
13128            assert!(after.operator_held());
13129            assert_eq!(after.hold_source, task.hold_source);
13130            assert_eq!(after.operator_decided_at, task.operator_decided_at);
13131            assert_eq!(after.runs, task.runs);
13132            assert_eq!(after.instruction, task.instruction);
13133            assert!(after.resume_override.is_none());
13134            assert!(after.action_applied(&q.id));
13135            let reason = after.hold_reason.as_deref().unwrap();
13136            assert!(reason.starts_with("Keep this PR paused"));
13137            assert!(reason.contains("later operator decision"));
13138            assert!(reason.contains(&format!("magi task release {}", task.id)));
13139
13140            for recovery in [
13141                crate::conduct::Recovery::Review,
13142                crate::conduct::Recovery::Requeue,
13143            ] {
13144                crate::conduct::apply(
13145                    &queue,
13146                    &questions,
13147                    &crate::conduct::Verdict {
13148                        decisions: vec![crate::conduct::Decision {
13149                            id: task.id.clone(),
13150                            recovery: Some(recovery),
13151                            ..Default::default()
13152                        }],
13153                    },
13154                )
13155                .unwrap();
13156            }
13157            // Reconciliation is idempotent, and automatic recovery cannot
13158            // reopen this owner after it observes the rejected repair answer.
13159            apply_task_choice_actions(&queue, &questions, dir.path());
13160            let still_held = queue.get(&task.id).unwrap();
13161            assert!(still_held.operator_held());
13162            assert_eq!(still_held.hold_reason, after.hold_reason);
13163            assert_eq!(still_held.runs, task.runs);
13164            assert!(still_held.review_branch.is_none());
13165            assert!(!still_held.fresh_start);
13166            assert!(queue.next_runnable().is_none());
13167        }
13168    }
13169
13170    #[test]
13171    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
13172        for held in [false, true] {
13173            for retry in [false, true] {
13174                let dir = tempfile::tempdir().unwrap();
13175                let queue = Queue::at(dir.path().join("queue"));
13176                let questions = Questions::at(dir.path().join("questions"));
13177                let home = dir.path().join("home");
13178                let mut t = task();
13179                if held {
13180                    t.hold_machine(Some("driver state unknown".into()));
13181                }
13182                queue.put(&mut t).unwrap();
13183                let verdict = serde_json::from_value(serde_json::json!({
13184                    "decisions": [{
13185                        "id": t.id,
13186                        "question": "Driver state unknown; retry the checks or hold?",
13187                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
13188                        "actions": {
13189                            "daemon: recheck and retry": {"do": "requeue"},
13190                            "daemon: hold the task": {"do": "hold"}
13191                        }
13192                    }]
13193                }))
13194                .unwrap();
13195                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
13196                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13197                let mut q = questions.list().pop().unwrap();
13198                let choice = if retry {
13199                    "daemon: recheck and retry"
13200                } else {
13201                    "daemon: hold the task"
13202                };
13203                assert_eq!(q.actions.len(), 2);
13204                q.answer(ask::Answer::Choice(choice.into())).unwrap();
13205                questions.put(&mut q).unwrap();
13206
13207                // A Web answer does not remove the deputy's fresh lease.
13208                questions.beat(&q.id, ask::WaiterKind::Deputy);
13209                for _ in 0..2 {
13210                    resolve_blockers(&queue, &questions);
13211                    apply_task_choice_actions(&queue, &questions, &home);
13212                    let waiting = queue.get(&t.id).unwrap();
13213                    assert_eq!(waiting.status, TaskStatus::Blocked);
13214                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
13215                    assert!(waiting.answers.is_empty());
13216                    assert!(!waiting.action_applied(&q.id));
13217                    assert!(runnable(&queue).is_empty());
13218                    let free = Arc::new(tokio::sync::Semaphore::new(1));
13219                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
13220                }
13221                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13222
13223                // Releasing the blocker and applying the operation share one save.
13224                resolve_blockers(&queue, &questions);
13225                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13226                apply_task_choice_actions(&queue, &questions, &home);
13227                let after = queue.get(&t.id).unwrap();
13228                assert_eq!(
13229                    after.status,
13230                    if retry {
13231                        TaskStatus::Queued
13232                    } else {
13233                        TaskStatus::Held
13234                    }
13235                );
13236                assert!(after.action_applied(&q.id));
13237                assert_eq!(after.operator_held(), !retry);
13238                assert_eq!(after.answers.len(), 1);
13239
13240                // A later operator decision must not replay this answer.
13241                let mut changed = after;
13242                if retry {
13243                    changed.hold_manual(Some("later hold".into()));
13244                } else {
13245                    changed.release_operator("test", None);
13246                }
13247                let expected = changed.status;
13248                queue.put(&mut changed).unwrap();
13249                apply_task_choice_actions(&queue, &questions, &home);
13250                assert_eq!(queue.get(&t.id).unwrap().status, expected);
13251            }
13252        }
13253    }
13254
13255    #[test]
13256    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
13257        let dir = tempfile::tempdir().unwrap();
13258        let queue = Queue::at(dir.path().join("queue"));
13259        let questions = Questions::at(dir.path().join("questions"));
13260        let home = dir.path().join("home");
13261        let mut state = run_state(RunStatus::Blocked);
13262        state.id = "20260101-000000-act1".to_owned();
13263        state.save_under(&home).unwrap();
13264
13265        let mut t = held_task_with(&state.id);
13266        queue.put(&mut t).unwrap();
13267        let mut q = action_question(&state.id, resume_action(&state.id));
13268        questions.put(&mut q).unwrap();
13269
13270        apply_task_choice_actions(&queue, &questions, &home);
13271        let after = queue.get(&t.id).unwrap();
13272        assert_eq!(after.status, TaskStatus::Queued);
13273        assert!(!after.fresh_start);
13274        assert!(after.action_applied(&q.id));
13275        let pin = after.resume_override.clone().unwrap();
13276        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
13277        assert!(pin.forced);
13278
13279        // Held again later: the same answer does not release it a second time.
13280        let mut again = queue.get(&t.id).unwrap();
13281        again.hold_machine(Some("later".into()));
13282        queue.put(&mut again).unwrap();
13283        apply_task_choice_actions(&queue, &questions, &home);
13284        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13285    }
13286
13287    #[test]
13288    fn a_delivered_answer_is_still_acted_on_exactly_once() {
13289        let dir = tempfile::tempdir().unwrap();
13290        let queue = Queue::at(dir.path().join("queue"));
13291        let questions = Questions::at(dir.path().join("questions"));
13292        let home = dir.path().join("home");
13293        let mut state = run_state(RunStatus::Blocked);
13294        state.id = "20260101-000000-act2".to_owned();
13295        state.save_under(&home).unwrap();
13296
13297        let mut t = held_task_with(&state.id);
13298        queue.put(&mut t).unwrap();
13299        let mut q = action_question(&state.id, resume_action(&state.id));
13300        q.answer_delivered = true;
13301        questions.put(&mut q).unwrap();
13302
13303        // Delivered, and the agent then died: the task is still held, so the
13304        // chosen action applies.
13305        apply_task_choice_actions(&queue, &questions, &home);
13306        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13307        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
13308
13309        // Held again: the same answer does nothing a second time.
13310        let mut again = queue.get(&t.id).unwrap();
13311        again.hold_machine(Some("later".into()));
13312        queue.put(&mut again).unwrap();
13313        apply_task_choice_actions(&queue, &questions, &home);
13314        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13315    }
13316
13317    #[test]
13318    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
13319        let dir = tempfile::tempdir().unwrap();
13320        let queue = Queue::at(dir.path().join("queue"));
13321        let questions = Questions::at(dir.path().join("questions"));
13322        let home = dir.path().join("home");
13323        let mut state = run_state(RunStatus::Blocked);
13324        state.id = "20260101-000000-act3".to_owned();
13325        state.save_under(&home).unwrap();
13326        let mut t = held_task_with(&state.id);
13327        queue.put(&mut t).unwrap();
13328        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
13329        questions.put(&mut q).unwrap();
13330
13331        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
13332        apply_task_choice_actions(&queue, &questions, &home);
13333        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13334
13335        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13336        apply_task_choice_actions(&queue, &questions, &home);
13337        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13338    }
13339
13340    #[test]
13341    fn action_standing_tells_the_reasons_apart() {
13342        let mut t = held_task_with("r1");
13343        let q = action_question("r1", ask::ChoiceAction::Requeue);
13344        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13345        let mut plain = q.clone();
13346        plain.actions.clear();
13347        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
13348
13349        // Applied wins over everything, even a running task.
13350        t.mark_action_applied(&q.id);
13351        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
13352
13353        // A newer attempt running: the old question is Stale, not Busy.
13354        let mut t = held_task_with("r1");
13355        t.start("r2".to_owned());
13356        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
13357        // The same question about the latest run just waits.
13358        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
13359        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13360        t.status = TaskStatus::Blocked;
13361        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13362
13363        // A conductor question is keyed by the task, never stale.
13364        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
13365        c.node = crate::conduct::NODE.to_owned();
13366        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
13367        assert!(!ActionStanding::Busy.daemon_owns());
13368    }
13369
13370    #[test]
13371    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
13372        let dir = tempfile::tempdir().unwrap();
13373        let queue = Queue::at(dir.path().join("queue"));
13374        let questions = Questions::at(dir.path().join("questions"));
13375        let home = dir.path().join("home");
13376        let mut state = run_state(RunStatus::Blocked);
13377        state.id = "20260101-000000-act4".to_owned();
13378        state.save_under(&home).unwrap();
13379        let mut t = held_task_with(&state.id);
13380        t.status = TaskStatus::Running;
13381        queue.put(&mut t).unwrap();
13382        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13383        q.cwd = Some(dir.path().display().to_string());
13384        questions.put(&mut q).unwrap();
13385
13386        // While the task runs the daemon will not act, so the waiter still
13387        // delivers the word to the dead asker's seat ...
13388        let running = queue.get(&t.id).unwrap();
13389        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13390        assert!(matches!(
13391            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13392            crate::waiter::Action::Deliver(_)
13393        ));
13394        // ... and the daemon waits while the task runs, then applies once.
13395        apply_task_choice_actions(&queue, &questions, &home);
13396        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13397        let mut back = queue.get(&t.id).unwrap();
13398        back.hold_machine(Some("later".into()));
13399        queue.put(&mut back).unwrap();
13400        apply_task_choice_actions(&queue, &questions, &home);
13401        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13402        let mut again = queue.get(&t.id).unwrap();
13403        again.hold_machine(Some("again".into()));
13404        queue.put(&mut again).unwrap();
13405        apply_task_choice_actions(&queue, &questions, &home);
13406        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13407    }
13408}