Skip to main content

magi/
daemon.rs

1//! The unattended scheduler and independently leased task workers.
2//!
3//! The scheduler chooses tasks and execution lanes; a detached worker owns each
4//! queue claim, graph driver and outcome settlement. Replacing the scheduler
5//! reconstructs occupied slots from live worker jobs, without touching their
6//! attempts, passes or paid agent calls. Finite maintenance jobs follow the same
7//! lifetime rule. Explicit parking is durable control, never an upgrade step.
8//!
9//! # A crashed worker is legible
10//!
11//! A task is written `Running`, with its run id, before graph execution. The
12//! worker keeps its claim until the outcome is recorded. Recovery requires both
13//! no live worker reservation and an obtainable task claim, and settles the
14//! saved run through the same policy as a live finish. A scheduler's missing
15//! heartbeat alone is never evidence that a run died.
16//!
17//! # Retries are bounded
18//!
19//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
20//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
21//! exception is a run that ended `Stalled`: the panel collapsed because the
22//! agent CLIs hit their quota, which is a fact about the machine and not about
23//! the task, so it must not spend an attempt. Without that exception a quota
24//! outage would quietly hold the entire backlog, and the operator would come
25//! back to a reset quota and nothing left that the loop is willing to run.
26
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Mutex, MutexGuard};
31use std::time::Duration;
32
33use anyhow::{Context, Result, bail};
34use jiff::Timestamp;
35use serde::{Deserialize, Serialize};
36use tokio::sync::Notify;
37
38use crate::ask::{self, Questions};
39use crate::clean;
40use crate::conduct::Conductor;
41use crate::config::{Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{Queue, Task, TaskStatus};
46use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
47use crate::triage;
48
49/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
50pub const SCHEMA: u32 = 1;
51
52/// How often the status file is refreshed. A reader treats a status file older
53/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
54/// that a busy daemon is never mistaken for a dead one.
55pub const HEARTBEAT: Duration = Duration::from_secs(5);
56
57/// How old a heartbeat may be before a reader calls the daemon dead. Six
58/// missed beats: long enough to survive a slow filesystem, short enough that
59/// a crashed daemon is not still reported as running a task.
60///
61/// The single threshold every reader shares — the web UI's `/api/health` and
62/// `magi doctor` both call [`Reading::running`] rather than each comparing
63/// against their own copy of this number, so a crashed daemon cannot look
64/// alive on one screen and dead on another.
65pub const STALE_SECS: i64 = 30;
66
67/// Default queue poll interval.
68pub const POLL: Duration = Duration::from_secs(5);
69
70/// How old a claim has to be before startup sweeps it. Longer than any run
71/// this graph plausibly takes, so a sweep cannot pull a task out from under a
72/// daemon that is merely slow.
73pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
74
75/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
76/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
77///
78/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
79/// poll, by attempting the task's own claim: a dead pid is proof enough for
80/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
81/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
82/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
83/// age instead, since there is nothing else to check (see
84/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
85/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
86/// task `running` — see
87/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
88/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
89/// conductor well before the mechanical six-hour sweep would, and thirty
90/// minutes is comfortably below `STALE_CLAIM` while still being generous
91/// enough that a task merely late to publish its first [`HEARTBEAT`] is
92/// never mistaken for abandoned.
93pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
94
95/// What the loop is working on, for the status file.
96#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(default)]
98pub struct Current {
99    /// Worker reservation that produced this claim; absent on legacy drivers.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub worker: Option<String>,
102    /// Task id being run.
103    pub task: String,
104    /// Run id the task produced.
105    pub run: String,
106}
107
108/// The daemon's liveness, published to `<home>/daemon.json`.
109///
110/// This is the only interface between the loop and the web UI, which is why it
111/// carries `updated_at` as well as `started_at`: a reader cannot tell a
112/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
113/// can compare the heartbeat against the clock.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Status {
116    /// On-disk format version.
117    pub schema: u32,
118    /// Process id, so a human can find or kill the daemon.
119    pub pid: u32,
120    /// When this process started.
121    pub started_at: Timestamp,
122    /// Last heartbeat.
123    pub updated_at: Timestamp,
124    /// True when the queue has nothing runnable.
125    pub idle: bool,
126    /// Every task and run currently in flight. More than one entry means the
127    /// loop is driving more than one run at once — see
128    /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
129    /// nothing is running, so a reader never has to treat "no field" and "an
130    /// empty list" as two different kinds of idle.
131    pub current: Vec<Current>,
132    /// Tasks that reached a terminal status in this process.
133    pub completed: usize,
134    /// Queue polls since start, so a wedged loop shows up as a frozen count.
135    pub polls: u64,
136    /// Effective startup capabilities of the question recovery loops.
137    #[serde(default)]
138    pub question_recovery: Option<crate::question_delivery::Recovery>,
139    /// Independent-worker control protocol supported by this scheduler.
140    #[serde(default)]
141    pub worker_protocol: Option<u32>,
142}
143
144impl Status {
145    /// A fresh, idle status for this process.
146    #[must_use]
147    pub fn new() -> Self {
148        let now = Timestamp::now();
149        Self {
150            schema: SCHEMA,
151            pid: std::process::id(),
152            started_at: now,
153            updated_at: now,
154            idle: true,
155            current: Vec::new(),
156            completed: 0,
157            polls: 0,
158            question_recovery: None,
159            worker_protocol: Some(1),
160        }
161    }
162}
163
164impl Default for Status {
165    fn default() -> Self {
166        Self::new()
167    }
168}
169
170/// How the loop should behave.
171#[derive(Debug, Clone, Serialize, Deserialize)]
172#[serde(default)]
173pub struct Opts {
174    /// Repository used by tasks that name none.
175    pub repo: PathBuf,
176    /// Explicit `magi.toml`, instead of the discovered layer stack.
177    pub config: Option<PathBuf>,
178    /// Queue poll interval.
179    pub poll: Duration,
180    /// Attempts a task gets before it is held for a human.
181    pub max_attempts: usize,
182    /// Drain what is runnable now, then return, instead of waiting for more.
183    pub once: bool,
184    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
185    pub merge: Option<String>,
186    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
187    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
188    /// `None` resolves to [`crate::run::default_worktree_root`] - the
189    /// operator's real `~/wt/<repo>` - the same way a run with no
190    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
191    /// that does not own that directory (a test, an embedding that manages
192    /// worktrees itself) must set this, or every idle tick reclaims worktrees
193    /// out from under whoever actually does.
194    pub worktrees_root: Option<PathBuf>,
195}
196
197impl Default for Opts {
198    fn default() -> Self {
199        Self {
200            repo: PathBuf::from("."),
201            config: None,
202            poll: POLL,
203            max_attempts: 2,
204            once: false,
205            merge: None,
206            worktrees_root: None,
207        }
208    }
209}
210
211impl Opts {
212    fn absolute(&self) -> Result<Self> {
213        let mut opts = self.clone();
214        opts.repo = std::path::absolute(&opts.repo)?;
215        opts.config = opts
216            .config
217            .as_deref()
218            .map(std::path::absolute)
219            .transpose()?;
220        opts.worktrees_root = opts
221            .worktrees_root
222            .as_deref()
223            .map(std::path::absolute)
224            .transpose()?;
225        Ok(opts)
226    }
227}
228
229/// How many runs a plain `usize` from config may drive concurrently, floored
230/// at one. A `0` in a config file would otherwise stall the loop entirely -
231/// no runnable task could ever start - which is never what an operator who
232/// wrote `0` meant.
233fn max_concurrent(n: usize) -> usize {
234    n.max(1)
235}
236
237/// Where the status file lives.
238#[must_use]
239pub fn status_path() -> PathBuf {
240    crate::run::home().join("daemon.json")
241}
242
243/// Publish the status file for this process.
244pub fn write_status(status: &Status) -> Result<()> {
245    write_status_to(&status_path(), status)
246}
247
248/// Publish a status to an explicit path.
249///
250/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
251/// on every health poll and must never see a half-written one.
252pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
253    if let Some(parent) = path.parent() {
254        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
255    }
256    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
257    let tmp = path.with_extension("json.tmp");
258    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
259    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
260    Ok(())
261}
262
263/// Delete the status file. Called on the way out so a clean exit reads as
264/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
265pub fn clear_status() {
266    clear_status_at(&status_path());
267}
268
269/// Delete a status file at an explicit path, so the loop's teardown and
270/// [`clear_status`] cannot drift apart: the loop is handed the path it
271/// published to, and a test can watch a temp file disappear.
272fn clear_status_at(path: &Path) {
273    let _ = std::fs::remove_file(path);
274}
275
276/// A cooperative stop, shared with whoever asked the loop to run.
277///
278/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
279/// Ctrl-C listener and the web UI keep others, and every clone points at the
280/// same flag. There is no channel because there is nothing to send — the only
281/// message is "stop", it is idempotent, and a flag cannot be missed by a
282/// receiver that was not listening yet.
283///
284/// A stop ends scheduler dispatch promptly. Its busy snapshot is observational:
285/// detached task workers keep their own lifetimes and ownership after this
286/// handle's scheduler exits.
287#[derive(Debug, Clone, Default)]
288pub struct Stop {
289    /// Set once, never cleared: a stop is not something an operator takes back
290    /// half way through, and a clearable flag would let a start racing a stop
291    /// resurrect a loop that is already unwinding.
292    stopped: Arc<AtomicBool>,
293    /// Live task workers observed by the scheduler's latest dispatch snapshot.
294    busy: Arc<std::sync::atomic::AtomicUsize>,
295    /// Wakes the idle wait. Without this a stop would not be seen until the
296    /// poll interval elapsed, and an operator tapping stop on a phone would
297    /// watch a button do nothing for five seconds.
298    wake: Arc<Notify>,
299    /// Handed to the run in flight, so a stop can also mean "park at the next
300    /// node boundary" instead of "finish the whole competition first".
301    pause: crate::graph::Pause,
302}
303
304impl Stop {
305    /// A stop nobody has asked for yet.
306    #[must_use]
307    pub fn new() -> Self {
308        Self::default()
309    }
310
311    /// Ask the loop to stop. Idempotent, and safe to call before the loop
312    /// starts: the flag is checked before the first poll.
313    pub fn stop(&self) {
314        self.stopped.store(true, Ordering::SeqCst);
315        // `notify_one` rather than `notify_waiters` because the loop may not be
316        // parked yet: this stores a permit, so a wait that registers a moment
317        // later returns at once instead of sleeping out the whole interval.
318        self.wake.notify_one();
319    }
320
321    /// Has a stop been asked for?
322    #[must_use]
323    pub fn stopped(&self) -> bool {
324        self.stopped.load(Ordering::SeqCst)
325    }
326
327    /// Whether a requested scheduler retirement still has an active snapshot.
328    /// Workers continue independently after the scheduler has retired.
329    #[must_use]
330    pub fn finishing(&self) -> bool {
331        self.stopped() && self.busy_now()
332    }
333
334    /// Ask the loop to stop *and* the run in flight to park at its next node
335    /// boundary.
336    ///
337    /// Unlike plain stop, explicit park asks workers to checkpoint at their
338    /// existing safe boundaries. Binary replacement never needs a park.
339    pub fn park(&self, cause: crate::run::ParkCause) {
340        self.pause.park_for(cause);
341        self.stop();
342    }
343
344    /// Has a park been asked for?
345    #[must_use]
346    pub fn parking(&self) -> bool {
347        self.pause.parked()
348    }
349
350    /// The pause handle to give a runner.
351    #[must_use]
352    pub fn pause(&self) -> crate::graph::Pause {
353        self.pause.clone()
354    }
355
356    /// Whether the scheduler's latest snapshot contains active task workers.
357    #[must_use]
358    pub fn busy_now(&self) -> bool {
359        self.busy.load(Ordering::SeqCst) > 0
360    }
361
362    /// Wait out one poll interval, returning early once a stop is asked for.
363    async fn idle(&self, poll: Duration) {
364        tokio::select! {
365            () = tokio::time::sleep(poll) => {}
366            () = self.wake.notified() => {}
367        }
368    }
369}
370
371/// The daemon's published state, read permissively.
372///
373/// This mirrors [`Status`], but is a separate declaration on purpose: every
374/// field defaults, so a status file from an older or newer magi still yields
375/// a usable reading — one this build has never heard of — instead of a parse
376/// error that hides the daemon entirely.
377#[derive(Debug, Clone, Default, Deserialize)]
378#[serde(default)]
379pub struct Reading {
380    /// Format version the daemon claims.
381    pub schema: u32,
382    /// Daemon process id, for an operator who wants to stop it.
383    pub pid: Option<u32>,
384    /// When that process started.
385    pub started_at: Option<Timestamp>,
386    /// Last heartbeat. Absent means the file is unusable, hence not running.
387    pub updated_at: Option<Timestamp>,
388    /// True when the queue had nothing runnable at the last poll.
389    pub idle: bool,
390    /// What the daemon is working on. Empty means idle; more than one entry
391    /// means more than one run is in flight at once.
392    ///
393    /// `deserialize_with` rather than the plain derive: a daemon started
394    /// before this field became a list is still out there writing the old
395    /// shape — a single `{"task":...,"run":...}` object, or its absence —
396    /// on every heartbeat until it is restarted, and a live process reading
397    /// that file during the rollout must still see it as running rather than
398    /// as absent. A bare type change here would fail the whole struct's
399    /// deserialization on a type mismatch, defeating the permissiveness this
400    /// type exists for.
401    #[serde(deserialize_with = "de_current")]
402    pub current: Vec<Current>,
403    /// Tasks this daemon process has finished.
404    pub completed: u64,
405    /// Queue polls this daemon process has made.
406    pub polls: u64,
407    /// Effective startup capabilities of the question recovery loops.
408    #[serde(default)]
409    pub question_recovery: Option<crate::question_delivery::Recovery>,
410    /// Independent-worker control protocol, absent on legacy embedded loops.
411    pub worker_protocol: Option<u32>,
412}
413
414/// Accept the old single-`Current`-or-absent shape as well as the current
415/// list, so a reader never has to know which build wrote the file.
416fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
417where
418    D: serde::Deserializer<'de>,
419{
420    #[derive(Deserialize)]
421    #[serde(untagged)]
422    enum Shape {
423        Many(Vec<Current>),
424        One(Current),
425    }
426    Ok(
427        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
428            Shape::Many(v) => v,
429            Shape::One(c) => vec![c],
430        }),
431    )
432}
433
434impl Reading {
435    /// Seconds since the last heartbeat, or `None` when there has never been
436    /// one.
437    #[must_use]
438    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
439        self.updated_at
440            .map(|at| (now.as_second() - at.as_second()).max(0))
441    }
442
443    /// Whether the loop counts as running: a heartbeat no older than
444    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
445    /// progress hours after the daemon that owned it was killed.
446    #[must_use]
447    pub fn running(&self, now: Timestamp) -> bool {
448        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
449    }
450}
451
452/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
453/// usable there.
454///
455/// Missing, half-written and unparseable all collapse to `None`, because the
456/// only question a reader asks is whether a daemon is alive, and a file it
457/// cannot read is not evidence that one is.
458#[must_use]
459pub fn read_status(home: &Path) -> Option<Reading> {
460    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
461    serde_json::from_str(&body).ok()
462}
463
464/// Read-only evidence of runs owned by a live daemon or independent worker.
465///
466/// CLI, sandboxed conversation controls and Web cleanup share this observation.
467/// A stale daemon heartbeat does not invalidate a worker's OS-held lease.
468/// Starting reservations and unknown worker state remain protected; observing
469/// them never creates, reconciles or archives files in the worker store.
470/// Callers interested in one identity use [`is_working_on`] or
471/// [`is_working_on_task`].
472#[must_use]
473pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
474    let mut current = read_status(home)
475        .filter(|reading| reading.running(now))
476        .map(|reading| reading.current)
477        .unwrap_or_default();
478    let workers = crate::worker::observe_active(home).and_then(|jobs| {
479        jobs.into_iter()
480            .filter(|job| job.kind == "task")
481            .map(|job| {
482                let request: TaskWorker = serde_json::from_value(job.payload)?;
483                let run = Queue::at(request.queue)
484                    .get(&request.task)
485                    .ok()
486                    .and_then(|task| task.execution_runs().last().cloned())
487                    .unwrap_or_default();
488                Ok(Current {
489                    worker: Some(job.id),
490                    task: request.task,
491                    run,
492                })
493            })
494            .collect::<Result<Vec<_>>>()
495    });
496    match workers {
497        Ok(workers) => {
498            for worker in workers {
499                if !current.iter().any(|claim| {
500                    claim.task == worker.task
501                        && claim.run == worker.run
502                        && claim.worker == worker.worker
503                }) {
504                    current.push(worker);
505                }
506            }
507        }
508        Err(error) => {
509            // This API gates destructive cleanup. Unknown worker ownership
510            // protects every known task/run instead of pretending it is idle.
511            tracing::error!("cannot determine active workers: {error:#}");
512            current.extend(
513                Queue::at(home.join("queue"))
514                    .list()
515                    .into_iter()
516                    .map(|task| Current {
517                        worker: None,
518                        task: task.id.clone(),
519                        run: task.execution_runs().last().cloned().unwrap_or_default(),
520                    }),
521            );
522            current.extend(
523                crate::run::list_ids_in(&home.join("runs"))
524                    .into_iter()
525                    .map(|run| Current {
526                        worker: None,
527                        task: String::new(),
528                        run,
529                    }),
530            );
531        }
532    }
533    current
534}
535
536/// Whether a live daemon is working on this run at this moment.
537#[must_use]
538pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
539    current_work(home, now).iter().any(|c| c.run == run)
540}
541
542/// Admission may ignore only this process's confirmed worker reservation.
543/// Keep anonymous/legacy daemon claims and every other worker, even for the
544/// same task. The run's execution lease and process identity are checked by
545/// the caller under the owner lock as well.
546pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
547    // A helper or test may inherit an identity from a different run store.
548    // That identity grants no exception here; retain all ownership evidence.
549    let same_home = std::env::var_os("MAGI_WORKER_HOME")
550        .is_some_and(|worker_home| Path::new(&worker_home) == home);
551    let caller = if same_home {
552        crate::worker::current_job(home)?
553    } else {
554        None
555    }
556    .filter(|job| {
557        job.kind == "task"
558            && job.status == crate::worker::Status::Running
559            && job.pid == Some(std::process::id())
560    });
561    Ok(other_claims_run(
562        &current_work(home, now),
563        run,
564        caller.as_ref().map(|job| job.id.as_str()),
565    ))
566}
567
568fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
569    claims
570        .iter()
571        .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
572}
573
574/// Whether a live daemon is working on a run whose short id is this one.
575///
576/// For a worktree that has no run record to compare against at all -
577/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
578/// id is not available to hand to [`is_working_on`]. The short id is: a run's
579/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
580/// and it is exactly the gap between the daemon claiming a task and
581/// `RunState::new` saving the first `run.json` that this exists to protect -
582/// a run genuinely in flight but invisible to a scan of `runs/`.
583#[must_use]
584pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
585    current_work(home, now)
586        .iter()
587        .any(|c| crate::run::short_of(&c.run) == short)
588}
589
590/// Whether a live daemon is working on this task at this moment.
591#[must_use]
592pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
593    current_work(home, now).iter().any(|c| c.task == task)
594}
595
596/// Remove claim files whose owner is provably dead, or that have simply
597/// outlived `older_than`, and return the task ids swept.
598///
599/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
600/// destructor, and the orphaned `.lock` file would make its task permanently
601/// unclaimable — the backlog would stop for good at exactly the task that was
602/// in flight when the machine went down.
603///
604/// The pid recorded in the lock is the authority whenever it can be read at
605/// all; age is only a fallback for when it cannot be.
606///
607/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
608///   full stop — dead sweeps the lock immediately, regardless of age; alive
609///   protects it, regardless of age. This is what lets a lock be reclaimed in
610///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
611///   before this daemon even started, next to a `queued` task, no longer has
612///   to sit for six hours before anything notices its owner is gone.
613/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
614///   falls back to `older_than`, since there is nothing else to check.
615///
616/// Age must never override a *positive* liveness confirmation. `sweep`
617/// polls concurrently with independently running task workers. A worker may
618/// legitimately run longer than `older_than`; its live pid must still protect
619/// its claim. Age alone must never turn that claim into a second task attempt,
620/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
621/// to a second attempt — two `Runner`s writing the same `run.json` and the
622/// same worktree at once. `pid_alive` answering "alive" for anything it
623/// cannot determine (a live process, a pid this build cannot check, one
624/// under another account) is exactly what keeps that path from ever
625/// firing on a guess.
626///
627/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
628/// output unreadable must not be license to guess, and the risk of an
629/// unparseable lock outliving a genuinely dead owner is bounded by an order
630/// of magnitude above any plausible run rather than by a positive check.
631///
632/// Runs on every poll, not only at startup — a daemon up for days must keep
633/// noticing a lock some other, now-dead, daemon left behind just as readily
634/// as one it trips over on the way up.
635pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
636    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
637}
638
639/// [`sweep_stale_claims`] with its process-query boundary supplied by the
640/// caller. This keeps the lock policy testable where process listing is
641/// unavailable, while production still uses the platform query above.
642fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
643where
644    F: Fn(u32) -> bool,
645{
646    let this_process = std::process::id();
647    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
648        .into_iter()
649        .flatten()
650        .flatten()
651        .map(|e| e.path())
652        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
653        .filter(|p| {
654            match std::fs::read_to_string(p)
655                .ok()
656                .and_then(|body| body.trim().parse::<u32>().ok())
657            {
658                // This process wrote it and is asking the question right
659                // now, so it is definitionally still alive - settled without
660                // spawning a helper process at all.
661                Some(pid) if pid == this_process => false,
662                Some(pid) => !pid_alive(pid),
663                None => p
664                    .metadata()
665                    .and_then(|m| m.modified())
666                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
667                    .is_ok_and(|age| age >= older_than),
668            }
669        })
670        .filter(|p| std::fs::remove_file(p).is_ok())
671        .filter_map(|p| {
672            p.file_stem()
673                .and_then(|s| s.to_str())
674                .map(std::borrow::ToOwned::to_owned)
675        })
676        .collect();
677    swept.sort_unstable();
678    swept
679}
680
681/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
682/// no live daemon's heartbeat naming it? Deterministic — no model call, and
683/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
684/// shown.
685fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
686    task.status == TaskStatus::Running
687        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
688        && !is_working_on_task(home, &task.id, now)
689}
690
691/// Every task [`is_stalled`] right now — "止まったタスク" in
692/// `crate::conduct`'s vocabulary.
693fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
694    queue
695        .list()
696        .into_iter()
697        .filter(|t| is_stalled(t, home, now))
698        .collect()
699}
700
701/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
702/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
703/// `Failed`-and-so-also-runnable: a task that already attempted and lost
704/// belongs in [`finished_tasks`], where the question is a recovery, not a
705/// dependency.
706fn queued_tasks(queue: &Queue) -> Vec<Task> {
707    queue
708        .list()
709        .into_iter()
710        .filter(|t| t.status == TaskStatus::Queued)
711        .collect()
712}
713
714/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
715/// タスク" in `crate::conduct`'s vocabulary.
716fn finished_tasks(queue: &Queue) -> Vec<Task> {
717    queue
718        .list()
719        .into_iter()
720        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
721        .collect()
722}
723
724/// Deterministically resolve `Task::blocked_by`: a dependency task that
725/// reached `Done`, or a question that was answered, is removed — no model
726/// involved, on every poll. An answered question's content is copied onto
727/// the task ([`Task::record_answer`]) before its id is dropped, so it
728/// reaches the next `crate::conduct` prompt and the next run's instruction
729/// (see [`instruction_for`]) rather than only clearing the block.
730///
731/// A `blocked_by` id that names neither an existing task nor an existing
732/// question - `magi task rm` (or an operator by hand) deleted it while this
733/// task was still waiting - is caught before any of that: it can never
734/// become `Done` or `Answered`, so the ordinary loop below would otherwise
735/// leave the task `blocked` forever with nothing to notice. Such a task is
736/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
737/// which puts it in front of `crate::triage::run_once`'s own walk the next
738/// time it runs - see that module's doc for why the choice is "ask a human",
739/// never "assume the missing dependency was satisfied and unblock anyway".
740fn resolve_blockers(queue: &Queue, questions: &Questions) {
741    for listed in queue.list() {
742        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
743            continue;
744        }
745        let Ok(_claim) = queue.claim(&listed.id) else {
746            continue;
747        };
748        let Ok(mut task) = queue.get(&listed.id) else {
749            continue;
750        };
751        if task.status != TaskStatus::Blocked {
752            continue;
753        }
754        // A dependency deleted on purpose is released, not held - and before
755        // the missing check, so a pass that races the delete (or a claim that
756        // made `Queue::remove` skip this task) settles it quietly.
757        let deleted = queue.apply_deleted_blockers(&mut task, questions);
758        if !deleted.is_empty() {
759            record(queue, &mut task);
760            for id in &deleted {
761                queue.note_dependency_deleted(&task, id);
762            }
763            if task.status != TaskStatus::Blocked {
764                continue;
765            }
766        }
767        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
768        if !missing.is_empty() {
769            let language = language_of(&task, Path::new("."));
770            let mut cause = missing.clone();
771            cause.sort();
772            cause.dedup();
773            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
774            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
775                &task.blocked_by,
776                &missing,
777                &language,
778            )));
779            record(queue, &mut task);
780            continue;
781        }
782        // A conductor question nobody answered in time is retired by the
783        // waiter, and nothing else would ever move the task it blocks.
784        if let Some(q) = task.blocked_by.iter().find_map(|id| {
785            let crate::queue::Dependency::Question(full) =
786                crate::queue::dependency(queue, questions, id)
787            else {
788                return None;
789            };
790            questions.get_for_effects(&full).ok().filter(|q| {
791                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
792            })
793        }) {
794            let language = language_of(&task, Path::new("."));
795            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
796            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
797            record(queue, &mut task);
798            continue;
799        }
800        let mut changed = false;
801        for id in task.blocked_by.clone() {
802            let resolved = crate::queue::dependency(queue, questions, &id);
803            if let crate::queue::Dependency::Task(full) = &resolved {
804                if queue
805                    .get(full)
806                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
807                {
808                    task.unblock(&id);
809                    changed = true;
810                }
811                continue;
812            }
813            if let crate::queue::Dependency::Question(full) = resolved
814                && let Ok(q) = questions.get_for_effects(&full)
815                && q.status == ask::QuestionStatus::Answered
816            {
817                // The action sweep releases conductor blockers atomically
818                // with their selected operation. A fresh deputy lease must
819                // never leave an answered hold temporarily runnable.
820                if q.node == crate::conduct::NODE
821                    && q.chosen_action().is_some()
822                    && !task.action_applied(&q.id)
823                {
824                    continue;
825                }
826                let answer = match &q.answer {
827                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
828                    None => String::new(),
829                };
830                task.record_answer(q.summary.clone(), answer);
831                task.unblock(&id);
832                changed = true;
833            }
834        }
835        if changed {
836            record(queue, &mut task);
837        }
838    }
839}
840
841/// The `hold_reason` of a task whose conductor question went unanswered.
842fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
843    if crate::lang::is_japanese(language) {
844        format!(
845            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
846            q.short(),
847            q.summary
848        )
849    } else {
850        format!(
851            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
852            q.short(),
853            q.summary
854        )
855    }
856}
857
858/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
859/// for several unrelated reasons, and the waiter must not read them alike.
860#[derive(Debug, Clone, Copy, PartialEq, Eq)]
861pub(crate) enum ActionStanding {
862    /// The answer carries no action: the waiter delivers it as before.
863    NoAction,
864    /// The daemon will apply it (not applied, task idle, current attempt).
865    Pending,
866    /// Already applied (`Task::actions_applied`): the daemon has acted, so
867    /// delivering the word to the old seat would run it beside the new work.
868    Applied,
869    /// The question is about an earlier attempt than the task's latest.
870    Stale,
871    /// The task is running / blocked / done: the daemon defers for now.
872    Busy,
873}
874
875impl ActionStanding {
876    /// The daemon has acted or will act: the waiter must not deliver.
877    pub(crate) fn daemon_owns(self) -> bool {
878        matches!(self, Self::Pending | Self::Applied | Self::Stale)
879    }
880}
881
882/// Classify `q`'s chosen action against `task`. `Stale` is judged before
883/// `Busy`: a question about an earlier attempt must be stopped even while a
884/// newer competition is running.
885pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
886    if task.stale_question(q) {
887        ActionStanding::Stale
888    } else if q.chosen_action().is_none() {
889        ActionStanding::NoAction
890    } else if task.action_applied(&q.id) {
891        ActionStanding::Applied
892    } else if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
893        ActionStanding::Stale
894    } else if matches!(
895        task.status,
896        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
897    ) {
898        ActionStanding::Busy
899    } else {
900        ActionStanding::Pending
901    }
902}
903
904/// What [`decide_action`] concluded about one answered question.
905#[derive(Debug, Clone, PartialEq, Eq)]
906enum ActionDecision {
907    /// Nothing to do now (no action, already applied, or the task is busy).
908    Skip,
909    /// Continue the named run instead of competing again.
910    Resume(String),
911    /// Requeue as a fresh competition.
912    Requeue,
913    /// Hold the task by explicit operator choice.
914    Hold,
915    /// Close the task as done.
916    Done,
917    /// The question is about an earlier attempt than the task's latest; it
918    /// is recorded as handled and changes nothing.
919    Stale,
920    /// The action cannot be carried out; hold the task and say why. Never
921    /// falls back to something else, because the operator chose this one.
922    Refuse(String),
923}
924
925/// Decide what the choice answered on `q` means for `task`. `load` reads a
926/// run's state, as with [`unfinished_run_with`]. `home` must name that same
927/// store for driver leases and question checkpoints.
928///
929/// `Resume` only fires on the task's *latest* run, and only while that run
930/// could actually make progress ([`RunStatus::resumable`], not released, review
931/// budget left); an answer naming anything else is refused rather than
932/// reinterpreted as a fresh competition.
933fn decide_action<F>(
934    home: &Path,
935    task: &Task,
936    q: &ask::Question,
937    p: &Phrases,
938    load: F,
939) -> ActionDecision
940where
941    F: FnOnce(&str) -> Result<RunState>,
942{
943    if task.stale_question(q) {
944        return ActionDecision::Stale;
945    }
946    let Some(action) = q.chosen_action() else {
947        return ActionDecision::Skip;
948    };
949    if task.action_applied(&q.id)
950        || matches!(
951            task.status,
952            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
953        )
954    {
955        return ActionDecision::Skip;
956    }
957    // A question about an earlier attempt must not act on a newer one. A
958    // conductor question is keyed by the task id, not a run, so it is exempt.
959    if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
960        return ActionDecision::Stale;
961    }
962    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
963    let stopping = q.node == land::APPROVAL_NODE
964        && q.resolution()
965            .as_deref()
966            .is_some_and(crate::merge_decision::stops);
967    // An answer is the owner's decision as of when it was given: a manual hold
968    // placed before it (even after the question was asked) was seen and
969    // overruled by it, while a hold or release after it supersedes it.
970    let decision_at = q.answered_at.unwrap_or(q.asked_at);
971    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
972        return if repair || stopping {
973            ActionDecision::Refuse(format!(
974                "{} answer {} was superseded by a later operator decision; the task stays held. Inspect `magi show {}`; if this action is still wanted, explicitly release the existing owner with `magi task release {}`",
975                if repair { "repair" } else { "stop" },
976                q.id,
977                q.run,
978                task.id
979            ))
980        } else {
981            ActionDecision::Stale
982        };
983    }
984    match action {
985        a if a.maintenance() => ActionDecision::Skip,
986        ask::ChoiceAction::RecoverBase { .. }
987        | ask::ChoiceAction::ResumeRun { .. }
988        | ask::ChoiceAction::ReleaseTask { .. }
989        | ask::ChoiceAction::RerunChecks { .. }
990        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
991        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
992        ask::ChoiceAction::Hold => ActionDecision::Hold,
993        ask::ChoiceAction::Done => ActionDecision::Done,
994        ask::ChoiceAction::Resume { run } => {
995            if task.execution_runs().last() != Some(run) {
996                return ActionDecision::Refuse((p.resume_not_latest)(
997                    q.short(),
998                    ask::short_id(run),
999                ));
1000            }
1001            match load(run) {
1002                Ok(s) if stopping => {
1003                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1004                        || !s
1005                            .land_approval
1006                            .as_ref()
1007                            .is_some_and(|binding| binding.question == q.id)
1008                    {
1009                        ActionDecision::Stale
1010                    } else if s.liveness_under(home, false) == Liveness::Live {
1011                        ActionDecision::Skip
1012                    } else if s.status == RunStatus::Landing
1013                        && !s.released()
1014                        && s.retired_to.is_none()
1015                    {
1016                        ActionDecision::Resume(run.clone())
1017                    } else {
1018                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1019                    }
1020                }
1021                Ok(s)
1022                    if q.node == land::APPROVAL_NODE
1023                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1024                {
1025                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1026                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1027                    {
1028                        // A live/manual driver already consumed or superseded
1029                        // this answer. Do not hold its fresh approval wait.
1030                        ActionDecision::Stale
1031                    } else if s.liveness_under(home, false) == Liveness::Live {
1032                        ActionDecision::Skip
1033                    } else if s.status != RunStatus::Landing
1034                        || s.released()
1035                        || s.reviews.is_empty()
1036                        || !implementers_match(task, &s)
1037                        || !s
1038                            .land_approval
1039                            .as_ref()
1040                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1041                    {
1042                        ActionDecision::Refuse(format!(
1043                            "repair question {} no longer names a supported current approval on run {}; inspect `magi show {}` and restore the existing owner's approval before retrying; do not file another task",
1044                            q.id, run, run
1045                        ))
1046                    } else {
1047                        ActionDecision::Resume(run.clone())
1048                    }
1049                }
1050                Ok(s) if s.liveness_under(home, false) == Liveness::Live => {
1051                    ActionDecision::Refuse("run already has a live driver".into())
1052                }
1053                Ok(s) => match crate::handover::resume_refusal_under(&s, Some(home)) {
1054                    None => ActionDecision::Resume(run.clone()),
1055                    Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1056                        q.short(),
1057                        ask::short_id(run),
1058                        &reason.diagnostic(&s),
1059                    )),
1060                },
1061                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1062                    q.short(),
1063                    ask::short_id(run),
1064                    &format!("{e:#}"),
1065                )),
1066            }
1067        }
1068    }
1069}
1070
1071/// The fixed prose the daemon writes into [`Task::last_error`] and
1072/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1073/// `triage::Wording` and `land::Words`: only English and Japanese are
1074/// translated, anything else falls back to English.
1075///
1076/// Rendered when the reason is *generated*, so a reason keeps the language it
1077/// was written in if the setting changes later. The notification frame
1078/// (`Task <id> is held:`) is not here and stays English.
1079///
1080/// Deliberately **not** translated, because other code reads them back by
1081/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1082/// and `gate red`. IDs, node names, paths and external error text are embedded
1083/// as they are.
1084struct Phrases {
1085    /// `{}` = status label, then the detail.
1086    graph_stopped: fn(&str, &str) -> String,
1087    quorum_lost: &'static str,
1088    /// Followed by the seats' names.
1089    quota_took_out: &'static str,
1090    /// Followed by the status label.
1091    run_ended: &'static str,
1092    /// Followed by the question's short id.
1093    waiting_for_answer: &'static str,
1094    recovered_running: &'static str,
1095    no_run_to_recover: &'static str,
1096    could_not_start: &'static str,
1097    resume_not_latest: fn(&str, &str) -> String,
1098    resume_cannot_progress: fn(&str, &str, &str) -> String,
1099    resume_unreadable: fn(&str, &str, &str) -> String,
1100    /// A takeover refusal: the operator-facing text. English is the error's own
1101    /// `Display`; a translation keeps the machine detail apart in parentheses.
1102    handover_refused: fn(&crate::handover::Refused) -> String,
1103    /// Appended to a refused handover's hold reason (leading space included).
1104    handover_hint: &'static str,
1105    /// (seats that never answered, review rounds) for the review loop's
1106    /// "refusing to call it clean" stop.
1107    reviewers_never_answered: fn(usize, usize) -> String,
1108}
1109
1110const PHRASES_EN: Phrases = Phrases {
1111    graph_stopped: |status, detail| {
1112        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1113    },
1114    quorum_lost: "the judging panel lost its quorum",
1115    quota_took_out: "; quota took out ",
1116    run_ended: "run ended ",
1117    waiting_for_answer: " - waiting for operator answer to question ",
1118    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1119    no_run_to_recover: "task was `running` with no live daemon and no readable \
1120                        run to recover; held for a human to check what happened",
1121    could_not_start: "could not start the run: ",
1122    resume_not_latest: |q, run| {
1123        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1124    },
1125    resume_cannot_progress: |q, run, reason| {
1126        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1127    },
1128    resume_unreadable: |q, run, e| {
1129        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1130    },
1131    handover_refused: |r| r.to_string(),
1132    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1133    reviewers_never_answered: |missing, rounds| {
1134        format!(
1135            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1136             refusing to call it clean"
1137        )
1138    },
1139};
1140
1141const PHRASES_JA: Phrases = Phrases {
1142    graph_stopped: |status, detail| {
1143        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1144    },
1145    quorum_lost: "審査パネルが定足数を失いました",
1146    quota_took_out: "。クォータで脱落: ",
1147    run_ended: "run 終了: ",
1148    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1149    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1150    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1151                        何が起きたか人が確認するため保留にしました",
1152    could_not_start: "run を開始できませんでした: ",
1153    resume_not_latest: |q, run| {
1154        format!(
1155            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1156        )
1157    },
1158    resume_cannot_progress: |q, run, reason| {
1159        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1160    },
1161    resume_unreadable: |q, run, e| {
1162        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1163    },
1164    handover_refused: |r| {
1165        use crate::handover::Refused;
1166        match r {
1167            Refused::Foreign { branch, path, why } => format!(
1168                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1169                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1170                 から、やり直してください(詳細: {why})"
1171            ),
1172            Refused::Unsafe { branch, path, why } => format!(
1173                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1174                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1175                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1176            ),
1177            Refused::ReleaseFailed { branch, path, run } => format!(
1178                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1179                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1180                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1181            ),
1182        }
1183    },
1184    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1185    reviewers_never_answered: |missing, rounds| {
1186        format!(
1187            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1188             クリーンとは認めません"
1189        )
1190    },
1191};
1192
1193fn phrases(language: &str) -> &'static Phrases {
1194    if crate::lang::is_japanese(language) {
1195        &PHRASES_JA
1196    } else {
1197        &PHRASES_EN
1198    }
1199}
1200
1201/// The language of the repository a task belongs to, read best-effort for the
1202/// paths that have no run (and so no config of their own) to ask. An unreadable
1203/// config is English, not an error: a hold reason must still get written.
1204fn language_of(task: &Task, fallback: &Path) -> String {
1205    crate::lang::of_repo(&repo_for(task, fallback))
1206}
1207
1208/// The task an answered question speaks for: the one whose runs include the
1209/// question's run, or - for a conductor question, filed under the task's own
1210/// id - the task with that id.
1211pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1212    if q.node == crate::conduct::NODE {
1213        return tasks.iter().find(|t| t.id == q.run);
1214    }
1215    tasks.iter().find(|t| t.runs.contains(&q.run))
1216}
1217
1218/// Legacy conductor prose never becomes a maintenance command by inference.
1219/// Replace unsupported open labels under the question lock before dispatch.
1220fn repair_choice_offers(questions: &Questions) {
1221    let ownership = crate::task_chat::InquiryOwnership::default();
1222    for q in questions
1223        .list_for_effects_in(&ownership)
1224        .into_iter()
1225        .filter(|q| {
1226            q.status.open()
1227                && q.node == crate::conduct::NODE
1228                && q.choices
1229                    .iter()
1230                    .any(|c| crate::choice_effect::describe(q, c).is_none())
1231        })
1232    {
1233        let _ = questions.update_in(&q.id, &ownership, |current| {
1234            if current.status.open() {
1235                crate::choice_effect::executable_conductor(current);
1236                if let Some(deputy) = &mut current.deputy {
1237                    deputy.brief = crate::deputy::brief(
1238                        &current.run,
1239                        &current.detail,
1240                        &current.choices,
1241                        &current.actions,
1242                    );
1243                }
1244            }
1245            Ok(())
1246        });
1247    }
1248}
1249
1250/// Apply answered typed choices. Only the daemon calls this in production;
1251/// deputies settle the question and never execute its actions.
1252pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1253    apply_maintenance_choices(queue, questions, home).await;
1254    apply_task_choice_actions(queue, questions, home);
1255}
1256
1257/// Apply bounded maintenance effects independently of question ownership: a
1258/// release watcher need not have a queue task, and a predecessor is another run.
1259async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1260    let ownership = crate::task_chat::InquiryOwnership::default();
1261    for q in questions.list_for_effects_in(&ownership) {
1262        // Read again under the same fence used by explicit settlement.
1263        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1264            continue;
1265        };
1266        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1267            continue;
1268        };
1269        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1270            continue;
1271        };
1272        // Receipt paths use question IDs, whose format is independent of run
1273        // IDs. Apply the question store's filename safety rule to both eras.
1274        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1275            continue;
1276        }
1277        if queue.list().iter().any(|task| {
1278            (task.id == q.run
1279                || task.runs.contains(&q.run)
1280                || q.routed_task.as_deref() == Some(&task.id))
1281                && task.stale_question(&q)
1282        }) {
1283            continue;
1284        }
1285        if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1286            let tasks = queue.list();
1287            let owner = crate::task_chat::task_of(&q, &tasks);
1288            if let Some(owner) = owner
1289                && q.routed_task
1290                    .as_deref()
1291                    .is_none_or(|routed| routed == owner)
1292            {
1293                let result = crate::base_recovery_control::recover(
1294                    queue,
1295                    home,
1296                    crate::base_recovery_control::Request {
1297                        run: run.clone(),
1298                        head: stop.head.clone(),
1299                        actor: "decisions".into(),
1300                        request: q.id.clone(),
1301                        decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1302                        expected_stop: Some((stop.clone(), *episode)),
1303                    },
1304                )
1305                .await;
1306                if let Err(error) = result {
1307                    tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1308                    notices::raise_in(home, Notice::warn(
1309                        &format!("base-recovery:{}", q.id),
1310                        format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1311                    ).link(Link::Run { id: run.clone() }));
1312                }
1313            }
1314            continue;
1315        }
1316        let dir = home.join("choice-actions");
1317        if std::fs::create_dir_all(&dir).is_err() {
1318            continue;
1319        }
1320        let Ok(lock) = std::fs::OpenOptions::new()
1321            .create(true)
1322            .truncate(false)
1323            .write(true)
1324            .open(dir.join(format!("{}.lock", q.id)))
1325        else {
1326            continue;
1327        };
1328        if crate::pr_head::try_lock_file(&lock).is_err() {
1329            continue;
1330        }
1331        let fresh = !home
1332            .join("choice-actions")
1333            .join(format!("{}.json", q.id))
1334            .exists();
1335        let result = async {
1336            let receipt = dir.join(format!("{}.json", q.id));
1337            if receipt.exists() {
1338                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1339                anyhow::ensure!(
1340                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1341                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1342                );
1343                return Ok::<_, anyhow::Error>(());
1344            }
1345            // Never retry an uncertain external effect. The receipt is written
1346            // before calling gh, exactly like release_watch's rerun record.
1347            let record = |status: &str| -> anyhow::Result<()> {
1348                let tmp = receipt.with_extension("tmp");
1349                std::fs::write(
1350                    &tmp,
1351                    serde_json::to_vec(&serde_json::json!({
1352                        "action": action, "status": status,
1353                    }))?,
1354                )?;
1355                std::fs::rename(tmp, &receipt)?;
1356                Ok(())
1357            };
1358            let applied = async {
1359                match action {
1360                    ask::ChoiceAction::ResumeRun { run } => {
1361                        crate::resume::validate(home, run)?;
1362                        record("started")?;
1363                        let decided = q.answered_at.unwrap_or(q.asked_at);
1364                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1365                            crate::resume::validate_unqueued(home, run)?;
1366                            crate::resume::start(home, run.clone()).await?;
1367                        }
1368                    }
1369                    ask::ChoiceAction::ReleaseTask {
1370                        task,
1371                        held_at,
1372                        reason,
1373                    } => {
1374                        anyhow::ensure!(
1375                            queue.resolve_id(task)? == *task,
1376                            "task action requires an exact task ID"
1377                        );
1378                        let _claim = queue.claim(task)?;
1379                        let mut task = queue.get(task)?;
1380                        if task.action_applied(&q.id) {
1381                            return Ok(());
1382                        }
1383                        // Filing this conductor question temporarily wraps the
1384                        // original hold in a Blocked state. Restore only that
1385                        // exact blocker on the local copy before checking the
1386                        // hold binding; unrelated waits never authorize release.
1387                        if q.node == crate::conduct::NODE
1388                            && q.run == task.id
1389                            && task.status == TaskStatus::Blocked
1390                            && task.blocked_from == Some(TaskStatus::Held)
1391                            && task.blocked_by.as_slice() == [q.id.as_str()]
1392                        {
1393                            task.unblock(&q.id);
1394                        }
1395                        anyhow::ensure!(
1396                            task.status == TaskStatus::Held
1397                                && task.held_at == Some(*held_at)
1398                                && task.hold_reason.as_deref() == reason.as_deref()
1399                                && task
1400                                    .operator_decided_at
1401                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1402                            "task no longer has the hold this question names"
1403                        );
1404                        task.release_operator("choice", Some(&q.id));
1405                        task.mark_action_applied(&q.id);
1406                        queue.put(&mut task)?;
1407                    }
1408                    ask::ChoiceAction::AbandonRun { run } => {
1409                        record("started")?;
1410                        crate::driver::abandon_proven_dead(home, run)?;
1411                    }
1412                    ask::ChoiceAction::RerunChecks {
1413                        repo,
1414                        pr,
1415                        head,
1416                        runs,
1417                    } => {
1418                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1419                            .await?;
1420                    }
1421                    _ => unreachable!(),
1422                }
1423                Ok::<_, anyhow::Error>(())
1424            }
1425            .await;
1426            match applied {
1427                Ok(()) => record("applied"),
1428                Err(e) => {
1429                    record(&format!("refused or failed: {e:#}"))?;
1430                    Err(e)
1431                }
1432            }
1433        }
1434        .await;
1435        // Retire the originating blocker as well as the target operation.
1436        // A foreign resume leaves its issuer held instead of competing beside
1437        // the execution just started. Other successful maintenance lets the
1438        // original task retry its normal, guarded path.
1439        if home
1440            .join("choice-actions")
1441            .join(format!("{}.json", q.id))
1442            .exists()
1443            && let Some(listed) = task_of_question(&queue.list(), &q)
1444            && !listed.action_applied(&q.id)
1445            && let Ok(_claim) = queue.claim(&listed.id)
1446            && let Ok(mut origin) = queue.get(&listed.id)
1447        {
1448            if !origin.operator_held()
1449                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1450                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1451            {
1452                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1453                    origin.hold_machine(Some(format!(
1454                        "Maintenance choice {} settled; inspect its target before releasing this task",
1455                        q.id
1456                    )));
1457                } else {
1458                    origin.unblock(&q.id);
1459                }
1460            }
1461            origin.mark_action_applied(&q.id);
1462            let _ = queue.put(&mut origin);
1463        }
1464        if let Err(e) = result
1465            && fresh
1466        {
1467            notices::raise_in(
1468                home,
1469                Notice::warn(
1470                    &format!("action:{}", q.id),
1471                    format!("Choice action {} was not completed: {e:#}", q.id),
1472                )
1473                .link(if q.run_names_task() {
1474                    Link::Task { id: q.run.clone() }
1475                } else {
1476                    Link::Run { id: q.run.clone() }
1477                }),
1478            );
1479        }
1480    }
1481}
1482
1483/// Rerun the named failed workflow runs of a pull request, each at most once
1484/// per `request` (a question id, or a chat operation identity). The head,
1485/// lifecycle and failed state are re-read from the forge first; `started` is
1486/// called once those checks pass and before the first external call, and the
1487/// ledger entry is written before every `gh` call, so an uncertain result is
1488/// never repeated automatically.
1489pub(crate) async fn rerun_checks_once(
1490    home: &Path,
1491    request: &str,
1492    repo: &Path,
1493    pr: &str,
1494    head: &str,
1495    runs: &[String],
1496    started: impl FnOnce() -> anyhow::Result<()>,
1497) -> anyhow::Result<()> {
1498    use crate::release_watch::{GhForge, ReleaseForge};
1499    anyhow::ensure!(
1500        !runs.is_empty()
1501            && runs.len() <= 20
1502            && runs
1503                .iter()
1504                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1505            && !pr.starts_with('-'),
1506        "invalid rerun targets"
1507    );
1508    let snap = GhForge.snapshot(repo, pr).await?;
1509    anyhow::ensure!(
1510        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1511        "pull request head or lifecycle changed"
1512    );
1513    anyhow::ensure!(
1514        runs.iter().all(|r| snap
1515            .checks
1516            .iter()
1517            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1518        "named workflow is no longer failed on this pull request"
1519    );
1520    started()?;
1521    let dir = home.join("choice-actions");
1522    std::fs::create_dir_all(&dir)?;
1523    let rerun_lock = std::fs::OpenOptions::new()
1524        .create(true)
1525        .truncate(false)
1526        .write(true)
1527        .open(dir.join("reruns.lock"))?;
1528    crate::pr_head::try_lock_file(&rerun_lock)?;
1529    let ledger = dir.join("reruns.json");
1530    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1531        serde_json::from_slice(&std::fs::read(&ledger)?)?
1532    } else {
1533        Default::default()
1534    };
1535    for run in runs {
1536        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1537        if !recorded.insert(key) {
1538            continue;
1539        }
1540        let tmp = ledger.with_extension("tmp");
1541        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1542        std::fs::rename(tmp, &ledger)?;
1543        GhForge.rerun(repo, run).await?;
1544    }
1545    Ok(())
1546}
1547
1548/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1549///
1550/// Runs on every poll before the conductor looks at the queue. The task is
1551/// re-read under its claim, so a task somebody completed or held by hand in
1552/// the meantime is judged on what it is now. `Resume` releases the task and
1553/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1554/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1555/// ordinary `unfinished_run` logic resumes that same run.
1556pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1557    let tasks = queue.list();
1558    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1559    for q in questions.list_for_effects_in(&ownership) {
1560        // Read again under the same fence used by explicit settlement.
1561        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1562            continue;
1563        };
1564        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1565            continue;
1566        };
1567        // Dismissal is committed by the question writer, never a resume.
1568        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1569            continue;
1570        }
1571        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1572            continue;
1573        }
1574        let Some(listed) = task_of_question(&tasks, &q) else {
1575            if q.node == land::APPROVAL_NODE
1576                && q.resolution().as_deref().is_some_and(|choice| {
1577                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1578                })
1579            {
1580                notices::raise_in(
1581                    home,
1582                    Notice::warn(
1583                        &format!("repair-owner:{}", q.id),
1584                        format!(
1585                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1586                            q.run, q.run
1587                        ),
1588                    ).link(Link::Run { id: q.run.clone() }),
1589                );
1590            }
1591            continue;
1592        };
1593        if listed.action_applied(&q.id) {
1594            continue;
1595        }
1596        let Ok(_claim) = queue.claim(&listed.id) else {
1597            continue;
1598        };
1599        let Ok(mut task) = queue.get(&listed.id) else {
1600            continue;
1601        };
1602        // Work only on this local copy until the action can be committed.
1603        // In particular, a fresh lease below leaves the persisted task blocked.
1604        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1605            let blockers: Vec<_> = task
1606                .blocked_by
1607                .iter()
1608                .filter(|id| {
1609                    crate::queue::dependency(queue, questions, id)
1610                        == crate::queue::Dependency::Question(q.id.clone())
1611                })
1612                .cloned()
1613                .collect();
1614            if !blockers.is_empty() {
1615                for id in blockers {
1616                    task.unblock(&id);
1617                }
1618                let answer = match &q.answer {
1619                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1620                    None => String::new(),
1621                };
1622                task.record_answer(q.summary.clone(), answer);
1623            }
1624        }
1625        let language = language_of(&task, Path::new("."));
1626        let decision = decide_action(home, &task, &q, phrases(&language), |id| {
1627            RunState::load_under(id, home)
1628        });
1629        let ran = matches!(
1630            decision,
1631            ActionDecision::Resume(_)
1632                | ActionDecision::Requeue
1633                | ActionDecision::Hold
1634                | ActionDecision::Done
1635        );
1636        if ran && asker_may_still_read(questions, &q, home) {
1637            // The asking process or its seat can still take the word; act
1638            // once it has gone quiet. Bound on the remaining window: the
1639            // check is not atomic with the write below, so an asker that
1640            // takes the word in between (at most one poll, never more than
1641            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1642            // and `Task::actions_applied` under the claim keeps the action to
1643            // one application. The waiter does not deliver an answer that
1644            // carries an action (`waiter::decide_owned`), so it cannot race.
1645            continue;
1646        }
1647        let done = matches!(decision, ActionDecision::Done);
1648        // Resume owes an execution pass; only these task-local effects finish
1649        // in this write. Stale/refused actions never acquire an effect receipt.
1650        let completed = matches!(
1651            decision,
1652            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1653        );
1654        match decision {
1655            ActionDecision::Skip => continue,
1656            ActionDecision::Resume(run) => {
1657                task.release_operator("choice", Some(&q.id));
1658                task.resume_override = Some(crate::queue::OperatorResume {
1659                    question_id: q.id.clone(),
1660                    at: Timestamp::now(),
1661                    conductor_rehold: None,
1662                    forced: true,
1663                    pinned_run: Some(run),
1664                });
1665            }
1666            ActionDecision::Stale => {}
1667            ActionDecision::Requeue => {
1668                task.release_operator("choice-requeue", Some(&q.id));
1669                task.requeue();
1670            }
1671            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1672            ActionDecision::Done => task.succeed(),
1673            ActionDecision::Refuse(why) => {
1674                let _ =
1675                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1676                if task.operator_held() {
1677                    // A rejected answer does not release the operator's hold
1678                    // or reclassify it as recoverable by the conductor.
1679                    task.hold_reason = Some(match task.hold_reason.take() {
1680                        Some(reason) => format!("{reason}\n\n{why}"),
1681                        None => why,
1682                    });
1683                } else {
1684                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1685                    task.hold_machine(Some(why));
1686                }
1687                notices::raise(
1688                    Notice::warn(
1689                        &format!("action:{}", q.id),
1690                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1691                    )
1692                    .link(Link::Task {
1693                        id: task.id.clone(),
1694                    }),
1695                );
1696            }
1697        }
1698        task.mark_action_applied(&q.id);
1699        if completed {
1700            task.decision_effects.insert(
1701                q.id.clone(),
1702                format!("decision: {}", q.resolution().expect("answered action")),
1703            );
1704        }
1705        // The applied id travels with the transition, so a failed save loses
1706        // neither and the answer is acted on at the next poll.
1707        record(queue, &mut task);
1708        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1709            supersede_prior_runs(&task, home);
1710        }
1711        // Delivery is only a note of who has read the answer; the task's own
1712        // mark above is the authority. Best effort.
1713        let _ = questions.update_in(&q.id, &ownership, |r| {
1714            r.answer_delivered = true;
1715            Ok(())
1716        });
1717    }
1718}
1719
1720/// Whether something may still read the answer to `q`: a fresh lease, or the
1721/// asking seat still listed as active in its run (its CLI can outlive the
1722/// `magi ask` that was killed).
1723fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1724    let now = Timestamp::now();
1725    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1726        return true;
1727    }
1728    q.node != crate::conduct::NODE
1729        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1730            s.seats_active()
1731                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1732        })
1733}
1734
1735/// Retire an unanswered conductor question after its task no longer refers to
1736/// it. Conductor questions use the task id in `Question::run`, so run-based
1737/// cleanup cannot observe a manual release or completion.
1738///
1739/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1740/// own question also carries a `run`, and a run id that happens to collide
1741/// with some task's id is not this loop's business — only a conductor
1742/// question actually uses the task id that way. One `Questions::list()` scan
1743/// is taken up front and matched against the in-memory task set, rather than
1744/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1745fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1746    let tasks = queue.list();
1747    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1748    let by_id: std::collections::BTreeMap<&str, &Task> =
1749        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1750    let referenced: Vec<&str> = tasks
1751        .iter()
1752        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1753        .collect();
1754
1755    for mut question in questions.list_for_effects_in(&ownership) {
1756        if !question.status.open()
1757            || question.node != crate::conduct::NODE
1758            || questions.held_reply_in(&question.id, &ownership)
1759        {
1760            continue;
1761        }
1762        // Keep questions a task still names, including when the reference
1763        // moved to a dependent task.
1764        // Preserve even ambiguous references: retiring a possibly referenced
1765        // question is unsafe until the operator disambiguates it.
1766        if referenced
1767            .iter()
1768            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1769        {
1770            continue;
1771        }
1772        let Some(task) = by_id.get(question.run.as_str()) else {
1773            continue;
1774        };
1775        question.abandon(format!(
1776            "task {} no longer waits for this answer",
1777            task.short()
1778        ));
1779        if let Err(e) = questions.put_in(&mut question, &ownership) {
1780            tracing::warn!(
1781                "could not retire question {} for task {}: {e:#}",
1782                question.short(),
1783                task.short()
1784            );
1785        }
1786    }
1787}
1788
1789/// What a finished run tells the queue about the task it came from.
1790///
1791/// A struct rather than a fourth and fifth boolean argument: the two flags
1792/// answer different questions about the same run, and a call site passing
1793/// `(…, true, false)` is one transposition away from refunding attempts
1794/// forever.
1795#[derive(Debug, Clone, Copy)]
1796pub struct Verdict {
1797    /// Where the graph stopped.
1798    pub status: RunStatus,
1799    /// The run opened a pull request.
1800    pub left_pr: bool,
1801    /// At least one seat was lost to a rate limit.
1802    pub quota_hit: bool,
1803    /// The run parked at a node boundary because it was asked to.
1804    pub parked: bool,
1805    /// The run never produced a single candidate a judge could look at.
1806    ///
1807    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1808    /// still have another candidate worth judging, in which case the loss was
1809    /// not the reason nothing came of the run. This is `true` only when the
1810    /// implement wave ended with nothing viable at all.
1811    pub no_viable_candidates: bool,
1812}
1813
1814/// Record a finished run against the task it came from.
1815///
1816/// Kept pure and separate from the loop because this mapping *is* the retry
1817/// policy, and a policy that can only be exercised by spawning a graph is a
1818/// policy nobody checks. The table:
1819///
1820/// | run status                           | task becomes        | attempt spent |
1821/// |---------------------------------------|---------------------|---------------|
1822/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1823/// | `Merged`, `Ready`                      | `Done`               | yes          |
1824/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1825/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1826/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1827/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1828/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1829/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1830/// | `Blocked` with a PR                    | `Held`               | yes          |
1831/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1832/// | `VerifiedNoop`                          | `Held`               | yes          |
1833/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1834///
1835/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1836/// deliberately: every candidate agreeing there is nothing to write is not a
1837/// machine fact about a rate limit, it is an unverified claim about the
1838/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1839/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1840/// claim could be wrong (a misread instruction, a stale check), and closing
1841/// the task automatically on an implementer's say-so would be the exact
1842/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1843/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1844/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1845/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1846/// claim regardless of whether the one already-spent attempt is refunded, and
1847/// [`Task::release`] resets the count to zero anyway the moment a human looks
1848/// at the evidence and lets it run again.
1849///
1850/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1851/// twice, together. A quorum lost to rate limits is a property of the machine
1852/// and not of the task, so the attempt is refunded and a reset quota picks
1853/// the work up where it stopped — and that is just as true when every
1854/// implement seat lost the same race and `after_implement` bails with nothing
1855/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1856/// machine fact. The `no_viable_candidates` guard is what keeps that row
1857/// narrow: a `Failed` run that produced a real candidate which then lost for
1858/// some other reason still spends the attempt, exactly like the quorum lost
1859/// to judges that answered with the wrong shape is ordinary flakiness, and
1860/// refunding *that* takes the bound off the retry loop entirely: run e633
1861/// stalled with `quota: []` after two judges wrote unusable JSON, was
1862/// refunded, and the next attempt paid for a fresh hour-long implement wave
1863/// before it could fail the same way. `max_attempts` exists precisely so
1864/// that cannot repeat forever.
1865///
1866/// A non-terminal status means `execute` returned while the graph was still
1867/// mid-flight, which is a bug rather than a verdict; it is treated as a
1868/// failure so that a task cannot loop on it either.
1869///
1870/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1871/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1872pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1873    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1874}
1875
1876/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1877fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1878    // A parked run is the operator's own doing, and its work is intact on
1879    // disk. The task goes back in line with its attempt refunded so the next
1880    // loop resumes the same run - which `one_task` prefers over competing
1881    // again - and so that swapping the binary a few times cannot exhaust a
1882    // budget meant for agents that actually misbehaved.
1883    if verdict.parked {
1884        task.park(detail);
1885        return;
1886    }
1887    match verdict.status {
1888        RunStatus::Merged | RunStatus::Ready
1889            if task.pr_recovery.as_ref().is_some_and(|s| {
1890                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1891            }) =>
1892        {
1893            task.hold_manual(Some("Public delivery is not confirmed. Inspect the selected PR and run, then use recover-pr --disposition land with the intended source and validation configuration.".into()));
1894        }
1895        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1896        RunStatus::AlreadyInBase => task.already_landed(detail),
1897        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1898        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1899            task.stall(detail)
1900        }
1901        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1902        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1903        RunStatus::Blocked => task.fail(detail, max_attempts),
1904        RunStatus::VerifiedNoop => task.handed_off(detail),
1905        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1906    }
1907}
1908
1909/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1910/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1911/// itself has actually finished *and* its own last attempt is provably why:
1912/// this loads that run and requires `Merged`/`Ready` before touching
1913/// anything earlier in `runs`, since `Task::succeed` can also be called
1914/// directly on a task whose last attempt never landed at all.
1915///
1916/// Called right after whatever call set `task.status` to
1917/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1918/// `reclaim`'s, but also every other place a task can be closed by hand
1919/// without the loop ever settling it itself: `magi task done`
1920/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1921/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1922/// GitHub merge, say, exactly the workflow this repository's own
1923/// "Landing a run's winner by hand" documents — is just as much "this task's
1924/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1925/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1926/// forever, which is the exact backlog this status exists to clear. `pub`
1927/// for those two out-of-module callers; everything else about this stays
1928/// internal bookkeeping.
1929///
1930/// A run something is still actually driving is left alone: a
1931/// task cannot be `Done` while one of its *own* attempts is still in flight,
1932/// so a live one at this point can only be an unrelated process — a manual
1933/// `--resume` of this old, now-moot run — and rewriting under it would just
1934/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1935/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1936/// pair `run_report`/`run_detail` use for the same question elsewhere:
1937/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1938/// --resume` invoked by hand outside it, which `liveness` also checks via
1939/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1940/// (already terminal in some other way, or itself mid-run) is left untouched
1941/// too.
1942///
1943/// Best-effort, like the rest of this module's bookkeeping: a load or save
1944/// failure here is a `tracing::warn`, not a failed settle, and the next time
1945/// this same task's completion is recorded — or a daemon restart replays
1946/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1947/// separate reconciliation pass; if that gap ever matters in practice, one
1948/// can be added then.
1949///
1950/// `home` is a parameter, not the process-global [`crate::run::home`], for
1951/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1952/// calls this with `ui.home`, which is `crate::run::home()` in a real
1953/// process but a fixture's own directory under test — falling through to
1954/// the global there would read and write through whichever home some other
1955/// test in the same binary happened to pin into that `OnceLock` first, not
1956/// the run this call actually means.
1957pub fn supersede_prior_runs(task: &Task, home: &Path) {
1958    let now = Timestamp::now();
1959    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1960    // right behind a `Merged`/`Ready` verdict) from one set directly by
1961    // `magi task done`/its web equivalent/the conductor on a task whose last
1962    // recorded attempt never actually landed - that requires reading the
1963    // run itself, which is exactly what this does before trusting anything
1964    // in `runs` is safe to relabel.
1965    let last_run_succeeded = task
1966        .runs
1967        .last()
1968        .and_then(|id| RunState::load_under(id, home).ok())
1969        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1970    for id in task.superseded_attempts(last_run_succeeded) {
1971        let mut state = match RunState::load_under(id, home) {
1972            Ok(s) => s,
1973            Err(e) => {
1974                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1975                continue;
1976            }
1977        };
1978        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1979            continue;
1980        }
1981        let daemon_claims = is_working_on(home, id, now);
1982        if state.liveness(daemon_claims) == Liveness::Live {
1983            continue;
1984        }
1985        state.status = RunStatus::Superseded;
1986        if let Err(e) = state.save_under(home) {
1987            tracing::warn!("could not mark run {id} superseded: {e:#}");
1988        }
1989    }
1990}
1991
1992/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1993/// finish the moment it was called, because one of its earlier attempts was
1994/// still live then - a `magi run --resume` invoked by hand on an old run,
1995/// most likely.
1996///
1997/// That skip is correct at the time (rewriting under a run something is
1998/// still actively saving would just be undone), but a task only ever
1999/// reaches `Done` once, so without this nothing would ever look at it
2000/// again: if that manual process later ends anywhere other than
2001/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
2002/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
2003/// backlog this status exists to clear. Called on the same idle-only
2004/// cadence as [`janitor`], next to it rather than folded into it: this
2005/// walks `queue` and `janitor` never otherwise needs one.
2006///
2007/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
2008/// more than one attempt, every pass: each call is a handful of local file
2009/// reads bounded by that task's own attempt count, the same order of cost
2010/// [`clean::fold_due`] already pays scanning every run on disk on the same
2011/// cadence, and a task already fully resolved costs one failed liveness
2012/// check turned no-op the moment its lingering attempt is no longer live.
2013fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2014    for task in queue.list() {
2015        if task.status != TaskStatus::Done || task.runs.len() < 2 {
2016            continue;
2017        }
2018        supersede_prior_runs(&task, home);
2019    }
2020}
2021
2022/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
2023/// task ends up held.
2024///
2025/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
2026/// dead daemon never got back to) share this, so the two cannot drift into
2027/// disagreeing about which held tasks get a diagnostic.
2028fn settle_and_diagnose(
2029    task: &mut Task,
2030    verdict: Verdict,
2031    detail: &str,
2032    max_attempts: usize,
2033    state: &RunState,
2034) {
2035    let p = phrases(&state.config.graph.language);
2036    // Shared by normal completion and crash recovery, under the task claim.
2037    // No new attempt can own the task until the old driver has exited.
2038    if let Some(d) = &state.merge_decision {
2039        use crate::merge_decision as md;
2040        if task
2041            .execution_runs()
2042            .last()
2043            .is_some_and(|id| id != &state.id)
2044        {
2045            return;
2046        }
2047        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2048            task.succeed();
2049        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2050            if state.liveness(false) != Liveness::Dead {
2051                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2052                return;
2053            }
2054            let replacement = md::Replacement {
2055                question: d.question.clone(),
2056                run: state.id.clone(),
2057                pr: d.target.pr.clone(),
2058                agent: agent.to_owned(),
2059                context: format!(
2060                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2061                    d.target.pr,
2062                    state.id,
2063                    serde_json::to_string(&state.reviews).unwrap_or_default()
2064                ),
2065            };
2066            task.requeue();
2067            task.pr_recovery = None;
2068            task.review_of = None;
2069            task.replacement = Some(replacement);
2070        } else {
2071            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2072                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2073            } else { format!("PR closure was not confirmed. Task held; inspect the existing run before starting replacement work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str())) }));
2074        }
2075        task.mark_action_applied(&d.question);
2076        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2077            task.decision_effects
2078                .insert(d.question.clone(), format!("decision: {}", d.choice));
2079        }
2080        if let Some(pass) = state.passes.last() {
2081            task.record_pass_at(
2082                &state.id,
2083                pass.index,
2084                Some(pass.started_at),
2085                task.attempts,
2086                None,
2087            );
2088        }
2089        return;
2090    }
2091    if let Some(replacement) = &task.replacement
2092        && !state.parked
2093        && state.resource_block.is_none()
2094        && (state.viable().is_empty()
2095            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2096    {
2097        task.hold_manual(Some(format!("Selected implementer `{}` was unavailable, failed or hit quota before producing a viable implementation. No other implementer was dispatched. Inspect the run, restore availability, then explicitly release this task.", replacement.agent)));
2098        return;
2099    }
2100    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2101        let mut agents: Vec<_> = state
2102            .quota
2103            .iter()
2104            .filter(|q| {
2105                q.cause == crate::agent::QuotaCause::Authentication
2106                    && state
2107                        .passes
2108                        .last()
2109                        .is_none_or(|pass| q.at >= pass.started_at)
2110            })
2111            .map(|q| q.agent.as_str())
2112            .collect();
2113        agents.sort_unstable();
2114        agents.dedup();
2115        if !agents.is_empty() {
2116            task.stall(detail);
2117            task.notice_cause("agent-authentication", None, None);
2118            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2119            return;
2120        }
2121    }
2122    let attempts_before = task.attempts;
2123    // A run that stopped because a shared resource stayed busy was never a
2124    // failure of the task or of an agent. Earlier nodes may have run; only
2125    // the blocked operation lacks a result. The attempt is
2126    // refunded and the task is held by the machine, under a reason `triage`
2127    // can re-check, so the same run resumes with the same agents once the
2128    // resource is free. A park request still wins (it is the operator's).
2129    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2130        let disk_checked_at = task.disk_checked_at;
2131        task.notice_cause(
2132            &format!("resource:{}:{}", block.kind, block.node),
2133            None,
2134            None,
2135        );
2136        task.last_error = Some(detail.to_owned());
2137        task.diagnostic = None;
2138        task.attempts = task.attempts.saturating_sub(1);
2139        if block.kind == "agent authentication" {
2140            task.hold_machine(Some(format!(
2141                "[authentication] {}; no attempt was spent",
2142                block.detail
2143            )));
2144        } else if block.kind == "agent usage limit" {
2145            // Usage limits keep the existing cooldown-and-resume policy.
2146            if let Some(agent) = &state.config.graph.selected_implementer {
2147                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.")));
2148            } else {
2149                task.status = TaskStatus::Failed;
2150                task.last_error = Some(block.detail.clone());
2151            }
2152        } else if block.kind == "disk pressure" {
2153            task.hold_machine(Some(format!(
2154                "{}{}",
2155                crate::disk::RUNNING_PRESSURE,
2156                block.detail
2157            )));
2158        } else {
2159            task.hold_machine(Some(format!(
2160                "{}{}; no attempt was spent; resume to retry the affected operation",
2161                crate::cache::RESOURCE_HOLD,
2162                block.description()
2163            )));
2164        }
2165        if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2166            && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2167        {
2168            task.mark_disk_capacity();
2169            task.disk_checked_at = disk_checked_at;
2170        }
2171        if let Some(pass) = state.passes.last() {
2172            task.record_pass_at(
2173                &state.id,
2174                pass.index,
2175                Some(pass.started_at),
2176                attempts_before,
2177                None,
2178            );
2179        }
2180        return;
2181    }
2182    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2183        state.parked
2184            && state.status == RunStatus::Landing
2185            && state
2186                .pr_pushed_head
2187                .as_ref()
2188                .is_none_or(|h| h == &hold.head)
2189            && task.execution_runs().last() == Some(&state.id)
2190    }) {
2191        // Settlement and crash recovery share this idempotency key. A later
2192        // explicit resume is a new pass and may refund its own attempt once.
2193        let pass = state.passes.last().map_or(0, |p| p.index);
2194        if !task
2195            .passes
2196            .iter()
2197            .any(|p| p.run == state.id && p.pass_index == pass)
2198        {
2199            task.attempts = task.attempts.saturating_sub(1);
2200        }
2201        task.hold_machine(Some(format!(
2202            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2203            hold.question
2204        )));
2205        task.last_error = Some(detail.to_owned());
2206        task.diagnostic = None;
2207        task.record_pass_at(
2208            &state.id,
2209            pass,
2210            state.passes.last().map(|p| p.started_at),
2211            attempts_before,
2212            Some(crate::run::ParkCause::Question),
2213        );
2214        return;
2215    }
2216    let unresolved = task.hold_notice_cause.clone();
2217    if state.base_sync_blocked() {
2218        // No automatic retry may turn a retained sync stop into a new competition.
2219        task.hold_machine(Some(detail.to_owned()));
2220        task.last_error = Some(detail.to_owned());
2221    } else if !verdict.parked
2222        && task
2223            .pr_recovery
2224            .as_ref()
2225            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2226        && matches!(
2227            verdict.status,
2228            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2229        )
2230    {
2231        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2232            task.succeed();
2233        } else {
2234            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()));
2235        }
2236    } else if !verdict.parked
2237        && task.pr_recovery.is_some()
2238        && matches!(
2239            verdict.status,
2240            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2241        )
2242        && !verdict.quota_hit
2243    {
2244        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.")));
2245    } else {
2246        settle_in(task, verdict, detail, max_attempts, p);
2247    }
2248    if !verdict.parked
2249        && !verdict.quota_hit
2250        && matches!(
2251            verdict.status,
2252            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2253        )
2254    {
2255        task.recovery_failed(state);
2256    }
2257    if state.prep_failure.is_some() {
2258        // Minting a run whose candidates could not be prepared is not work
2259        // on a newly approved attempt. Keep the unresolved outcome anchor.
2260        task.hold_notice_cause = unresolved;
2261        task.startup_notice_cause("startup-candidates");
2262    }
2263    // Written here, where the refund (or not) is decided, so the history is a
2264    // fact and not a later guess from the run's status.
2265    if let Some(pass) = state.passes.last() {
2266        let parked = match &pass.end {
2267            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2268            _ => None,
2269        };
2270        task.record_pass_at(
2271            &state.id,
2272            pass.index,
2273            Some(pass.started_at),
2274            attempts_before,
2275            parked,
2276        );
2277    }
2278    if task.status == TaskStatus::Held {
2279        if state.base_sync_blocked() {
2280            task.base_sync_notice(state);
2281        } else if state.prep_failure.is_none() {
2282            task.notice_cause(
2283                label(verdict.status),
2284                Some(&state.id),
2285                state.passes.last().map(|p| p.index),
2286            );
2287        }
2288        task.diagnostic = diagnostic(state);
2289        note_open_question(task, &state.id, p);
2290    }
2291}
2292
2293/// If `task` is held with a `magi ask` question still open on `run`, name the
2294/// question in [`Task::hold_reason`] rather than leaving the hold reading
2295/// only [`describe`]'s run summary.
2296///
2297/// This is the shape task 20260928-191407-05fd left underspecified: an
2298/// implementer settled a verified no-op and filed a question for the
2299/// operator, and the hold that followed said nothing about the question
2300/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2301/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2302/// marker) and must keep seeing it unchanged.
2303///
2304/// Best-effort: an unreadable question store must not stop a run from
2305/// settling, so this is a no-op rather than a propagated error when
2306/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2307fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2308    let Some(home) = crate::run::try_home() else {
2309        return;
2310    };
2311    let open = Questions::at(home.join("questions")).open_for(run);
2312    let Some(q) = open.first() else {
2313        return;
2314    };
2315    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2316    decisions.sort_unstable();
2317    task.notice_cause(
2318        &format!("questions:{}", decisions.join(",")),
2319        Some(run),
2320        None,
2321    );
2322    let base = task.hold_reason.clone().unwrap_or_default();
2323    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2324}
2325
2326/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2327/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2328/// by some other means entirely, like a manual `magi run` resume that
2329/// finishes the graph outside the queue's bookkeeping.
2330///
2331/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2332/// `settle` is separate from `attempt`: a task recovered this way must land
2333/// exactly where a live daemon would have put it — the same policy table,
2334/// not a second one that quietly drifts from it — and that is only checkable
2335/// without spawning a real run.
2336fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2337    match last_run {
2338        Some(state) => {
2339            let verdict = Verdict {
2340                status: state.status,
2341                left_pr: state.pr.is_some(),
2342                quota_hit: state.quota.iter().any(|loss| {
2343                    state
2344                        .passes
2345                        .last()
2346                        .is_none_or(|pass| loss.at >= pass.started_at)
2347                }),
2348                parked: state.parked,
2349                no_viable_candidates: state.viable().is_empty(),
2350            };
2351            let detail = format!(
2352                "{}{}",
2353                phrases(&state.config.graph.language).recovered_running,
2354                describe(&state)
2355            );
2356            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2357        }
2358        None => {
2359            // No run, so no config of its own: `language` is the task's
2360            // repository's setting, read by the caller.
2361            let why = phrases(language).no_run_to_recover;
2362            task.last_error = Some(why.to_owned());
2363            // The phone shows `hold_reason`, so a task held by the machine
2364            // says why there too and not only in `last_error`.
2365            task.notice_cause("missing-run", None, None);
2366            task.hold_machine(Some(why.to_owned()));
2367        }
2368    }
2369}
2370
2371/// Find every task left at `running` that no live process is actually
2372/// driving, and settle each one against whatever its last run became.
2373///
2374/// # Why a claim is proof, not a guess
2375///
2376/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2377/// `running`, and the guard is held for the task's whole time in that status:
2378/// `attempt` does not return, and the loop does not move past the scope
2379/// holding the claim, until the run has settled. So a `running` task whose
2380/// lock is gone cannot have a live owner — this process or any other —
2381/// without needing a staleness threshold or a pid check the way
2382/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2383/// task that never got as far as `running` at all. Taking the claim here is
2384/// the whole test: it either fails, because something really does hold it
2385/// and the task is left alone, or it succeeds, which is the proof — and it is
2386/// kept for the rest of the decision so nothing else can start a competing
2387/// run while this one is being written.
2388///
2389/// Called on every poll, not only at startup, for the reason
2390/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2391/// keep noticing this, not only on the one morning it happened to restart.
2392fn reclaim_orphaned_running(
2393    queue: &Queue,
2394    max_attempts: usize,
2395    live_workers: &std::collections::BTreeSet<String>,
2396) -> Vec<String> {
2397    let mut reclaimed = Vec::new();
2398    for listed in queue.list() {
2399        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2400            continue;
2401        }
2402        let Ok(_claim) = queue.claim(&listed.id) else {
2403            continue;
2404        };
2405        // Re-read under the claim: a release or an edit landed by a human
2406        // between the listing above and the claim just taken must not be
2407        // clobbered by a decision based on the stale copy.
2408        let Ok(mut task) = queue.get(&listed.id) else {
2409            continue;
2410        };
2411        if task.status != TaskStatus::Running {
2412            continue;
2413        }
2414        let last_run = task
2415            .execution_runs()
2416            .last()
2417            .and_then(|id| RunState::load(id).ok());
2418        // `execute` normally abandons a run's own open questions the moment
2419        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2420        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2421        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2422        // with the question still `open`, because the process died before
2423        // reaching that call. `reclaim` itself stays pure on purpose (see its
2424        // own doc), so the same cleanup runs here instead, against the run
2425        // this reclaim is already reading. `settle_run` costs nothing when
2426        // `execute` already got there first.
2427        if let Some(state) = &last_run
2428            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2429        {
2430            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2431        }
2432        let language = if last_run.is_none() {
2433            language_of(&task, Path::new("."))
2434        } else {
2435            String::new()
2436        };
2437        reclaim(&mut task, last_run, max_attempts, &language);
2438        if task.status == TaskStatus::Done {
2439            supersede_prior_runs(&task, &crate::run::home());
2440        }
2441        record(queue, &mut task);
2442        reclaimed.push(task.id.clone());
2443    }
2444    reclaimed
2445}
2446
2447/// Find every run whose `run.json` is provably dead — every seat it still
2448/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2449/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2450/// not merely "no daemon claims it" — and fail it, clearing the leftover
2451/// active seats so the run stops reading as `implementing` (or whichever
2452/// node) forever.
2453///
2454/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2455/// `running`, using whatever `run.json` already says — but nothing in that
2456/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2457/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2458/// never got back to sits exactly where it was left: `active` full of seats
2459/// nobody will ever answer for, `status` stuck on whatever node was in
2460/// flight. `magi show` already tells an operator this in prose (`no live
2461/// daemon claims this run right now`); this is what makes that fact durable
2462/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2463/// stay stuck once nothing is driving it.
2464///
2465/// Runs on every poll, not only at startup, for the reason
2466/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2467/// daemon up for days must keep noticing a run some other, now-dead, daemon
2468/// left behind just as readily as one it trips over on the way up.
2469///
2470/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2471/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2472/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2473/// `runs` directory instead: `home` here is a parameter precisely so a test
2474/// can point it away from the operator's real history (see [`drive`]'s own
2475/// doc), and a scan that fell through to the global home anyway would walk
2476/// whichever directory some *other* process or test pinned into that
2477/// `OnceLock` first — mutating runs this call was never handed.
2478fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2479    reclaim_abandoned_runs_with(
2480        home,
2481        now,
2482        crate::proc::pid_status,
2483        crate::proc::process_started_at,
2484    )
2485}
2486
2487/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2488/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2489/// for the identical reason: this sweep's real damage (wiping a run's active
2490/// seats and failing it) has to be provable against an injected answer in a
2491/// test, not just the real process table.
2492fn reclaim_abandoned_runs_with<F, G>(
2493    home: &Path,
2494    now: Timestamp,
2495    query: F,
2496    identity: G,
2497) -> Vec<String>
2498where
2499    F: Fn(u32) -> Option<bool>,
2500    G: Fn(u32) -> Option<String>,
2501{
2502    let mut abandoned = Vec::new();
2503    for entry in std::fs::read_dir(home.join("runs"))
2504        .into_iter()
2505        .flatten()
2506        .flatten()
2507    {
2508        let id = entry.file_name().to_string_lossy().into_owned();
2509        if !crate::run::is_run_id(&id) {
2510            continue;
2511        }
2512        // Serialize the proof and save with claims and takeover: a new
2513        // execution must not be overwritten after the liveness observation.
2514        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2515            continue;
2516        };
2517        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2518        // that module's docs for why a run this cannot parse is left alone
2519        // rather than guessed at. A different schema number is not that: this
2520        // touches only `status` and `active`, never a field whose meaning a
2521        // schema bump changed, so an old record's values serve this exactly
2522        // as well as a current one's (see `clean::read_state`'s own doc for
2523        // the same reasoning applied to folding).
2524        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2525            continue;
2526        };
2527        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2528            continue;
2529        };
2530        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2531            continue;
2532        }
2533        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2534        // it", which is also the normal, healthy shape of a manual `magi
2535        // run` / `magi review` sharing this same home — this scan walks
2536        // every run on disk, not only ones this daemon itself started. Such
2537        // a run's active seats can legitimately sit past their own timeout
2538        // for a little while (the CLI finishing up, its result still being
2539        // collected) without the process driving it having died. `liveness`
2540        // is what actually tells the two apart, by corroborating
2541        // `driver_pid` against the process it names — see its own doc. Only
2542        // its strongest, provable answer licenses wiping this run's active
2543        // seats and failing it out from under whatever is still running it.
2544        let daemon_claims = is_working_on(home, &id, now);
2545        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2546            != crate::run::Liveness::Dead
2547        {
2548            continue;
2549        }
2550        state.abandon("daemon");
2551        if let Err(e) = state.save_under(home) {
2552            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2553            continue;
2554        }
2555        // This run never passes through `Runner::execute` again, so its end
2556        // is announced here.
2557        if let Some(notice) = notices::run_ended(&state) {
2558            notices::raise_in(home, notice);
2559        }
2560        // The seat that asked is gone for good now, exactly like any other
2561        // door `graph::Runner::settle_questions` closes the moment `status`
2562        // lands somewhere non-resumable - see that method's own doc. Nothing
2563        // else reaches this one before the next `janitor()` startup pass
2564        // (`clean::abandon_settled_questions`), and a daemon that stays up
2565        // for days must not leave an open question badging the operator
2566        // until it happens to restart.
2567        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2568            tracing::warn!("abandon questions for {id}: {e:#}");
2569        }
2570        abandoned.push(id);
2571    }
2572    abandoned
2573}
2574
2575#[derive(Debug, Clone, Serialize, Deserialize)]
2576struct TaskWorker {
2577    opts: Opts,
2578    queue: PathBuf,
2579    task: String,
2580    #[serde(default)]
2581    lane: PermitKind,
2582    #[serde(default)]
2583    standalone: bool,
2584}
2585
2586fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2587    Ok(crate::worker::active(home)?
2588        .into_iter()
2589        .filter(|job| job.kind == "task")
2590        .collect())
2591}
2592
2593fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2594    task_jobs(home)?
2595        .into_iter()
2596        .filter_map(
2597            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2598                Ok(request) if !request.standalone => Some(Ok(job)),
2599                Ok(_) => None,
2600                Err(error) => Some(Err(error.into())),
2601            },
2602        )
2603        .collect()
2604}
2605
2606/// Whether an independent scheduler can be controlled without its web parent.
2607#[must_use]
2608pub fn managed(home: &Path) -> bool {
2609    match crate::worker::active(home) {
2610        Err(error) => {
2611            tracing::error!("cannot determine scheduler ownership: {error:#}");
2612            true
2613        }
2614        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2615        Ok(_) => {
2616            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2617                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2618        }
2619    }
2620}
2621
2622/// Start a detached, singleton scheduler using this executable generation.
2623pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2624    anyhow::ensure!(
2625        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2626        "the scheduler is stopping; wait for retirement before starting it again"
2627    );
2628    crate::worker::spawn(
2629        home,
2630        "scheduler",
2631        "scheduler",
2632        serde_json::to_value(opts.absolute()?)?,
2633    )
2634    .await
2635}
2636
2637fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2638    home.join("worker-parks").join(format!("{}.json", job.id))
2639}
2640
2641fn request_task_park(
2642    home: &Path,
2643    job: &crate::worker::Job,
2644    cause: crate::run::ParkCause,
2645) -> Result<()> {
2646    let path = park_request_path(home, job);
2647    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2648    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2649    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2650}
2651
2652/// Stop dispatch immediately; only an explicit park reaches existing workers.
2653pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2654    if control == crate::worker::Control::Park {
2655        for job in owned_task_jobs(home)? {
2656            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2657        }
2658    }
2659    crate::worker::request(home, "scheduler", control)
2660}
2661
2662/// Replace the scheduler, leaving all active task and conversation jobs alone.
2663pub async fn restart_detached(home: &Path) -> Result<()> {
2664    let active = crate::worker::active(home)?;
2665    let prior = active.into_iter().find(|job| job.kind == "scheduler");
2666    if prior.is_none() && !managed(home) {
2667        return Ok(());
2668    }
2669    let opts: Opts = match prior {
2670        Some(job) => serde_json::from_value(job.payload)?,
2671        None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2672    };
2673    request_control(home, crate::worker::Control::Stop)?;
2674    loop {
2675        let reserved = crate::worker::active(home)?
2676            .iter()
2677            .any(|job| job.kind == "scheduler");
2678        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2679            break;
2680        }
2681        tokio::time::sleep(Duration::from_millis(100)).await;
2682    }
2683    spawn_detached(home, &opts).await?;
2684    Ok(())
2685}
2686
2687/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2688pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2689    let opts: Opts = serde_json::from_value(payload)?;
2690    let _ = home;
2691    serve_until(opts, Stop::new()).await
2692}
2693
2694/// Execute and settle one task with the queue claim owned by this process.
2695pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2696    let request: TaskWorker = serde_json::from_value(payload)?;
2697    let queue = Queue::at(request.queue);
2698    let key = format!("task:{}", request.task);
2699    let job = task_jobs(home)?
2700        .into_iter()
2701        .find(|job| job.key == key)
2702        .context("task worker reservation is missing")?;
2703    let park_path = park_request_path(home, &job);
2704    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2705    // our durable reservation. Never execute before that ownership hand-off.
2706    let _claim = loop {
2707        match queue.claim(&request.task) {
2708            Ok(claim) => break claim,
2709            // Only contention (the claim file exists) is worth waiting out; an
2710            // I/O failure must end this worker instead of pinning its lane.
2711            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2712                return Err(e.context("claim the task for its worker"));
2713            }
2714            Err(_) => {
2715                sweep_stale_claims(&queue, STALE_CLAIM);
2716                tokio::time::sleep(Duration::from_millis(50)).await;
2717            }
2718        }
2719    };
2720    let mut task = queue.get(&request.task)?;
2721    if !task.status.runnable()
2722        || (!request.standalone
2723            && request.lane
2724                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2725    {
2726        return Ok(());
2727    }
2728    let stop = Stop::new();
2729    let watcher = {
2730        let home = home.to_path_buf();
2731        let stop = stop.clone();
2732        let park_path = park_path.clone();
2733        tokio::spawn(async move {
2734            loop {
2735                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2736                    let cause = std::fs::read(&park_path)
2737                        .ok()
2738                        .and_then(|body| serde_json::from_slice(&body).ok())
2739                        .unwrap_or(crate::run::ParkCause::Operator);
2740                    stop.park(cause);
2741                    return;
2742                }
2743                tokio::time::sleep(Duration::from_millis(200)).await;
2744            }
2745        })
2746    };
2747    let quota = if request.standalone {
2748        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2749    } else {
2750        let status = Arc::new(Mutex::new(Status::new()));
2751        Box::pin(attempt(
2752            &request.opts,
2753            &queue,
2754            &status,
2755            &stop,
2756            crate::graph::Pause::new(),
2757            &mut task,
2758        ))
2759        .await
2760    };
2761    watcher.abort();
2762    let _ = std::fs::remove_file(park_path);
2763    persist_cooldown(home, &quota).await?;
2764    Ok(())
2765}
2766
2767/// Launch the standalone task worker with a claim-to-reservation handoff.
2768/// Returns only after the worker owns a durable execution reservation.
2769pub async fn spawn_claimed(
2770    home: &Path,
2771    opts: &Opts,
2772    queue: &Queue,
2773    task: &Task,
2774    claim: crate::queue::Claim,
2775) -> Result<crate::worker::Job> {
2776    let request = TaskWorker {
2777        opts: opts.absolute()?,
2778        queue: std::path::absolute(queue.root())?,
2779        task: task.id.clone(),
2780        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2781        standalone: true,
2782    };
2783    let job = crate::worker::spawn(
2784        home,
2785        "task",
2786        &format!("task:{}", task.id),
2787        serde_json::to_value(request)?,
2788    )
2789    .await?;
2790    drop(claim);
2791    Ok(job)
2792}
2793
2794/// Transfer a standalone caller's claim only after the detached worker is live,
2795/// then follow that worker to its final (non-automatically-retrying) outcome.
2796pub async fn run_detached_claimed(
2797    opts: &Opts,
2798    queue: &Queue,
2799    task: &mut Task,
2800    claim: crate::queue::Claim,
2801) -> Result<()> {
2802    let home = crate::run::home();
2803    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2804    loop {
2805        // Reconcile execution leases even without a scheduler. A dead worker
2806        // must become a reported failure, never an infinite persisted wait.
2807        crate::worker::active(&home)?;
2808        let current = crate::worker::get(&home, &job.id)?;
2809        if matches!(
2810            current.status,
2811            crate::worker::Status::Finished | crate::worker::Status::Failed
2812        ) {
2813            *task = queue.get(&task.id)?;
2814            anyhow::ensure!(
2815                current.status != crate::worker::Status::Failed,
2816                "task worker failed: {}",
2817                current.result.as_deref().unwrap_or("unknown failure")
2818            );
2819            return Ok(());
2820        }
2821        tokio::time::sleep(Duration::from_millis(200)).await;
2822    }
2823}
2824
2825async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2826    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2827        let _lease = loop {
2828            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2829                break lease;
2830            }
2831            tokio::time::sleep(Duration::from_millis(10)).await;
2832        };
2833        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2834            let path = home.join("task-quota-cooldown.json");
2835            let temporary = path.with_extension("json.tmp");
2836            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2837            std::fs::rename(temporary, path)?;
2838        }
2839    }
2840    Ok(())
2841}
2842
2843fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2844    match std::fs::read(home.join("task-quota-cooldown.json")) {
2845        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2846        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2847        Err(error) => Err(error.into()),
2848    }
2849}
2850
2851/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2852///
2853/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2854/// sets, so there is one loop body rather than two that drift apart the first
2855/// time the retry policy changes on only one of them.
2856pub async fn serve(opts: Opts) -> Result<()> {
2857    tracing::info!(
2858        "automatic update and restart requires magi web; standalone serve does not restart"
2859    );
2860    serve_until(opts, Stop::new()).await
2861}
2862
2863/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2864///
2865/// A stop retires dispatch promptly, including while a worker launch is being
2866/// acknowledged. Already reserved workers own their attempts independently and
2867/// finish with their started executable. Explicit park additionally forwards
2868/// durable park requests; neither scheduler retirement nor update does so.
2869///
2870/// While the queue is empty the stop is honoured within one wakeup rather than
2871/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2872/// caller that taps stop does not sit through the remainder of a sleep.
2873pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2874    let opts = opts.absolute()?;
2875    let home = crate::run::home();
2876    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2877        .context("another scheduler already owns this home")?;
2878    if let Some(reading) = read_status(&home)
2879        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2880    {
2881        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2882    }
2883    if !crate::worker::active(&home)?
2884        .iter()
2885        .any(|job| job.kind == "scheduler")
2886    {
2887        crate::worker::clear_control(&home, "scheduler")?;
2888    }
2889    std::fs::write(
2890        home.join("scheduler-options.json"),
2891        serde_json::to_vec(&opts)?,
2892    )?;
2893    let control = {
2894        let home = home.clone();
2895        let stop = stop.clone();
2896        tokio::spawn(async move {
2897            loop {
2898                match crate::worker::control(&home, "scheduler").ok().flatten() {
2899                    Some(crate::worker::Control::Park) => {
2900                        let _ = request_control(&home, crate::worker::Control::Park);
2901                        stop.park(crate::run::ParkCause::Operator);
2902                        break;
2903                    }
2904                    Some(crate::worker::Control::Stop) => {
2905                        stop.stop();
2906                        break;
2907                    }
2908                    None => {}
2909                }
2910                tokio::time::sleep(Duration::from_millis(100)).await;
2911            }
2912        })
2913    };
2914    let signal = {
2915        let stop = stop.clone();
2916        tokio::spawn(async move {
2917            if tokio::signal::ctrl_c().await.is_ok() {
2918                stop.stop();
2919                tracing::info!("scheduler shutdown requested; independent workers continue");
2920            }
2921        })
2922    };
2923
2924    let worktrees_root = opts
2925        .worktrees_root
2926        .clone()
2927        .unwrap_or_else(crate::run::default_worktree_root);
2928    let outcome = drive(
2929        &opts,
2930        &Queue::open(),
2931        &status_path(),
2932        &crate::run::home(),
2933        &worktrees_root,
2934        &stop,
2935    )
2936    .await;
2937
2938    signal.abort();
2939    control.abort();
2940    outcome
2941}
2942
2943/// The loop proper: setup, poll, teardown, with the queue and the status file
2944/// supplied rather than discovered.
2945///
2946/// All three of `home`, `worktrees_root` and the queue/status paths are
2947/// parameters rather than resolved here, for the same reason:
2948/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2949/// so a unit test that pinned it would fight every other test in the binary,
2950/// and a loop that resolved its own worktree bay could only be exercised
2951/// against the operator's real `~/wt/<repo>` - publishing over a live
2952/// daemon's status file, claiming tasks out of a live backlog, and, since
2953/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2954/// whatever the operator actually has on disk.
2955async fn drive(
2956    opts: &Opts,
2957    queue: &Queue,
2958    status_file: &Path,
2959    home: &Path,
2960    worktrees_root: &Path,
2961    stop: &Stop,
2962) -> Result<()> {
2963    // The status file is a *snapshot*, not a stream of events: a reader only
2964    // ever wants the latest values, and every tick rewrites the whole file
2965    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2966    // while an mpsc channel would force the loop to re-send unchanged fields on
2967    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2968    // for no gain. The lock is only ever held across a field assignment, never
2969    // across an await.
2970    let recovery_cfg = prepare(&opts.repo, opts).ok();
2971    let daemon_cfg = recovery_cfg
2972        .as_ref()
2973        .map(|c| c.daemon.clone())
2974        .unwrap_or_default();
2975    let reconciled = crate::driver::reconcile(home);
2976    if !reconciled.is_empty() {
2977        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2978    }
2979    let mut initial_status = Status::new();
2980    let owned = owned_task_jobs(home)?;
2981    initial_status.current = current_work(home, Timestamp::now())
2982        .into_iter()
2983        .filter(|current| {
2984            owned
2985                .iter()
2986                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2987        })
2988        .collect();
2989    initial_status.idle = initial_status.current.is_empty();
2990    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2991        recovery_cfg.as_ref(),
2992        daemon_cfg.max_deputies,
2993    ));
2994    let status = Arc::new(Mutex::new(initial_status));
2995    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2996    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2997
2998    // Read once at startup, not per task: how many runs this loop drives at
2999    // once is a property of the machine running it, not of whichever
3000    // repository a given task happens to name - see
3001    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
3002    // fact in the same sense the agent roster is.
3003    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3004
3005    tracing::info!(
3006        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3007        queue.root().display(),
3008        opts.poll.as_secs(),
3009        opts.max_attempts,
3010        concurrency,
3011        if daemon_cfg.pause_for_interrupts {
3012            ", interrupts enabled"
3013        } else {
3014            ""
3015        }
3016    );
3017
3018    let outcome = tokio::select! {
3019        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3020            max_concurrent: concurrency,
3021            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3022            recovery_cfg,
3023        }) => outcome,
3024        () = async {
3025            while !stop.stopped() {
3026                tokio::time::sleep(Duration::from_millis(25)).await;
3027            }
3028        } => {
3029            if stop.parking() {
3030                request_control(home, crate::worker::Control::Park)?;
3031            }
3032            Ok(())
3033        }
3034    };
3035
3036    stop.busy.store(0, Ordering::SeqCst);
3037    beat.abort();
3038    clear_status_at(status_file);
3039    outcome
3040}
3041
3042/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3043/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3044pub(crate) fn release_watch_settings_from_config(
3045    home: &Path,
3046    repo: &Path,
3047    cfg: &Config,
3048) -> (Vec<PathBuf>, u64) {
3049    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3050        .into_iter()
3051        .map(|r| r.path)
3052        .collect();
3053    // Repositories the daemon has worked in, wherever they live: a task may
3054    // name one outside `[repos] roots`, and its release PR must be watched too.
3055    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3056        .list()
3057        .into_iter()
3058        .map(|t| t.repo)
3059        .collect();
3060    let runs = home.join("runs");
3061    for id in crate::run::list_ids_in(&runs) {
3062        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3063            .ok()
3064            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3065            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3066        known.extend(repo);
3067    }
3068    for k in known {
3069        let k = k.canonicalize().unwrap_or(k);
3070        if k.join(".git").exists() && !paths.contains(&k) {
3071            paths.push(k);
3072        }
3073    }
3074    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3075    if !paths.contains(&own) {
3076        paths.push(own);
3077    }
3078    (paths, cfg.daemon.release_stall_minutes)
3079}
3080
3081/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3082const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3083
3084/// Refresh the status file on a fixed tick.
3085///
3086/// Separate from the loop because a run takes tens of minutes: a status file
3087/// written only between tasks would look stale for the whole of every run, and
3088/// a reader would report the daemon dead exactly while it was busiest.
3089async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3090    loop {
3091        tokio::time::sleep(HEARTBEAT).await;
3092        let snapshot = {
3093            let mut guard = lock(&status);
3094            guard.updated_at = Timestamp::now();
3095            guard.clone()
3096        };
3097        if let Err(e) = write_status_to(&path, &snapshot) {
3098            // A failed heartbeat must not take the daemon down: the loop is the
3099            // product, the status file is only the window onto it.
3100            tracing::warn!("could not refresh the daemon status file: {e:#}");
3101        }
3102    }
3103}
3104
3105/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3106/// if so, whether that wait is over.
3107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3108enum LandResume {
3109    /// The task's last run is not parked on a land approval; schedule it
3110    /// like any other candidate.
3111    NotLanding,
3112    /// Parked in `land`, waiting on a question nobody has answered yet.
3113    /// Left alone: attempting it now would only re-observe the same pull
3114    /// request and park again, spending a `gh` call on a decision that has
3115    /// not changed since the last time this was checked.
3116    StillWaiting,
3117    /// Parked in `land`, and the question is settled - answered or
3118    /// abandoned. Resuming this is the one kind of candidate that must not
3119    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3120    Ready,
3121}
3122
3123/// Classify a runnable candidate by whether it is parked on a land-merge
3124/// approval. Read-only - no claim taken, nothing written - so it is cheap
3125/// enough to call on every candidate, every poll.
3126fn land_resume_state(task: &Task) -> LandResume {
3127    let Some(run_id) = task.execution_runs().last() else {
3128        return LandResume::NotLanding;
3129    };
3130    let Ok(state) = RunState::load(run_id) else {
3131        return LandResume::NotLanding;
3132    };
3133    if !state.parked {
3134        return LandResume::NotLanding;
3135    }
3136    if state.status == RunStatus::Landing
3137        && state.land_approval.as_ref().is_some_and(|binding| {
3138            ask::Questions::open()
3139                .get_for_effects(&binding.question)
3140                .is_ok_and(|q| {
3141                    q.run == state.id
3142                        && q.resolution()
3143                            .as_deref()
3144                            .is_some_and(crate::merge_decision::stops)
3145                })
3146        })
3147    {
3148        return LandResume::Ready;
3149    }
3150    if !implementers_match(task, &state) {
3151        return LandResume::NotLanding;
3152    }
3153    // Parked in `land` on the merge approval, or at `merge` on the owner's
3154    // word about a title/body the posting gate withheld. Told apart by the
3155    // run's own record, not by a status both can share.
3156    let node = if state.status == RunStatus::Landing {
3157        land::APPROVAL_NODE
3158    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3159        crate::github_text::ASK_NODE
3160    } else {
3161        return LandResume::NotLanding;
3162    };
3163    let store = ask::Questions::open();
3164    let waiting = store
3165        .list_for_effects()
3166        .into_iter()
3167        .filter(|q| &q.run == run_id && q.node == node)
3168        .max_by(|a, b| a.id.cmp(&b.id));
3169    let Some(mut q) = waiting else {
3170        return LandResume::Ready;
3171    };
3172    if !q.status.open() {
3173        // Repair spends agent resources and must obey concurrency and quota
3174        // waits; only a merge/hold decision may use the decision-only lane.
3175        if q.resolution().as_deref() == Some(land::REPAIR) {
3176            return if state.liveness(false) == Liveness::Live {
3177                LandResume::StillWaiting
3178            } else {
3179                LandResume::NotLanding
3180            };
3181        }
3182        return LandResume::Ready;
3183    }
3184    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3185    // nobody ever answered; land's approval bypasses that wait entirely (see
3186    // `land::approval_gate`), so the same deadline has to be enforced here
3187    // instead, or `graph.answer_timeout` silently stops meaning anything for
3188    // a land approval and a run can sit `StillWaiting` forever with nobody
3189    // told to look at it.
3190    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3191    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3192    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3193        q.abandon(format!(
3194            "no answer within {}s of asking",
3195            timeout.as_secs().max(1)
3196        ));
3197        // If this can't be persisted, do not treat the wait as settled on a
3198        // guess: fall through and try again next poll.
3199        if store.put(&mut q).is_ok() {
3200            return LandResume::Ready;
3201        }
3202    }
3203    LandResume::StillWaiting
3204}
3205
3206/// How often the loop rechecks for new work while something it already
3207/// started is still running, rather than sleeping out the whole
3208/// [`Opts::poll`] interval.
3209///
3210/// Short on purpose: this is what lets a land-merge approval that comes back
3211/// while another task is mid-competition be noticed and resumed within a
3212/// fraction of a second, not within the next multi-second poll.
3213const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3214
3215/// How often [`poll`] rechecks the shared build cache against its cap at a
3216/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3217/// waiting for the queue to run dry.
3218///
3219/// A queue that never empties means the `janitor` call at the bottom of this
3220/// loop's fully-idle branch can go unreached for as long as the backlog
3221/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3222/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3223/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3224/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3225/// backlog of short tasks does not pay for that walk on every poll.
3226const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3227
3228/// State of [`poll`]'s own interrupt-scheduling sequence - see
3229/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3230/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3231/// both kept free of `Task`'s non-identity fields on purpose: every decision
3232/// here turns only on task ids and which ones are in flight, so the "never
3233/// more than one run at once" and "exactly one resume" invariants can be
3234/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3235/// queue - which is exactly the coverage this feature's first two attempts
3236/// were missing.
3237///
3238/// Persisted after every transition, so scheduler replacement preserves the
3239/// interrupt's exclusive turn and the interrupted task's priority resume.
3240#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3241enum Interrupt {
3242    /// No interrupt sequence in progress. Ordinary dispatch applies.
3243    Idle,
3244    /// `interrupt_task` is runnable and exactly one other run is in flight;
3245    /// `parked` names that one task's id. Dispatch is withheld from
3246    /// everyone, including `interrupt_task` itself, until it has left
3247    /// flight - only then is `interrupt_task` let through.
3248    ///
3249    /// `parked` is a `Vec` rather than a bare id for symmetry with
3250    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3251    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3252    /// when exactly one run is in flight, so it is guaranteed to hold
3253    /// exactly one entry in practice - see that branch's own doc for why
3254    /// more than one is deliberately never attempted.
3255    Parking {
3256        parked: Vec<String>,
3257        interrupt_task: String,
3258    },
3259    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3260    /// withheld from everyone until it leaves flight - merged, failed, held,
3261    /// it makes no difference - at which point the sequence moves to
3262    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3263    /// going straight to `Idle` would hand `parked` back to ordinary
3264    /// priority-order dispatch, where a higher-priority task filed in the
3265    /// meantime could start ahead of it.
3266    Running {
3267        parked: Vec<String>,
3268        interrupt_task: String,
3269    },
3270    /// `interrupt_task` left flight; `parked` still names the one run this
3271    /// sequence owes a resume. Dispatch is withheld from everyone except
3272    /// that task - see [`interrupt_gate`] - so the resume this feature
3273    /// promises is never raced by, or run alongside, an unrelated candidate.
3274    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3275    /// own doc on abandonment - the moment it is no longer runnable at all.
3276    Resuming { parked: Vec<String> },
3277}
3278
3279/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3280/// and `runnable` are read-only snapshots of this tick's reality, and the
3281/// only side effect the caller still owes the world is asking whichever
3282/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3283/// site.
3284///
3285/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3286/// accepted rather than a narrower type because that is what [`poll`] already
3287/// has on hand from [`runnable`], and building a second, smaller list on
3288/// every tick just to satisfy this signature would cost more than it proves.
3289///
3290/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3291/// back to a task they are waiting on no longer being [`runnable`] - held,
3292/// blocked, deleted, or finished by some other means entirely, all of which
3293/// an operator can do to a task sitting in the queue with no claim on it at
3294/// all, at any moment, interrupt sequence or not. Without this check the
3295/// sequence would wait forever for a dispatch that can never come, and
3296/// `interrupt_gate` would withhold every other task in the queue right along
3297/// with it - a single `magi task hold` on the wrong id turning into a
3298/// daemon that never dispatches anything again.
3299fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3300    match state {
3301        Interrupt::Idle => {
3302            // Not just "something to interrupt": exactly one thing. More
3303            // than one run in flight only happens above the default
3304            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3305            // one resume, never run alongside anything else" only because
3306            // it is only ever seeded with exactly one id - see
3307            // `Interrupt::Resuming`'s own doc on why releasing more than one
3308            // parked id back to ordinary dispatch cannot be made safe
3309            // against that same setting's own extra concurrency slots.
3310            // Waiting here for the herd to settle to one is the
3311            // simplification this feature's own constraints ask for rather
3312            // than a second concurrency model to reconcile with the first.
3313            if in_flight.len() != 1 {
3314                return Interrupt::Idle;
3315            }
3316            match runnable.iter().find(|t| t.interrupt) {
3317                Some(t) => Interrupt::Parking {
3318                    parked: in_flight.to_vec(),
3319                    interrupt_task: t.id.clone(),
3320                },
3321                None => Interrupt::Idle,
3322            }
3323        }
3324        Interrupt::Parking {
3325            parked,
3326            interrupt_task,
3327        } => {
3328            if in_flight.iter().any(|id| parked.contains(id)) {
3329                // Still waiting for what was in flight to actually stop.
3330                Interrupt::Parking {
3331                    parked,
3332                    interrupt_task,
3333                }
3334            } else if in_flight.contains(&interrupt_task) {
3335                Interrupt::Running {
3336                    parked,
3337                    interrupt_task,
3338                }
3339            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3340                // The parked run(s) are gone, but the interrupt task has not
3341                // been dispatched yet on this tick - `interrupt_gate` is
3342                // what lets it through next.
3343                Interrupt::Parking {
3344                    parked,
3345                    interrupt_task,
3346                }
3347            } else {
3348                // The interrupt task itself is no longer runnable - see this
3349                // function's own doc on abandonment. The parked run(s) still
3350                // get their guaranteed resume; there is simply no interrupt
3351                // to run ahead of them any longer.
3352                Interrupt::Resuming { parked }
3353            }
3354        }
3355        Interrupt::Running {
3356            parked,
3357            interrupt_task,
3358        } => {
3359            if in_flight.contains(&interrupt_task) {
3360                Interrupt::Running {
3361                    parked,
3362                    interrupt_task,
3363                }
3364            } else {
3365                // The interrupt task's own run reached a terminal status,
3366                // whichever one - this is the *only* trigger that moves the
3367                // sequence on, driven straight off the same in-flight
3368                // bookkeeping `poll` already reaps every tick, not a second,
3369                // independent poll of anything.
3370                Interrupt::Resuming { parked }
3371            }
3372        }
3373        Interrupt::Resuming { parked } => {
3374            if in_flight.iter().any(|id| parked.contains(id)) {
3375                // One of the parked runs has been dispatched - the resume
3376                // this sequence owed is fulfilled. Whatever else is left in
3377                // `parked` (ordinarily nothing, at the default concurrency
3378                // of one) rejoins ordinary priority-order dispatch, same as
3379                // any other runnable task.
3380                Interrupt::Idle
3381            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3382                Interrupt::Resuming { parked }
3383            } else {
3384                // Abandonment (see this function's own doc): nothing left in
3385                // `parked` is even runnable any longer.
3386                Interrupt::Idle
3387            }
3388        }
3389    }
3390}
3391
3392/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3393/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3394/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3395/// indistinguishable from any other runnable task - exactly the "off does
3396/// nothing" this feature promises.
3397fn advance_interrupt_tick(
3398    enabled: bool,
3399    state: Interrupt,
3400    in_flight: &[String],
3401    runnable: &[Task],
3402) -> Interrupt {
3403    if !enabled {
3404        return Interrupt::Idle;
3405    }
3406    advance_interrupt(state, in_flight, runnable)
3407}
3408
3409/// Which of this tick's runnable candidates the interrupt sequence actually
3410/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3411/// each half is assertable on its own: this is the half that keeps a
3412/// competition and an interrupt from ever running at the same moment.
3413fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3414    match state {
3415        Interrupt::Idle => candidates,
3416        Interrupt::Parking {
3417            parked,
3418            interrupt_task,
3419        } => {
3420            if in_flight.iter().any(|id| parked.contains(id)) {
3421                Vec::new()
3422            } else {
3423                candidates
3424                    .into_iter()
3425                    .filter(|t| &t.id == interrupt_task)
3426                    .collect()
3427            }
3428        }
3429        Interrupt::Running { .. } => Vec::new(),
3430        // At most one: even if `parked` names more than one id (more than
3431        // one run was in flight when the sequence began, only possible
3432        // above the default `max_concurrent_runs = 1`), only the first match
3433        // is offered. Capping this to a single candidate - not merely to
3434        // `parked`'s own ids - is what makes "exactly one resume, never two
3435        // dispatched together" true regardless of how many ordinary slots
3436        // happen to be free this tick.
3437        Interrupt::Resuming { parked } => candidates
3438            .into_iter()
3439            .find(|t| parked.contains(&t.id))
3440            .into_iter()
3441            .collect(),
3442    }
3443}
3444
3445/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3446/// bundled into one parameter so `poll`'s own signature stays readable -
3447/// see [`drive`]'s call site for where these are actually read.
3448struct DispatchLimits {
3449    /// How many *ordinary* candidates run at once. See
3450    /// [`crate::config::Daemon::max_concurrent_runs`].
3451    max_concurrent: usize,
3452    /// See [`crate::config::Daemon::pause_for_interrupts`].
3453    pause_for_interrupts: bool,
3454    recovery_cfg: Option<Config>,
3455}
3456
3457/// Which semaphore, if any, dispatching a candidate should draw its permit
3458/// from.
3459///
3460/// Pure and separate from [`poll`]'s loop body for the same reason
3461/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3462/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3463/// exactly the policy this feature adds, and a policy only exercisable by
3464/// running the whole loop is a policy nobody checks.
3465#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3466enum PermitKind {
3467    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3468    /// Checked first - a task can be both a land resume and marked
3469    /// [`Task::urgent`], and the resume's own "must not queue behind
3470    /// anything" guarantee takes precedence.
3471    None,
3472    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3473    /// (never in addition to trying) the ordinary pool. This is what lets
3474    /// an urgent task dispatch while every ordinary slot is already checked
3475    /// out, and what stops a second urgent task from opening a third run: it
3476    /// waits on this same one-slot semaphore rather than falling through to
3477    /// the ordinary one.
3478    Urgent,
3479    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3480    /// above.
3481    #[default]
3482    Ordinary,
3483}
3484
3485/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3486/// own boolean, already computed by the caller from [`land_resume_state`].
3487fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3488    if priority {
3489        PermitKind::None
3490    } else if urgent {
3491        PermitKind::Urgent
3492    } else {
3493        PermitKind::Ordinary
3494    }
3495}
3496
3497fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3498    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3499        (0usize, 0usize),
3500        |(ordinary, urgent), request| match request.lane {
3501            PermitKind::Ordinary => (ordinary + 1, urgent),
3502            PermitKind::Urgent => (ordinary, urgent + 1),
3503            PermitKind::None => (ordinary, urgent),
3504        },
3505    );
3506    (
3507        limit.saturating_sub(ordinary),
3508        1usize.saturating_sub(urgent),
3509    )
3510}
3511
3512struct DispatchClaim {
3513    task: Task,
3514    claim: crate::queue::Claim,
3515    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3516}
3517
3518/// Claim and re-read before choosing a lane: a queue listing may predate an
3519/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3520fn claim_dispatch(
3521    queue: &Queue,
3522    candidate: &Task,
3523    cooling_down: bool,
3524    ordinary: &Arc<tokio::sync::Semaphore>,
3525    urgent: &Arc<tokio::sync::Semaphore>,
3526) -> Option<DispatchClaim> {
3527    let Ok(claim) = queue.claim(&candidate.id) else {
3528        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3529        return None;
3530    };
3531    let task = match queue.get(&candidate.id) {
3532        Ok(t) if t.status.runnable() => t,
3533        Ok(_) => return None,
3534        Err(e) => {
3535            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3536            return None;
3537        }
3538    };
3539    let resume = land_resume_state(&task);
3540    if resume == LandResume::StillWaiting {
3541        return None;
3542    }
3543    let priority = resume == LandResume::Ready;
3544    if !priority && cooling_down {
3545        return None;
3546    }
3547    // Never borrow an ordinary slot when the single urgent slot is busy.
3548    // Keep scanning other candidates when either pool has no free slot.
3549    let permit = match permit_kind(priority, task.urgent) {
3550        PermitKind::None => None,
3551        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3552        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3553    };
3554    // Persist the dispatch order under the claim, before config discovery or
3555    // coordination waits can reorder concurrent starts.
3556    let stamp = Timestamp::now();
3557    let mut task = task;
3558    task.dispatched_at = Some(stamp);
3559    if let Err(e) = queue.modify(&task.id, |t| {
3560        t.dispatched_at = Some(stamp);
3561        true
3562    }) {
3563        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3564    }
3565    Some(DispatchClaim {
3566        task,
3567        claim,
3568        permit,
3569    })
3570}
3571
3572/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3573/// teardown and cannot skip the teardown on an early return.
3574///
3575/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3576/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3577/// land approval that has since been answered is dispatched outside that
3578/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3579/// the whole point of parking there is that it must not queue behind
3580/// whatever else the loop happens to be running, even at the default of one.
3581/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3582/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3583/// these exemptions is still subject to the interrupt gate below, urgent
3584/// included: a land-resume or urgent candidate is exactly as much "something
3585/// else running" as an ordinary one from the interrupt sequence's point of
3586/// view, and letting either slip through while a run is being parked, or
3587/// while the interrupt task itself has the floor, is precisely the second
3588/// run 75dd's own "at most one run, ever, at once" guarantee must never
3589/// allow - see [`Interrupt`]'s own doc.
3590#[derive(Serialize, Deserialize)]
3591struct ServiceWorker {
3592    opts: Opts,
3593    queue: PathBuf,
3594    worktrees_root: PathBuf,
3595    operation: String,
3596}
3597
3598fn load_conductor(home: &Path) -> Result<Conductor> {
3599    match std::fs::read(home.join("conductor-state.json")) {
3600        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3601        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3602        Err(error) => Err(error.into()),
3603    }
3604}
3605
3606fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3607    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3608        .into_iter()
3609        .map(|c| c.task)
3610        .collect();
3611    let stalled = stalled_tasks(queue, home, Timestamp::now());
3612    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3613    let finished = finished_tasks(queue)
3614        .into_iter()
3615        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3616        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3617        .collect();
3618    let queued = queued_tasks(queue)
3619        .into_iter()
3620        .filter(|t| !live.contains(&t.id))
3621        .collect();
3622    (queued, stalled, finished)
3623}
3624
3625// Separate latest dispatch and worker receipts expose version handoff and skips
3626// without erasing the last completed scan or treating observations as authority.
3627fn retention_service_receipt(
3628    home: &Path,
3629    operation: &str,
3630    phase: &str,
3631    outcome: &str,
3632    detail: &str,
3633    cfg: Option<&Config>,
3634) {
3635    if !matches!(operation, "housekeeping" | "disk-pressure") {
3636        return;
3637    }
3638    let receipt = serde_json::json!({"checked_at": Timestamp::now(),
3639        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
3640        "operation": operation, "outcome": outcome, "detail": detail,
3641        "auto_fold": cfg.map(|c| c.disk.auto_fold),
3642        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
3643    if let Err(error) = crate::fold_evidence::atomic_write(
3644        &home.join(format!("source-eviction-{operation}-{phase}.json")),
3645        &serde_json::to_vec(&receipt).expect("service receipt"),
3646    ) {
3647        tracing::warn!("retention service receipt failed: {error:#}");
3648    }
3649}
3650
3651async fn start_service(
3652    home: &Path,
3653    opts: &Opts,
3654    queue: &Queue,
3655    worktrees_root: &Path,
3656    operation: &str,
3657    cfg: Option<&Config>,
3658    busy: bool,
3659) -> Result<()> {
3660    // Fetch policy is live configuration, unlike question recovery capacity.
3661    // Reload before both cadence and eligibility, including disabled -> enabled.
3662    let fetch_cfg = if operation == "fetch" {
3663        match prepare(&opts.repo, opts) {
3664            Ok(cfg) => Some(cfg),
3665            Err(error) => {
3666                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3667                return Ok(());
3668            }
3669        }
3670    } else {
3671        None
3672    };
3673    let cfg = fetch_cfg.as_ref().or(cfg);
3674    let ticks = home.join("service-ticks");
3675    std::fs::create_dir_all(&ticks)?;
3676    let receipt = ticks.join(format!("daemon-{operation}"));
3677    let last = std::fs::read(&receipt)
3678        .ok()
3679        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3680    let interval = match operation {
3681        "disk-pressure" => 30,
3682        "cache" => CACHE_CHECK_INTERVAL_SECS,
3683        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3684        _ => opts.poll.as_secs().max(1),
3685    };
3686    let now = Timestamp::now();
3687    if !cache_check_due(last, now, interval) {
3688        retention_service_receipt(
3689            home,
3690            operation,
3691            "dispatch",
3692            "skipped",
3693            "cadence not due",
3694            cfg,
3695        );
3696        return Ok(());
3697    }
3698    let key = format!("service:daemon-{operation}");
3699    if crate::worker::active(home)?
3700        .iter()
3701        .any(|job| job.key == key)
3702    {
3703        retention_service_receipt(
3704            home,
3705            operation,
3706            "dispatch",
3707            "skipped",
3708            "service worker already active",
3709            cfg,
3710        );
3711        return Ok(());
3712    }
3713    let eligible = match operation {
3714        "conductor" => {
3715            let (queued, stalled, finished) = conductor_work(queue, home);
3716            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3717                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3718        }
3719        "maintenance" => {
3720            queue.list().iter().any(|task| {
3721                crate::triage::disk_wait_eligible(task)
3722                    && task
3723                        .disk_checked_at
3724                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
3725            }) || Questions::at(home.join("questions"))
3726                .list_for_effects()
3727                .iter()
3728                .any(|q| {
3729                    q.chosen_action().is_some_and(|action| action.maintenance())
3730                        && !home
3731                            .join("choice-actions")
3732                            .join(format!("{}.json", q.id))
3733                            .exists()
3734                })
3735        }
3736        "housekeeping" => !busy && runnable(queue).is_empty(),
3737        "cache" => {
3738            !busy
3739                && !runnable(queue).is_empty()
3740                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3741        }
3742        "disk-pressure" => busy,
3743        "fetch" => {
3744            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3745        }
3746        _ => false,
3747    };
3748    if !eligible {
3749        retention_service_receipt(
3750            home,
3751            operation,
3752            "dispatch",
3753            "skipped",
3754            if operation == "housekeeping" {
3755                "active work or runnable task queue"
3756            } else {
3757                "no active work; idle housekeeping owns scan"
3758            },
3759            cfg,
3760        );
3761        return Ok(());
3762    }
3763    retention_service_receipt(
3764        home,
3765        operation,
3766        "dispatch",
3767        "launching",
3768        "eligible and cadence due",
3769        cfg,
3770    );
3771    let request = ServiceWorker {
3772        opts: opts.absolute()?,
3773        queue: std::path::absolute(queue.root())?,
3774        worktrees_root: std::path::absolute(worktrees_root)?,
3775        operation: operation.to_owned(),
3776    };
3777    if let Err(error) =
3778        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3779    {
3780        retention_service_receipt(
3781            home,
3782            operation,
3783            "dispatch",
3784            "error",
3785            &format!("worker launch: {error:#}"),
3786            cfg,
3787        );
3788        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3789    }
3790    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3791    Ok(())
3792}
3793
3794/// Finite maintenance jobs survive scheduler replacement without duplicating
3795/// agent calls or cancelling an operation between its effect and receipt.
3796pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3797    let request: ServiceWorker = serde_json::from_value(payload)?;
3798    let opts = &request.opts;
3799    let queue = Queue::at(request.queue);
3800    let questions = Questions::at(home.join("questions"));
3801    match request.operation.as_str() {
3802        "maintenance" => {
3803            apply_maintenance_choices(&queue, &questions, home).await;
3804            triage::monitor_disk_waits(
3805                &queue,
3806                &questions,
3807                opts.config.as_deref(),
3808                Timestamp::now(),
3809            );
3810        }
3811        "conductor" => {
3812            let path = home.join("conductor-state.json");
3813            let mut conductor = load_conductor(home)?;
3814            let (queued, stalled, finished) = conductor_work(&queue, home);
3815            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3816                && conductor.worth_a_look(&queue, &stalled, &finished)
3817            {
3818                let cfg = prepare(&opts.repo, opts)?;
3819                conductor
3820                    .maybe_run(
3821                        &cfg,
3822                        &opts.repo,
3823                        &queue,
3824                        &questions,
3825                        home,
3826                        &queued,
3827                        &stalled,
3828                        &finished,
3829                        opts.max_attempts,
3830                    )
3831                    .await;
3832                let temporary = path.with_extension("json.tmp");
3833                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3834                std::fs::rename(temporary, path)?;
3835            }
3836        }
3837        "fetch" => {
3838            let cfg = prepare(&opts.repo, opts)?;
3839            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3840                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3841                tracing::debug!("fetch origins: {outcome:?}");
3842            }
3843        }
3844        "cache" => {
3845            if task_jobs(home)?.is_empty() {
3846                let mut checked = None;
3847                maybe_prune_cache_between_runs(
3848                    &opts.repo,
3849                    opts,
3850                    home,
3851                    &Stop::new(),
3852                    &mut checked,
3853                    Timestamp::now(),
3854                )
3855                .await;
3856            }
3857        }
3858        "disk-pressure" => {
3859            if let Ok(cfg) = prepare(&opts.repo, opts) {
3860                retention_service_receipt(
3861                    home,
3862                    "disk-pressure",
3863                    "worker",
3864                    "running",
3865                    "retention sweep",
3866                    Some(&cfg),
3867                );
3868                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3869                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3870                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3871                }
3872                for current in current_work(home, Timestamp::now()) {
3873                    if let Ok(state) = RunState::load_under(&current.run, home)
3874                        && let Some(reason) = disk_gate(&state.repo, &state.config)
3875                    {
3876                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
3877                            job.key.strip_prefix("task:") == Some(current.task.as_str())
3878                        }) {
3879                            request_task_park(
3880                                home,
3881                                &job,
3882                                crate::run::ParkCause::Interrupt {
3883                                    reason: reason.clone(),
3884                                },
3885                            )?;
3886                        }
3887                        notices::raise_in(
3888                            home,
3889                            Notice::warn(
3890                                "disk:pressure",
3891                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
3892                            ),
3893                        );
3894                    }
3895                }
3896            } else {
3897                retention_service_receipt(
3898                    home,
3899                    "disk-pressure",
3900                    "worker",
3901                    "error",
3902                    "configuration could not be loaded",
3903                    None,
3904                );
3905            }
3906        }
3907        "housekeeping" => {
3908            if task_jobs(home)?.is_empty() {
3909                match prepare(&opts.repo, opts) {
3910                    Ok(cfg) => {
3911                        retention_service_receipt(
3912                            home,
3913                            "housekeeping",
3914                            "worker",
3915                            "running",
3916                            "retention sweep",
3917                            Some(&cfg),
3918                        );
3919                        crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3920                    }
3921                    Err(error) => retention_service_receipt(
3922                        home,
3923                        "housekeeping",
3924                        "worker",
3925                        "error",
3926                        &format!("configuration: {error:#}"),
3927                        None,
3928                    ),
3929                }
3930                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
3931                resweep_superseded_attempts(&queue, home);
3932                triage_held(&queue, home, opts).await;
3933            } else {
3934                retention_service_receipt(
3935                    home,
3936                    "housekeeping",
3937                    "worker",
3938                    "skipped",
3939                    "task worker became active",
3940                    None,
3941                );
3942            }
3943        }
3944        operation => bail!("unknown daemon service {operation}"),
3945    }
3946    Ok(())
3947}
3948
3949/// Only a different request under the same key is a dispatch handoff race.
3950/// Our own unacknowledged reservation is a startup failure, not competing work:
3951/// stop dispatch without fencing it, so an already detached child may still run.
3952fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
3953    let key = format!("task:{}", request.task);
3954    let payload = serde_json::to_value(request)?;
3955    if crate::worker::active(home)?
3956        .iter()
3957        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
3958    {
3959        tracing::warn!(
3960            "task {} acquired a competing worker reservation: {error:#}",
3961            crate::run::short_of(&request.task)
3962        );
3963        return Ok(());
3964    }
3965    tracing::error!("task worker startup stopped dispatch: {error:#}");
3966    notices::raise_in(
3967        home,
3968        Notice::error(
3969            "loop:worker-startup",
3970            // Startup diagnostics may contain private child-process details;
3971            // keep them in the local error/log rather than the chat or notifier.
3972            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),
3973        ).link(Link::Task { id: request.task.clone() }),
3974    );
3975    Err(error).with_context(|| {
3976        format!(
3977            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
3978            crate::run::short_of(&request.task)
3979        )
3980    })
3981}
3982
3983async fn poll(
3984    opts: &Opts,
3985    queue: &Queue,
3986    status: &Arc<Mutex<Status>>,
3987    home: &Path,
3988    worktrees_root: &Path,
3989    stop: &Stop,
3990    limits: DispatchLimits,
3991) -> Result<()> {
3992    let mut attempted = Vec::new();
3993    let mut settling_once_services = false;
3994    let interrupt_path = home.join("scheduler-interrupt.json");
3995    let mut interrupt = match std::fs::read(&interrupt_path) {
3996        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
3997        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
3998        Err(error) => return Err(error.into()),
3999    };
4000    let mut previous = std::collections::BTreeSet::<String>::new();
4001    while !stop.stopped() {
4002        let jobs: Vec<_> = crate::worker::active(home)?
4003            .into_iter()
4004            .filter(|job| job.kind == "task")
4005            .collect();
4006        let requests: Vec<_> = jobs
4007            .iter()
4008            .map(|job| {
4009                serde_json::from_value::<TaskWorker>(job.payload.clone())
4010                    .with_context(|| format!("read live task worker {}", job.id))
4011            })
4012            .collect::<Result<_>>()?;
4013        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4014        let owned: std::collections::BTreeSet<_> = requests
4015            .iter()
4016            .filter(|r| !r.standalone)
4017            .map(|r| r.task.clone())
4018            .collect();
4019        let current: Vec<_> = requests
4020            .iter()
4021            .zip(&jobs)
4022            .filter(|(request, _)| !request.standalone)
4023            .map(|(request, job)| Current {
4024                worker: Some(job.id.clone()),
4025                task: request.task.clone(),
4026                run: queue
4027                    .get(&request.task)
4028                    .ok()
4029                    .and_then(|task| task.execution_runs().last().cloned())
4030                    .unwrap_or_default(),
4031            })
4032            .collect();
4033        {
4034            let mut snapshot = lock(status);
4035            snapshot.polls += 1;
4036            snapshot.completed += previous.difference(&owned).count();
4037            snapshot.current = current;
4038            snapshot.idle = owned.is_empty();
4039        }
4040        previous = owned.clone();
4041        stop.busy.store(owned.len(), Ordering::SeqCst);
4042
4043        // Slots are reconstructed from durable reservations and OS-held worker
4044        // leases, not this scheduler's lifetime or mutable task urgency.
4045        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4046        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4047        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4048        let mut permits = Vec::new();
4049        sweep_stale_claims(queue, STALE_CLAIM);
4050        reclaim_orphaned_running(queue, opts.max_attempts, &live);
4051        reclaim_abandoned_runs(home, Timestamp::now());
4052        let questions = Questions::at(home.join("questions"));
4053
4054        // Deterministic: no model, run before the conductor sees anything so
4055        // its input reflects the queue's current, already-resolved state.
4056        crate::task_chat::sweep(
4057            queue,
4058            &crate::talk::Talks::at(home.join("talks")),
4059            &questions,
4060            home,
4061        );
4062        if let Err(error) = crate::task_inquiry::Outbox::at(home)
4063            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4064        {
4065            tracing::warn!("task inquiry delivery remains pending: {error:#}");
4066        }
4067        repair_choice_offers(&questions);
4068        resolve_blockers(queue, &questions);
4069        apply_task_choice_actions(queue, &questions, home);
4070        triage::apply_answers(queue, &questions);
4071        reconcile_task_questions(queue, &questions);
4072        let talks = crate::talk::Talks::at(home.join("talks"));
4073        crate::chat_notify::sweep(queue, &talks, home);
4074        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4075        crate::chat_watch::sweep(home, &talks);
4076        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4077            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4078        }
4079        let mut turns = tokio::task::JoinSet::new();
4080        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4081        // start_turns dispatches detached turns; no paid work lives in this set.
4082        while turns.join_next().await.is_some() {}
4083
4084        crate::consult::start_services(
4085            home,
4086            &opts.repo,
4087            limits.recovery_cfg.as_ref(),
4088            opts.config.as_deref(),
4089        )
4090        .await?;
4091        for operation in [
4092            "conductor",
4093            "maintenance",
4094            "housekeeping",
4095            "disk-pressure",
4096            "cache",
4097            "fetch",
4098        ] {
4099            // Once an idle --once drain starts settling services, subsequent
4100            // scans only consume their effects. An expired cadence receipt
4101            // must not start another service and keep the drain alive.
4102            if settling_once_services {
4103                break;
4104            }
4105            start_service(
4106                home,
4107                opts,
4108                queue,
4109                worktrees_root,
4110                operation,
4111                limits.recovery_cfg.as_ref(),
4112                !live.is_empty(),
4113            )
4114            .await?;
4115        }
4116        let latest = crate::worker::active(home)?;
4117        if latest.iter().any(|job| job.key == "service:daemon-cache")
4118            || latest
4119                .iter()
4120                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4121        {
4122            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4123            continue;
4124        }
4125        let candidates: Vec<Task> = runnable(queue)
4126            .into_iter()
4127            .filter(|task| !live.contains(&task.id))
4128            .filter(|task| !opts.once || !attempted.contains(&task.id))
4129            .collect();
4130        let in_flight: Vec<_> = owned.iter().cloned().collect();
4131        let prior_interrupt = std::mem::discriminant(&interrupt);
4132        interrupt = advance_interrupt_tick(
4133            limits.pause_for_interrupts,
4134            interrupt,
4135            &in_flight,
4136            &candidates,
4137        );
4138        // Same-variant transitions preserve their identities. Only an actual
4139        // transition needs a durable write, atomically before sending controls.
4140        if prior_interrupt != std::mem::discriminant(&interrupt) {
4141            let temporary = interrupt_path.with_extension("json.tmp");
4142            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4143            std::fs::rename(temporary, &interrupt_path)?;
4144        }
4145        if let Interrupt::Parking {
4146            parked,
4147            interrupt_task,
4148        } = &interrupt
4149        {
4150            for job in jobs.iter().filter(|job| {
4151                parked
4152                    .iter()
4153                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4154            }) {
4155                if crate::worker::control(home, &job.key)?.is_none() {
4156                    request_task_park(
4157                        home,
4158                        job,
4159                        crate::run::ParkCause::Interrupt {
4160                            reason: format!(
4161                                "task {} asked to run first",
4162                                crate::run::short_of(interrupt_task)
4163                            ),
4164                        },
4165                    )?;
4166                }
4167            }
4168        }
4169        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4170        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4171        let mut started = false;
4172        let mut resync = false;
4173        for candidate in candidates {
4174            if stop.stopped() {
4175                break;
4176            }
4177            let Some(DispatchClaim {
4178                task,
4179                claim,
4180                permit,
4181            }) = claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem)
4182            else {
4183                continue;
4184            };
4185            if crate::worker::active(home)?
4186                .iter()
4187                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4188            {
4189                drop(claim);
4190                resync = true;
4191                break;
4192            }
4193            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4194            let request = TaskWorker {
4195                opts: opts.absolute()?,
4196                queue: std::path::absolute(queue.root())?,
4197                task: task.id.clone(),
4198                lane,
4199                standalone: false,
4200            };
4201            // Keep the claim until spawn acknowledges the worker's durable
4202            // reservation. The worker then claims and re-reads before attempt.
4203            if let Err(error) = crate::worker::spawn(
4204                home,
4205                "task",
4206                &format!("task:{}", task.id),
4207                serde_json::to_value(&request)?,
4208            )
4209            .await
4210            {
4211                task_worker_spawn_error(home, &request, error)?;
4212                drop(claim);
4213                resync = true;
4214                break;
4215            }
4216            drop(claim);
4217            permits.extend(permit);
4218            attempted.push(task.id);
4219            started = true;
4220        }
4221        if started || resync {
4222            continue;
4223        }
4224        if owned.is_empty() && opts.once {
4225            settling_once_services = true;
4226            // These finite services can own queue claims or publish answers.
4227            // A skipped claim is not an idle queue until they have finished;
4228            // scan again afterwards so their changes are actually scheduled.
4229            if crate::worker::active(home)?.iter().any(|job| {
4230                job.kind == "daemon-service"
4231                    && matches!(
4232                        job.key.as_str(),
4233                        "service:daemon-housekeeping"
4234                            | "service:daemon-conductor"
4235                            | "service:daemon-maintenance"
4236                    )
4237            }) {
4238                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4239                continue;
4240            }
4241            break;
4242        }
4243        stop.idle(if live.is_empty() {
4244            opts.poll
4245        } else {
4246            RECHECK_WHILE_BUSY.min(opts.poll)
4247        })
4248        .await;
4249    }
4250    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4251    // every queue claim and Runner driver lease through outcome settlement.
4252    stop.busy.store(0, Ordering::SeqCst);
4253    Ok(())
4254}
4255
4256/// A maintenance pass may briefly own the same record while a worker starts.
4257/// Wait without blocking the executor or charging an agent attempt, then read
4258/// ownership again under the acquired lock. Other I/O failures still fail closed.
4259async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4260    let busy = |error: &anyhow::Error| {
4261        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4262            error.kind() == std::io::ErrorKind::WouldBlock
4263                || cfg!(windows) && error.raw_os_error() == Some(33)
4264        })
4265    };
4266    match crate::pr_head::owner_lock(home, id) {
4267        Ok(lock) => return Ok(lock),
4268        Err(error) if busy(&error) => {}
4269        Err(error) => return Err(error),
4270    }
4271    let wait = RunState::load_under(id, home)?
4272        .config
4273        .graph
4274        .timeout_resource_wait;
4275    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4276}
4277
4278/// Historical successors do not revoke a still-resumable public owner. Scan
4279/// under the same lock as publication/driver claims, and fail closed on unknown
4280/// history before spending another attempt.
4281async fn public_resume_owner(
4282    home: &Path,
4283    runs: &[String],
4284    repo: &Path,
4285) -> Result<Option<RunState>> {
4286    let mut owner = None;
4287    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4288        let _lock = resume_owner_lock(home, id).await?;
4289        let state = RunState::load_under(id, home)?;
4290        if state.released()
4291            || state.retired_to.is_some()
4292            || state.pr_taken_over_by.is_some()
4293            || !crate::handover::landing_checkpoint(&state)
4294        {
4295            continue;
4296        }
4297        anyhow::ensure!(
4298            crate::git::toplevel(&state.repo).await?.canonicalize()?
4299                == crate::git::toplevel(repo).await?.canonicalize()?,
4300            "public owner repository differs; inspect run lineage"
4301        );
4302        anyhow::ensure!(
4303            owner.is_none(),
4304            "multiple retained public owners; inspect run lineage"
4305        );
4306        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4307            anyhow::bail!(reason.diagnostic(&state));
4308        }
4309        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4310        anyhow::ensure!(
4311            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4312            "public owner's driver is live or unknown; wait before retrying"
4313        );
4314        owner = Some(state);
4315    }
4316    Ok(owner)
4317}
4318
4319/// Run one claimed task to a terminal status and record the outcome.
4320///
4321/// Every transition is flushed to the queue as it happens, so the state on disk
4322/// is what actually occurred rather than what this process still intends to
4323/// write.
4324async fn attempt(
4325    opts: &Opts,
4326    queue: &Queue,
4327    status: &Arc<Mutex<Status>>,
4328    stop: &Stop,
4329    interrupt_pause: crate::graph::Pause,
4330    task: &mut Task,
4331) -> Vec<QuotaLoss> {
4332    let repo = repo_for(task, &opts.repo);
4333    tracing::info!(
4334        "task {} — {} (repo {})",
4335        task.short(),
4336        task.title,
4337        repo.display()
4338    );
4339
4340    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4341        Ok(owner) => owner,
4342        Err(e) => {
4343            task.hold_machine(Some(format!(
4344                "Cannot verify existing public owner: {e:#}; no attempt started."
4345            )));
4346            record(queue, task);
4347            return Vec::new();
4348        }
4349    };
4350    let resume_runs = public_owner
4351        .as_ref()
4352        .map(|s| vec![s.id.clone()])
4353        .unwrap_or_else(|| task.execution_runs().to_vec());
4354
4355    // A stop spends no agent resources and uses the saved landing owner.
4356    // Current roster edits, missing attachments or a failed config fetch must
4357    // never turn it into a new implementation, or prevent a PR from closing.
4358    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4359        && previous
4360            .merge_decision
4361            .as_ref()
4362            .is_some_and(|decision| !decision.closed)
4363        && previous.status != RunStatus::Landing
4364        && !crate::merge_decision::resumable_hold(&previous)
4365    {
4366        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)));
4367        record(queue, task);
4368        return Vec::new();
4369    }
4370    let stop_owner = resume_runs
4371        .last()
4372        .and_then(|id| RunState::load(id).ok())
4373        .filter(|state| {
4374            crate::merge_decision::resumable_hold(state)
4375                || state.status == RunStatus::Landing
4376                    && state.land_approval.as_ref().is_some_and(|binding| {
4377                        Questions::open()
4378                            .get_for_effects(&binding.question)
4379                            .is_ok_and(|q| {
4380                                q.run == state.id
4381                                    && q.resolution()
4382                                        .as_deref()
4383                                        .is_some_and(crate::merge_decision::stops)
4384                            })
4385                    })
4386        });
4387    if let Some(owner) = stop_owner {
4388        let mut runner = match Runner::resume(&owner.id) {
4389            Ok(runner) => runner,
4390            Err(e) => {
4391                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4392                record(queue, task);
4393                return Vec::new();
4394            }
4395        };
4396        runner.on_pause(stop.pause());
4397        runner.watch_interrupt(interrupt_pause);
4398        let quota_before = runner.state.quota.clone();
4399        let before_start = task.clone();
4400        task.start(owner.id.clone());
4401        if let Err(error) = queue.put(task) {
4402            *task = before_start;
4403            let error = runner.fail_startup("task-start", error);
4404            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4405                task.record_startup_failure(failure.clone());
4406            }
4407            task.hold_manual(Some(format!(
4408                "Could not persist task start; no agents dispatched: {error:#}"
4409            )));
4410            record(queue, task);
4411            return Vec::new();
4412        }
4413        lock(status).current.push(Current {
4414            worker: None,
4415            task: task.id.clone(),
4416            run: owner.id,
4417        });
4418        runner.state.carry_dispatched_resumes(task);
4419        runner.state.next_pass_task_entry = true;
4420        let result = runner.execute().await;
4421        return finish_attempt(
4422            opts.max_attempts,
4423            queue,
4424            task,
4425            &runner.state,
4426            &quota_before,
4427            result,
4428        );
4429    }
4430
4431    if let Some(owner) = &public_owner
4432        && (task.fresh_start || !may_resume_run(owner, task))
4433    {
4434        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)));
4435        record(queue, task);
4436        return Vec::new();
4437    }
4438
4439    if let Some(state) = task
4440        .execution_runs()
4441        .last()
4442        .and_then(|id| RunState::load(id).ok())
4443        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4444    {
4445        task.hold_machine(Some(reason));
4446        record(queue, task);
4447        return Vec::new();
4448    }
4449
4450    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4451        && !task.fresh_start
4452        && task.pr_recovery.is_none()
4453    {
4454        // Authorization still takes the owner lock and execution lease and
4455        // rechecks liveness, retained HEAD and ownership before saving.
4456        let authorized = if crate::repair_budget::conflict_pending(task, &held) {
4457            true
4458        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4459            let home = queue.root().parent().expect("queue has a home");
4460            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4461                Ok(()) => true,
4462                Err(error) => {
4463                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4464                    false
4465                }
4466            }
4467        } else {
4468            false
4469        };
4470        if !authorized {
4471            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())));
4472            // Retain the existing stop identity when an old release reached the queue.
4473            task.base_sync_notice(&held);
4474            task.resume_override = None;
4475            record(queue, task);
4476            return Vec::new();
4477        }
4478    }
4479    let unfinished = (!task.fresh_start)
4480        .then(|| unfinished_run(&resume_runs, task.short()))
4481        .flatten()
4482        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4483    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4484    if let Some(id) = &task.disk_resume_run
4485        && unfinished.as_ref() != Some(id)
4486    {
4487        task.hold_manual(Some("Automatic disk recovery cannot resume the retained execution safely. Inspect its state and recovery approvals; no replacement competition was started.".into()));
4488        record(queue, task);
4489        return Vec::new();
4490    }
4491
4492    if !task.fresh_start
4493        && task.pr_recovery.is_none()
4494        && task.review_branch.is_none()
4495        && task.resume_override.is_none()
4496        && previous
4497            .as_ref()
4498            .is_some_and(|run| run.retired_to.is_some())
4499        && unfinished.is_none()
4500    {
4501        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()));
4502        record(queue, task);
4503        return Vec::new();
4504    }
4505
4506    let saved_recovery = previous.as_ref().filter(|run| {
4507        task.replacement.is_none()
4508            && task.pr_recovery.as_ref().is_some_and(|selected| {
4509                selected
4510                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4511                    .is_ok()
4512                    && selected_starter(selected, Some(run), unfinished.as_deref())
4513                        == Starter::Resume(run.id.clone())
4514            })
4515    });
4516
4517    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4518    // failure here is the network's or the operator's, not the task's: hold
4519    // without spending an attempt, never fall back to a possibly stale copy.
4520    let explicit = match &task.overrides {
4521        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4522        Some(_) => opts.config.as_deref(),
4523        None => opts.config.as_deref(),
4524    };
4525    let (mut config, layers) = if let Some(run) = saved_recovery {
4526        // A matching resume owns its resolved configuration and evidence;
4527        // current layers and inherited overrides only configure new work.
4528        let mut saved = run.clone();
4529        if let Err(e) = saved.configure_recovery_resume() {
4530            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4531            record(queue, task);
4532            return Vec::new();
4533        }
4534        (saved.config, Vec::new())
4535    } else {
4536        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4537            Ok(loaded) => loaded,
4538            Err(e) => {
4539                let reason = format!("[config] {e:#}");
4540                record_config_failure(task, &e);
4541                task.last_error = Some(reason.clone());
4542                task.hold_machine(Some(reason));
4543                record(queue, task);
4544                return Vec::new();
4545            }
4546        };
4547        if let Err(e) = apply_options(&mut config, opts, task) {
4548            task.hold_manual(Some(format!(
4549                "[config] {e:#}; correct the merge override before releasing the task"
4550            )));
4551            record(queue, task);
4552            return Vec::new();
4553        }
4554        if let Some(selected) = &task.pr_recovery
4555            && let Err(e) = selected.configure(&mut config)
4556        {
4557            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4558            record(queue, task);
4559            return Vec::new();
4560        }
4561        (config, layers)
4562    };
4563    let config_evidence = crate::pr_recovery::ConfigEvidence {
4564        layers,
4565        overrides: task.overrides.clone(),
4566        daemon_merge: task
4567            .overrides
4568            .as_ref()
4569            .is_none_or(|o| o.inherit_daemon_options)
4570            .then(|| opts.merge.clone())
4571            .flatten(),
4572    };
4573    apply_task_implementers(&mut config, task);
4574    if let Some(replacement) = &task.replacement {
4575        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4576            old.liveness(false) == Liveness::Dead
4577                && old.merge_decision.as_ref().is_some_and(|d| {
4578                    d.closed
4579                        && d.question == replacement.question
4580                        && d.replacement_run.as_ref().is_none_or(|run| {
4581                            task.execution_runs().last() == Some(run)
4582                                && RunState::load(run).is_ok_and(|current| {
4583                                    current.replaces.as_ref().is_some_and(|pin| {
4584                                        pin.question == replacement.question
4585                                            && pin.agent == replacement.agent
4586                                    })
4587                                })
4588                        })
4589                })
4590        });
4591        if !safe {
4592            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()));
4593            record(queue, task);
4594            return Vec::new();
4595        }
4596        match config.agent(&replacement.agent) {
4597            Ok(agent) if crate::agent::installed(agent) => {}
4598            _ => {
4599                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)));
4600                record(queue, task);
4601                return Vec::new();
4602            }
4603        }
4604        config.graph.implementers = 1;
4605        config.graph.land_approval = true;
4606        config.merge.mode = MergeMode::Pr;
4607        config.graph.selected_implementer = Some(replacement.agent.clone());
4608    }
4609    let p = phrases(&config.graph.language);
4610    let start_failed = p.could_not_start;
4611    // Resolve once for both admission and settlement. The inputs are the
4612    // task's explicit sources (never prose), plus an explicit review source's
4613    // current head; review-only runs may rebase later, and neither fact can
4614    // refund a failed automatic generation.
4615    if let Ok(base) =
4616        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4617            .await
4618        && let Ok(head) =
4619            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4620    {
4621        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4622        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4623            let source = crate::git::rev_parse(&repo, branch)
4624                .await
4625                .unwrap_or_default();
4626            inputs.push_str(&format!(";review:{branch}:{source}"));
4627        }
4628        if let Some(reason) = task
4629            .recovery_exhausted(
4630                &head,
4631                &inputs,
4632                task.attempt_limit
4633                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4634            )
4635            .filter(|_| {
4636                !task.repair_grants.last().is_some_and(|receipt| {
4637                    RunState::load(&receipt.request.run)
4638                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4639                })
4640            })
4641        {
4642            task.hold_unrequested_retry(Some(reason));
4643            record(queue, task);
4644            return Vec::new();
4645        }
4646        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4647    }
4648
4649    // The free-space gate, checked *before* anything is minted: a task that
4650    // waits out a full disk costs nothing yet, and must not spend an attempt
4651    // or start a run the machine cannot finish. Held tasks stay in the list
4652    // for the human to see; triage requeues them automatically when capacity
4653    // and output reservations permit the same execution to resume. A volume whose free
4654    // space cannot be measured closes the gate too: starting a run blind on a
4655    // disk that may be full is how the machine ends up with 6.7 GB free.
4656    if let Some(reason) = disk_gate(&repo, &config) {
4657        task.notice_cause("disk-space", None, None);
4658        task.last_error = Some(reason.clone());
4659        let disk_checked_at = task.disk_checked_at;
4660        task.hold_machine(Some(reason.clone()));
4661        task.mark_disk_capacity();
4662        task.disk_checked_at = disk_checked_at;
4663        record(queue, task);
4664        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4665        // Stable wording - the free-space figures live in the task's hold
4666        // reason, and changing numbers would relight the bell every poll.
4667        notices::raise(
4668            Notice::warn(
4669                &format!("disk:{}", repo.display()),
4670                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
4671            )
4672            .link(Link::Task {
4673                id: task.id.clone(),
4674            }),
4675        );
4676        return Vec::new();
4677    }
4678
4679    // A resumable run of this task is carried on, never re-competed. The
4680    // candidates are built and paid for, and a fresh competition races a
4681    // second implementation against them.
4682    //
4683    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4684    // started 3cbf on the same task a moment later, duplicating two and a
4685    // half hours of agent work. Then b25f stalled on a judge that timed out
4686    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4687    // was to blame for - and 4043 started **one second** later, buying three
4688    // fresh implementations to reach the same panel. `RunStatus::resumable`
4689    // rather than `!done()` is what catches the second case: a stall is
4690    // terminal, and its cheap recovery re-asks only the absent seats.
4691    //
4692    // A load failure is warned about rather than silently read as "not
4693    // resumable": the alternative is exactly what let a schema mismatch on
4694    // run `eba2` fall through to a full re-competition with nobody told why.
4695    // `crate::conduct` is what actually offers a better answer than
4696    // `Runner::start` here (see `Recovery::Review`), once this task's next
4697    // failure shows it up as `held`/`failed` with the run state unreadable.
4698    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
4699    // branch survived, and this reopens exactly that branch as a
4700    // review-only pass rather than resuming or competing again. Consumed
4701    // (cleared) here whichever way this goes, so it never outlives this one
4702    // attempt - see `queue::Task::review_branch`.
4703    let review_branch = if previous
4704        .as_ref()
4705        .is_some_and(|state| crate::repair_budget::pending(task, state))
4706    {
4707        None
4708    } else {
4709        take_review_branch(task, previous.as_ref())
4710    };
4711    let branch_exists = match &review_branch {
4712        Some(branch) => crate::git::branch_exists(&repo, branch)
4713            .await
4714            .unwrap_or(false),
4715        None => false,
4716    };
4717    // An explicit `magi review <branch>` is reviewed whatever happens to the
4718    // branch unless an explicit implementer change requires fresh work. An
4719    // unfinished run of the same task still wins, so a retry resumes.
4720    let proposed = review_retry_starter(
4721        task,
4722        previous.as_ref(),
4723        review_branch.as_deref(),
4724        branch_exists,
4725        unfinished.as_deref(),
4726    );
4727    let retry_selected = task.replacement.is_some()
4728        && task.resumption.is_some()
4729        && !task.fresh_start
4730        && previous.as_ref().is_some_and(|run| {
4731            run.replaces.is_some()
4732                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4733                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4734        });
4735    let stop_pin = task
4736        .resume_override
4737        .as_ref()
4738        .filter(|pin| {
4739            Questions::open()
4740                .get_for_effects(&pin.question_id)
4741                .is_ok_and(|q| {
4742                    q.node == land::APPROVAL_NODE
4743                        && q.resolution()
4744                            .as_deref()
4745                            .is_some_and(crate::merge_decision::stops)
4746                })
4747        })
4748        .and_then(|pin| pin.pinned_run.clone());
4749    let granted_run = task.repair_grants.last().and_then(|receipt| {
4750        let state = RunState::load(&receipt.request.run).ok()?;
4751        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
4752    });
4753    let starter = if let Some(run) = granted_run {
4754        Starter::Resume(run)
4755    } else if let Some(owner) = &public_owner {
4756        Starter::Resume(owner.id.clone())
4757    } else if let Some(run) = stop_pin {
4758        // Stop actions resume their exact owner even after seat-count edits;
4759        // they must never fall through to implementation or a takeover.
4760        Starter::Resume(run)
4761    } else if retry_selected {
4762        Starter::Resume(previous.as_ref().unwrap().id.clone())
4763    } else if let Some(selected) = &task.pr_recovery {
4764        if selected
4765            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4766            .is_ok()
4767        {
4768            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4769        } else {
4770            Starter::Review(selected.branch.clone())
4771        }
4772    } else {
4773        starter_with_implementers(task, previous.as_ref(), proposed)
4774    };
4775    // An explicit resume pin must never degrade into a new competition or
4776    // takeover, including when its run stops being eligible after the answer.
4777    if let Some(pin) = &task.resume_override
4778        && let Some(run) = &pin.pinned_run
4779        && starter != Starter::Resume(run.clone())
4780    {
4781        let run = run.clone();
4782        task.notice_cause("resume-owner", Some(&run), None);
4783        task.hold_machine(Some(format!(
4784            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4785            task.id
4786        )));
4787        record(queue, task);
4788        return Vec::new();
4789    }
4790    // Automatic disk recovery resumes its retained run or stops: a changed
4791    // seat count or review branch must not turn it into a new competition.
4792    // No attempt is spent here.
4793    if let Some(run) = &task.disk_resume_run
4794        && starter != Starter::Resume(run.clone())
4795    {
4796        task.hold_manual(Some("Automatic disk recovery cannot resume the retained execution safely: the task's current settings would start a different run. Inspect its state and recovery approvals; no replacement competition was started.".into()));
4797        record(queue, task);
4798        return Vec::new();
4799    }
4800    if task.replacement.is_some()
4801        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4802        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4803    {
4804        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()));
4805        record(queue, task);
4806        return Vec::new();
4807    }
4808    if let Some(reason) = retained_attempt_hold(
4809        task,
4810        &starter,
4811        config.disk.retained_attempt_limit,
4812        RunState::load,
4813    ) {
4814        // The review choice was consumed above. Preserve it across this hold
4815        // so a later release cannot silently become a fresh implementation.
4816        if let Starter::Review(branch) = &starter {
4817            task.review_branch = Some(branch.clone());
4818        }
4819        task.hold_unrequested_retry(Some(reason));
4820        record(queue, task);
4821        return Vec::new();
4822    }
4823    // Absolute paths of the files the task was filed with, re-read from the
4824    // task now so a file attached while it was held reaches a resumed run
4825    // too. A stored name whose file has gone is an error before any agent is
4826    // paid for, never a silent omission the implementer cannot notice.
4827    let attachments = match task_attachments(queue, task) {
4828        Ok(a) => a,
4829        Err(e) => {
4830            task.attempts += 1;
4831            task.fail_startup_target(
4832                "startup-attachments",
4833                e.name.clone(),
4834                format!("{start_failed}{e:#}"),
4835                opts.max_attempts,
4836            );
4837            record(queue, task);
4838            return Vec::new();
4839        }
4840    };
4841    let startup_pause = stop.pause();
4842    let startup_interrupt = interrupt_pause.clone();
4843    let wait = crate::repo_lock::WaitPolicy::new(
4844        Duration::from_secs(config.graph.timeout_resource_wait),
4845        move || startup_pause.parked() || startup_interrupt.parked(),
4846    );
4847    // Startup includes review takeover and recovery. Do not embed its large
4848    // future in both the wait scope and the surrounding attempt stack frame.
4849    let started = wait.scope(Box::pin(async { match &starter {
4850        Starter::Review(_) if task.pr_recovery.is_some() => {
4851            let selected = task.pr_recovery.clone().expect("selected recovery");
4852            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
4853                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4854                    .await
4855                    .map(|mut r| {
4856                        r.state.attachments = attachments.clone();
4857                        r
4858                    }),
4859                Err(e) => Err(e),
4860            }
4861        }
4862        Starter::Review(branch) => {
4863            tracing::info!(
4864                "task {} reopens `{branch}` as a review-only pass",
4865                task.short()
4866            );
4867            // Every earlier attempt is superseded by the one being minted
4868            // now, so a branch one of them still holds may be taken over.
4869            let takeover = crate::handover::Takeover {
4870                earlier: task.earlier_attempts().to_vec(),
4871                home: crate::run::home(),
4872                choice: take_divergence_answer(branch, &config.merge.remote, task),
4873                task_instruction: Some(instruction_for(task)),
4874            };
4875            Runner::review_taking_over(
4876                &repo,
4877                branch,
4878                config,
4879                Some(takeover),
4880                crate::run::Origin::queue(&task.id),
4881            )
4882            .await
4883        }
4884        Starter::Resume(id) => {
4885            tracing::info!("resuming run {id} rather than competing again");
4886            Runner::resume(id).and_then(|mut r| {
4887                if retry_selected {
4888                    // The explicit queue release retries this same pinned
4889                    // implementation, preserving the attempt and worktrees.
4890                    for candidate in &mut r.state.candidates {
4891                        candidate.failed = None;
4892                        candidate.empty = false;
4893                        candidate.commits = 0;
4894                    }
4895                    r.state.status = RunStatus::Implementing;
4896                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4897                }
4898                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4899                    r.state.sources = task.sources.clone();
4900                }
4901                if r.state.prep_failure.is_some() {
4902                    let approval = task
4903                        .resumption
4904                        .as_ref()
4905                        .context("preparation retry requires an explicit task release")?;
4906                    r.retry_preparation(approval.at)?;
4907                }
4908                if let Some(instruction) =
4909                    prepare_instruction(&starter, Some(&r.state.instruction), task)
4910                {
4911                    r.state.instruction = instruction;
4912                }
4913                r.state.attachments = attachments.clone();
4914                if task.replacement.is_some() {
4915                    r.state.config.merge.mode = MergeMode::Pr;
4916                    r.state.config.graph.land_approval = true;
4917                }
4918                // Replacements publish a new PR and ask again. Selected PR
4919                // recoveries keep their saved disposition; ordinary runs can
4920                // retain the task's merge override.
4921                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4922                    .overrides
4923                    .as_ref()
4924                    .and_then(|o| o.merge.as_deref())
4925                    .and_then(|m| merge_mode(m).ok())
4926                {
4927                    r.state.config.merge.mode = mode;
4928                }
4929                Ok(r)
4930            })
4931        }
4932        Starter::Start => {
4933            if let Some(branch) = &review_branch {
4934                tracing::warn!(
4935                    "conductor chose review for task {} but branch `{branch}` no longer \
4936                     exists; requeuing as a fresh competition instead",
4937                    task.short()
4938                );
4939            }
4940            let instruction = prepare_instruction(&starter, None, task)
4941                .unwrap_or_else(|| task.instruction.clone());
4942            Runner::start_naming(
4943                &repo,
4944                instruction,
4945                &task.title,
4946                config,
4947                crate::run::Origin::queue(&task.id),
4948            )
4949            .await
4950            .map(|mut r| {
4951                r.state.attachments = attachments.clone();
4952                r.state.sources = task.sources.clone();
4953                r
4954            })
4955        }
4956    }})).await;
4957    if let Err(error) = &started
4958        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
4959    {
4960        task.record_startup_failure(failure.clone());
4961    }
4962    let mut runner = match started {
4963        Ok(r) => r,
4964        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4965            task.last_error = Some(e.to_string());
4966            if stop.parking() || interrupt_pause.parked() {
4967                let attempts = task.attempts;
4968                task.park(e.to_string());
4969                // Startup has not spent an attempt to refund.
4970                task.attempts = attempts;
4971            } else {
4972                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4973            }
4974            record(queue, task);
4975            return Vec::new();
4976        }
4977        // A branch an earlier attempt still holds and magi will not release
4978        // by itself is the operator's call, not a failed attempt: hold the
4979        // task with the reason, spend nothing, and say so on the bell.
4980        Err(e) if task.pr_recovery.is_some() => {
4981            task.startup_notice_cause("startup-public-head");
4982            task.attempts += 1;
4983            task.last_error = Some(format!("{start_failed}{e:#}"));
4984            task.hold_unrequested_retry(Some(format!(
4985                "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."
4986            )));
4987            record(queue, task);
4988            return Vec::new();
4989        }
4990        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4991            let detail = match e.downcast_ref::<crate::handover::Refused>() {
4992                Some(r) => (p.handover_refused)(r),
4993                None => format!("{e:#}"),
4994            };
4995            task.startup_notice_cause("startup-handover");
4996            let reason = format!("{start_failed}{detail}");
4997            task.last_error = Some(reason.clone());
4998            // Consumed above by `take`; keep it so the released task retries
4999            // as a review of this same branch.
5000            let branch = match &starter {
5001                Starter::Review(branch) => Some(branch.clone()),
5002                _ => None,
5003            };
5004            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
5005            // one page; the guidance rides in the reason, fixed per state so a
5006            // re-put never changes the wording and relights it.
5007            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5008            record(queue, task);
5009            tracing::warn!(
5010                "holding {} for a branch it cannot take over: {e:#}",
5011                task.short()
5012            );
5013            return Vec::new();
5014        }
5015        // A branch that differs between here and the remote in ways magi
5016        // cannot prove are the same change is a decision for the owner, not a
5017        // failed attempt: ask with both sides laid out, spend no attempt, and
5018        // let the answer requeue the task.
5019        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5020            let d = e
5021                .downcast_ref::<crate::reconcile::Diverged>()
5022                .expect("checked by the guard");
5023            let mut q = ask::Question::new(
5024                task.id.clone(),
5025                crate::reconcile::NODE.to_owned(),
5026                crate::reconcile::SEAT.to_owned(),
5027                d.summary(),
5028                d.detail(),
5029                d.choices(),
5030            );
5031            match Questions::open().put(&mut q) {
5032                Ok(()) => {
5033                    task.last_error = Some(format!("{e:#}"));
5034                    // Consumed above by `take`; the answer has to reach a review
5035                    // of this same branch, so keep pointing the task at it.
5036                    task.review_branch = Some(d.branch.clone());
5037                    task.review_instruction = Some(task.instruction.clone());
5038                    task.block(vec![q.id.clone()], Some(d.summary()));
5039                }
5040                Err(put) => {
5041                    tracing::warn!("could not file the divergence question: {put:#}");
5042                    task.attempts += 1;
5043                    task.fail_startup(
5044                        "startup-question-store",
5045                        format!("{start_failed}{e:#}"),
5046                        opts.max_attempts,
5047                    );
5048                }
5049            }
5050            record(queue, task);
5051            return Vec::new();
5052        }
5053        Err(e) => {
5054            // The answer was stale and nothing was applied: keep pointing at
5055            // the branch so the next attempt asks again against its new tips.
5056            // Nothing went wrong with the task, so no attempt is spent: a
5057            // budget one short of its limit must not hold it instead of
5058            // letting the question be asked again.
5059            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5060                && let Starter::Review(branch) = &starter
5061            {
5062                task.review_branch = Some(branch.clone());
5063                task.review_instruction = Some(task.instruction.clone());
5064                task.last_error = Some(format!("{start_failed}{e:#}"));
5065                task.status = crate::queue::TaskStatus::Failed;
5066                record(queue, task);
5067                return Vec::new();
5068            }
5069            task.attempts += 1;
5070            task.last_error = Some(format!("{start_failed}{e:#}"));
5071            task.startup_notice_cause("startup-source");
5072            task.hold_unrequested_retry(Some(format!(
5073                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5074            )));
5075            record(queue, task);
5076            return Vec::new();
5077        }
5078    };
5079    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5080        runner.state.recovery_config = Some(config_evidence);
5081    }
5082    if let Some(replacement) = &task.replacement {
5083        if matches!(starter, Starter::Start) {
5084            runner.state.instruction.push_str(&format!(
5085                "\n\n# Replacement review context\n{}",
5086                replacement.context
5087            ));
5088        }
5089        runner.state.replaces = Some(replacement.clone());
5090        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5091        if let Ok(mut old) = RunState::load(&replacement.run)
5092            && let Some(d) = &mut old.merge_decision
5093        {
5094            d.replacement_run = Some(runner.state.id.clone());
5095            old.event(
5096                "replacement",
5097                format!(
5098                    "replacement run {} owns the next attempt; old PR remains closed",
5099                    runner.state.id
5100                ),
5101            );
5102            if let Err(e) = old.save() {
5103                let error = runner.fail_startup("replacement-history", e);
5104                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5105                    task.record_startup_failure(failure.clone());
5106                }
5107                task.hold_manual(Some(format!(
5108                    "Could not link replacement history: {error:#}; no agents dispatched"
5109                )));
5110                record(queue, task);
5111                return Vec::new();
5112            }
5113        }
5114    }
5115    runner.state.task_instruction = Some(task.instruction.clone());
5116    // The follow-up depth is fixed now, while the task certainly exists:
5117    // deleting it later must not reset the cap (`crate::followup`).
5118    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5119    if runner.state.origin_chat.is_none() {
5120        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5121    }
5122    // A stop that means "park" reaches the graph through this handle.
5123    runner.on_pause(stop.pause());
5124    // `poll`'s interrupt scheduler reaches this one run - and no other -
5125    // through this handle. See `Pause`'s own doc for why these are never
5126    // the same one.
5127    runner.watch_interrupt(interrupt_pause);
5128
5129    // `start` has minted the run, so the task can now point at it. Persisting
5130    // `Running` before `execute` is what makes a crash mid-run legible.
5131    let run = runner.state.id.clone();
5132    let before_start = task.clone();
5133    task.start(run.clone());
5134    if let Err(error) = queue.put(task) {
5135        *task = before_start;
5136        let error = runner.fail_startup("task-start", error);
5137        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5138            task.record_startup_failure(failure.clone());
5139        }
5140        task.hold_manual(Some(format!(
5141            "Could not persist task start; no agents dispatched: {error:#}"
5142        )));
5143        record(queue, task);
5144        return Vec::new();
5145    }
5146    lock(status).current.push(Current {
5147        worker: None,
5148        task: task.id.clone(),
5149        run,
5150    });
5151
5152    // `RunState::quota` is the run's whole history across every resume, so
5153    // only what this execution added may arm the cooldown or earn a refund.
5154    let quota_before = runner.state.quota.clone();
5155    runner.state.carry_dispatched_resumes(task);
5156    runner.state.next_pass_task_entry = true;
5157    let result = runner.execute().await;
5158    finish_attempt(
5159        opts.max_attempts,
5160        queue,
5161        task,
5162        &runner.state,
5163        &quota_before,
5164        result,
5165    )
5166}
5167
5168/// Settle `task` after its run executed: the verdict, the diagnosis, the
5169/// supersession of earlier attempts and the save. Shared by the loop and by
5170/// `magi run --resume`, so an attempt is counted one way wherever it ran.
5171/// Returns the quota losses this execution added to the run.
5172pub fn finish_attempt(
5173    max_attempts: usize,
5174    queue: &Queue,
5175    task: &mut Task,
5176    state: &RunState,
5177    quota_before: &[QuotaLoss],
5178    result: Result<()>,
5179) -> Vec<QuotaLoss> {
5180    let detail = match result {
5181        Ok(()) => describe(state),
5182        Err(e) => format!("{e:#}"),
5183    };
5184    let fresh = losses_this_attempt(quota_before, &state.quota);
5185    let verdict = Verdict {
5186        status: state.status,
5187        // A run that opened a pull request handed its work over, whatever the
5188        // gate then decided about merging it.
5189        left_pr: state.pr.is_some(),
5190        // Only a rate limit earns the task its attempt back - and only one
5191        // suffered now: a refund justified by a previous session's loss is
5192        // the same mistake as re-arming the cooldown from it. A stalled run
5193        // resumed without hitting quota again therefore spends its attempt,
5194        // like any other failure of the task's own.
5195        quota_hit: !fresh.is_empty(),
5196        // A run that parked was asked to stop; that is not a failure and must
5197        // not spend an attempt, or replacing the binary a few times would
5198        // exhaust a task's budget without an agent ever misbehaving.
5199        parked: state.parked,
5200        // A quota loss that left nothing viable is the same machine fact as a
5201        // `Stalled` quota loss; see `settle`'s doc table.
5202        no_viable_candidates: state.viable().is_empty(),
5203    };
5204    if let Some(replacement) = &state.replaces
5205        && let Some(pr) = &state.pr
5206        && let Ok(mut old) = RunState::load(&replacement.run)
5207        && let Some(d) = &mut old.merge_decision
5208    {
5209        d.replacement_pr = Some(pr.url.clone());
5210        let _ = old.save();
5211    }
5212    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5213    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5214        task.hold_unrequested_retry(Some(format!(
5215            "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.",
5216            task.short()
5217        )));
5218    }
5219    if task.status == TaskStatus::Done {
5220        supersede_prior_runs(task, &crate::run::home());
5221    }
5222    record(queue, task);
5223    tracing::info!(
5224        "task {} is {} after run {} ({})",
5225        task.short(),
5226        task.status.as_str(),
5227        state.short(),
5228        label(state.status)
5229    );
5230    fresh
5231}
5232
5233/// A task a hand-started run leaves runnable (failed with attempts to spare,
5234/// or requeued) is **held**: nobody asked for a retry, and a loop starting
5235/// later must not spend agent calls on it. `magi task release` retries.
5236pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5237    // Parked work (including legacy Failed records with a parked run) is a
5238    // checkpoint or owner handoff, not an unrequested retry.
5239    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5240        && !awaiting_resume_with(task, RunState::load)
5241        // A run parked on the owner's word about a withheld PR title/body
5242        // resumes via `land_resume_state`, including review-only tasks that
5243        // `awaiting_resume_with` does not consider.
5244        && withheld_text_wait(task).is_none()
5245        && !(task.fresh_start && task.replacement.is_some())
5246    {
5247        let why = task.last_error.clone().map_or_else(
5248            || "the run did not finish".to_owned(),
5249            |e| format!("the run did not finish: {e}"),
5250        );
5251        task.hold_unrequested_retry(Some(format!(
5252            "{why}. It was started by hand, so it is not retried \
5253             automatically; `magi task release` retries it."
5254        )));
5255        record(queue, task);
5256    }
5257}
5258
5259/// Whether an attempt at a task whose newest run is `run` would resume that
5260/// run rather than start a fresh competition. `magi run --resume` hands a run
5261/// to a live loop only when this holds.
5262#[must_use]
5263pub fn loop_would_resume(run: &str) -> bool {
5264    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5265}
5266
5267/// A loop in another process that is alive right now: a fresh heartbeat in
5268/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
5269/// carries the pid it published (`None` inside when it published none - a
5270/// fresh heartbeat is still evidence of a live loop).
5271///
5272/// The one judgement of "is somebody else serving this queue", shared by the
5273/// web UI's refusal to start a second loop and by `magi run` / `magi review`
5274/// deciding whether to hand a task to the loop. A claim file proves nothing
5275/// here: whether a claim succeeds says nothing about whether its owner lives.
5276#[must_use]
5277pub fn foreign_loop(
5278    reading: Option<&Reading>,
5279    now: Timestamp,
5280    own_pid: u32,
5281) -> Option<Option<u32>> {
5282    let reading = reading.filter(|r| r.running(now))?;
5283    match reading.pid {
5284        Some(pid) if pid == own_pid => None,
5285        pid => Some(pid),
5286    }
5287}
5288
5289fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5290    reading.worker_protocol != Some(1)
5291        && (foreign_loop(Some(reading), now, own_pid).is_some()
5292            || reading
5293                .pid
5294                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5295}
5296
5297/// Low-level claimed-task execution shared by the detached standalone worker
5298/// and focused lifecycle fixtures. The caller must retain the queue claim for
5299/// this entire call. CLI callers transfer ownership through
5300/// [`run_detached_claimed`] instead of executing inside their own runtime.
5301///
5302/// The one deliberate difference from the loop: a task the attempt leaves
5303/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5304/// Nobody asked for a retry, and a daemon starting later must not spend agent
5305/// calls re-running a hand-started task behind the operator's back;
5306/// `magi task release` is the explicit retry.
5307pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5308    run_claimed_until(opts, queue, task, &Stop::new()).await;
5309}
5310
5311async fn run_claimed_until(
5312    opts: &Opts,
5313    queue: &Queue,
5314    task: &mut Task,
5315    stop: &Stop,
5316) -> Vec<QuotaLoss> {
5317    let status = Arc::new(Mutex::new(Status::new()));
5318    // An attempt embeds startup and graph futures. Keep it off the standalone
5319    // caller's stack, on both the initial execution and withheld-text resume.
5320    let mut quota = Box::pin(attempt(
5321        opts,
5322        queue,
5323        &status,
5324        stop,
5325        crate::graph::Pause::new(),
5326        task,
5327    ))
5328    .await;
5329    // A run parked on the owner's word about a withheld PR title/body has no
5330    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5331    // here with the claim still held, and resume once the question is settled
5332    // (answered, or abandoned at its deadline -> the neutral text).
5333    // A rejected reply files one more question (the gate asks at most twice),
5334    // so after a resume the run may be waiting again: keep going, with a fresh
5335    // limit for the new question. `resumes` bounds it even if a resume parks
5336    // without asking anything new.
5337    let mut resumes = 0;
5338    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5339        let Some(timeout) = withheld_text_wait(task) else {
5340            break;
5341        };
5342        eprintln!(
5343            "waiting for the owner's answer on a withheld pull request text \
5344             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5345        );
5346        // The deadline abandons the question itself; the extra margin only
5347        // covers an abandon that could not be saved.
5348        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5349        let ready = loop {
5350            match land_resume_state(task) {
5351                LandResume::StillWaiting
5352                    if !stop.parking() && std::time::Instant::now() < limit =>
5353                {
5354                    tokio::time::sleep(WITHHELD_POLL).await;
5355                }
5356                LandResume::Ready => break true,
5357                _ => break false,
5358            }
5359        };
5360        if !ready || stop.parking() {
5361            break;
5362        }
5363        resumes += 1;
5364        quota.extend(
5365            Box::pin(attempt(
5366                opts,
5367                queue,
5368                &status,
5369                stop,
5370                crate::graph::Pause::new(),
5371                task,
5372            ))
5373            .await,
5374        );
5375    }
5376    hold_if_runnable(queue, task);
5377    quota
5378}
5379
5380/// Resumes an in-process run makes for withheld-text questions: the gate asks
5381/// at most twice, plus one for a resume that asks nothing new.
5382const MAX_WITHHELD_RESUMES: u32 = 3;
5383
5384/// How often an in-process run rechecks its withheld-text question.
5385const WITHHELD_POLL: Duration = Duration::from_secs(15);
5386
5387/// The `answer_timeout` (seconds) of the task's last run when that run is
5388/// parked on an unresolved withheld-text question; `None` otherwise.
5389fn withheld_text_wait(task: &Task) -> Option<u64> {
5390    let id = task.execution_runs().last()?;
5391    let s = RunState::load(id).ok()?;
5392    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5393        .then_some(s.config.graph.answer_timeout)
5394}
5395
5396/// The quota losses `after` holds that `before` did not: what one execution
5397/// suffered, as opposed to the run's history.
5398///
5399/// Compared by value rather than by length or position because
5400/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5401/// the vector can shrink and shift under a resume. A retried seat that hits
5402/// quota again is a `push` with a new `at`, so it shows up as new here.
5403/// Crash recovery uses the recorded pass start as its boundary when available;
5404/// legacy records without passes retain their original history-based policy.
5405fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5406    after
5407        .iter()
5408        .filter(|q| !before.contains(q))
5409        .cloned()
5410        .collect()
5411}
5412
5413/// When the loop-wide quota cooldown should end, given this attempt's losses;
5414/// `None` when there were none. Reset-hint parsing and the cap live here.
5415fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5416    let quota: Vec<_> = quota
5417        .iter()
5418        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5419        .collect();
5420    if quota.is_empty() {
5421        return None;
5422    }
5423    let with_hint = quota.iter().find(|q| q.reset.is_some());
5424    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5425    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5426    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5427    Some(
5428        now.checked_add(jiff::SignedDuration::from_secs(secs))
5429            .unwrap_or(Timestamp::MAX),
5430    )
5431}
5432
5433/// An explicit task count must agree with a run before any resume.
5434fn implementers_match(task: &Task, state: &RunState) -> bool {
5435    task.replacement.as_ref().map_or_else(
5436        || {
5437            task.implementers()
5438                .is_none_or(|n| n == state.config.graph.implementers)
5439        },
5440        |replacement| {
5441            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5442                && state.config.graph.implementers == 1
5443        },
5444    )
5445}
5446
5447/// Never resume or take over candidate work built for a different seat count.
5448fn starter_with_implementers(
5449    task: &Task,
5450    previous: Option<&RunState>,
5451    proposed: Starter,
5452) -> Starter {
5453    if previous.is_some_and(|s| !implementers_match(task, s)) {
5454        task.review_of
5455            .as_ref()
5456            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5457    } else {
5458        proposed
5459    }
5460}
5461
5462/// Apply this task's explicit count to the new attempt, without changing defaults.
5463fn apply_task_implementers(config: &mut Config, task: &Task) {
5464    if let Some(n) = task.implementers() {
5465        config.graph.implementers = n;
5466    }
5467}
5468
5469/// [`prepare`] for one task: its own `--config` and command-line overrides
5470/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5471/// over the loop's, so handing a hand-started task to a daemon changes nothing
5472/// about what it does.
5473#[cfg(test)]
5474fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5475    let explicit = match &task.overrides {
5476        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5477        _ => opts.config.as_deref(),
5478    };
5479    let (mut config, _) = Config::discover(repo, explicit)?;
5480    apply_options(&mut config, opts, task)?;
5481    Ok(config)
5482}
5483
5484fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5485    if task
5486        .overrides
5487        .as_ref()
5488        .is_none_or(|o| o.inherit_daemon_options)
5489        && let Some(mode) = opts.merge.as_deref()
5490    {
5491        config.merge.mode = merge_mode(mode)?;
5492    }
5493    if let Some(o) = &task.overrides {
5494        o.apply(config);
5495    }
5496    Ok(())
5497}
5498
5499/// Load the config for a task's repository, with the merge override applied.
5500fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5501    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5502    if let Some(mode) = &opts.merge {
5503        config.merge.mode = merge_mode(mode)?;
5504    }
5505    Ok(config)
5506}
5507
5508/// Prune the shared build cache at a between-runs boundary. The detached cache
5509/// service checks authoritative task jobs first; dispatch waits for that finite
5510/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5511/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5512async fn maybe_prune_cache_between_runs(
5513    repo: &Path,
5514    opts: &Opts,
5515    home: &Path,
5516    stop: &Stop,
5517    last_checked: &mut Option<Timestamp>,
5518    now: Timestamp,
5519) {
5520    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5521        return;
5522    }
5523    *last_checked = Some(now);
5524    let cfg = match prepare(repo, opts) {
5525        Ok(cfg) => cfg,
5526        Err(e) => {
5527            tracing::warn!("cache check: no config: {e:#}");
5528            return;
5529        }
5530    };
5531    match clean::prune_cache_if_over_limit(&cfg, home) {
5532        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5533            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5534            pruned.files,
5535            pruned.freed
5536        ),
5537        Ok(_) => {}
5538        Err(e) => {
5539            tracing::warn!("housekeep: prune cache: {e:#}");
5540            notices::raise_in(
5541                home,
5542                Notice::warn(
5543                    "housekeep:cache",
5544                    format!(
5545                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5546                        e.to_string()
5547                            .lines()
5548                            .next()
5549                            .unwrap_or("unknown cleanup error")
5550                    ),
5551                ),
5552            );
5553        }
5554    }
5555}
5556
5557/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5558/// now, given when it last did (if ever). Pure, so the cadence is asserted
5559/// directly rather than by waiting out real minutes in a test.
5560fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5561    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5562}
5563
5564/// The disk janitor, with its housekeeping logged rather than fatal.
5565///
5566/// Called only at the loop's idle points, for the reason the caller documents:
5567/// a prune racing a live compile would delete files mid-build. The config is
5568/// re-read on every call because the repository that just ran may not be the
5569/// daemon's own default, and the cache directory is a repository fact.
5570///
5571/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5572/// and [`crate::run::default_worktree_root`] read here, for the same reason
5573/// [`drive`] takes its queue and status file rather than resolving them: a
5574/// test driving the loop must not reach through to the operator's real home
5575/// or worktree bay just because the janitor runs on every idle tick.
5576/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5577/// to get wrong silently - a test's `home` was already isolated, but nothing
5578/// exercised the parameter next to it, so a real worktree bay stayed wired in
5579/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5580/// it for real, every test in this file that drives the loop at all started
5581/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5582async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5583    let cfg = match prepare(repo, opts) {
5584        Ok(cfg) => cfg,
5585        Err(e) => {
5586            tracing::warn!("housekeep: no config: {e:#}");
5587            return;
5588        }
5589    };
5590    // A run's own worktree lives under `config.graph.worktree_root` when the
5591    // repository sets one - the same precedence `RunState::worktree_root`
5592    // uses - and `worktrees_root` only stands in for the *default* an
5593    // unconfigured repository resolves to (see this function's own
5594    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5595    // that always swept the default regardless of this override would never
5596    // see, and so never reclaim, a single worktree for a repository that
5597    // relocated them elsewhere.
5598    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5599    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5600    // Reported whenever there is anything to say, not only when `folded > 0`:
5601    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5602    // folded, on every single pass, for months - a report gated on `folded`
5603    // would have stayed silent through every one of them.
5604    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5605        let mut extra = Vec::new();
5606        if out.unreadable > 0 {
5607            extra.push(format!("{} unreadable", out.unreadable));
5608        }
5609        if out.orphaned_worktrees > 0 {
5610            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5611        }
5612        let detail = if extra.is_empty() {
5613            String::new()
5614        } else {
5615            format!(" ({})", extra.join(", "))
5616        };
5617        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5618    }
5619    if out.external_merges_recorded > 0 {
5620        tracing::info!(
5621            "housekeep: recorded {} run(s) as merged externally",
5622            out.external_merges_recorded
5623        );
5624    }
5625    if out.stale_pr_states_repaired > 0 {
5626        tracing::info!(
5627            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5628            out.stale_pr_states_repaired
5629        );
5630    }
5631    if out.cache_files > 0 {
5632        tracing::info!(
5633            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5634            out.cache_files,
5635            out.cache_freed
5636        );
5637    }
5638    if out.questions_abandoned > 0 {
5639        tracing::info!(
5640            "housekeep: abandoned {} question(s) left open by a finished run",
5641            out.questions_abandoned
5642        );
5643    }
5644}
5645
5646/// Run [`triage::run_once`] and log whatever it did, the same "only when
5647/// there is something to say" rule [`janitor`] follows for its own report.
5648///
5649/// Called at the same idle points as [`janitor`] - once per full poll
5650/// interval, never mid-attempt - for the same reason: it is not liveness
5651/// critical, and a task's own `hold_reason` string is the one thing this
5652/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5653/// tick for no benefit.
5654async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5655    let questions = Questions::at(home.join("questions"));
5656    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5657    if report.is_empty() {
5658        return;
5659    }
5660    if !report.quarantined.is_empty() {
5661        tracing::info!(
5662            "triage: held {} blocked task(s) whose blocked-on task or \
5663             question no longer exists: {}",
5664            report.quarantined.len(),
5665            report.quarantined.join(", ")
5666        );
5667    }
5668    if !report.resumed.is_empty() {
5669        tracing::info!(
5670            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5671            report.resumed.len(),
5672            report.resumed.join(", ")
5673        );
5674    }
5675    if !report.asked.is_empty() {
5676        tracing::info!(
5677            "triage: asked about {} held task(s): {}",
5678            report.asked.len(),
5679            report.asked.join(", ")
5680        );
5681    }
5682    if !report.answered.is_empty() {
5683        tracing::info!(
5684            "triage: applied {} operator answer(s): {}",
5685            report.answered.len(),
5686            report.answered.join(", ")
5687        );
5688    }
5689}
5690
5691/// The free-space gate: what stands between this task and a new run, if
5692/// anything. `Some(reason)` holds the task; `None` lets it start.
5693///
5694/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5695/// the operator opted out. A measurement failure is a gate, not a pass: both
5696/// sides of "cannot tell" are served by not starting.
5697pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5698    disk_gate_with(repo, config, crate::disk::free_bytes)
5699}
5700
5701/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
5702/// test can assert the exact wiring `attempt` runs - config's threshold in,
5703/// task-holding reason out - without asking the real machine's disk anything.
5704fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5705    repo: &Path,
5706    config: &Config,
5707    free_bytes: F,
5708) -> Option<String> {
5709    let min = config.disk.min_free_bytes;
5710    if min == 0 {
5711        return None;
5712    }
5713    let mut paths = vec![repo.to_owned()];
5714    if let Some(cache) = config.cache_dir() {
5715        paths.push(cache);
5716    }
5717    paths.push(
5718        config
5719            .graph
5720            .worktree_root
5721            .clone()
5722            .unwrap_or_else(crate::run::default_worktree_root),
5723    );
5724    for path in paths {
5725        let probe = if path == repo {
5726            path.as_path()
5727        } else {
5728            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5729        };
5730        let reason = match free_bytes(probe) {
5731            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5732            Err(e) => Some(crate::disk::unmeasured_in(
5733                probe,
5734                &e,
5735                &config.graph.language,
5736            )),
5737        };
5738        if reason.is_some() {
5739            return reason;
5740        }
5741    }
5742    None
5743}
5744
5745/// How long to wait before offering another task when a run lost a seat to a
5746/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
5747/// could read, or carried nothing at all. Long enough that a quota outage
5748/// cannot burn through a whole backlog in the few seconds each doomed attempt
5749/// takes to fail; short enough that a quota which clears early is not left
5750/// idle for the fallback's sake.
5751const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5752
5753/// Longest a parsed reset hint may push the wait out to. The hint comes from
5754/// the CLI's own words, not a contract, so a parsing slip that lands a day
5755/// away must not leave the loop asleep for a day.
5756const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5757
5758/// How long [`poll`] should wait before offering the next task, after a run
5759/// lost at least one seat to a rate limit.
5760///
5761/// Pure and separate from the loop so the policy can be exercised without a
5762/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
5763/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
5764/// nothing to parse, or the parsed time has already passed; `cap` bounds how
5765/// far a parsed hint is trusted to push the wait out.
5766fn quota_wait(
5767    reset_at: Option<Timestamp>,
5768    now: Timestamp,
5769    fallback: Duration,
5770    cap: Duration,
5771) -> Duration {
5772    match reset_at {
5773        Some(at) if at > now => {
5774            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5775            Duration::from_secs(secs).min(cap)
5776        }
5777        _ => fallback,
5778    }
5779}
5780
5781/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
5782///
5783/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
5784/// explains why parsing it exactly "would be a bug factory" — so this only
5785/// recognises the shapes actually observed in the wild, and returns `None`
5786/// for anything else rather than guess at a format nobody has seen.
5787///
5788/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
5789/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
5790/// said it, not from whenever this loop happens to read it: anchoring on `now`
5791/// would push the reset later on every read and would read an already-elapsed
5792/// reset as still in the future. (A long hint is still clamped by
5793/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
5794fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5795    parse_reset_hint_zoned(text, now)
5796        .or_else(|| parse_reset_hint_dated(text))
5797        .or_else(|| parse_reset_hint_relative(text, recorded))
5798}
5799
5800/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
5801/// optional but at least one required, in that order. A bare number or any
5802/// unknown unit is refused.
5803fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5804    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5805    let mut rest = rest.trim();
5806    if rest.is_empty() {
5807        return None;
5808    }
5809    let mut total: i64 = 0;
5810    let mut matched = false;
5811    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5812        if let Some((digits, tail)) = rest.split_once(unit)
5813            && !digits.is_empty()
5814            && digits.bytes().all(|b| b.is_ascii_digit())
5815        {
5816            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5817            rest = tail;
5818            matched = true;
5819        }
5820    }
5821    if !rest.is_empty() || !matched {
5822        return None;
5823    }
5824    recorded
5825        .checked_add(jiff::SignedDuration::from_secs(total))
5826        .ok()
5827}
5828
5829/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
5830/// case-insensitive) into a 24-hour hour and minute. Shared by every
5831/// reset-hint shape below.
5832fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5833    let clock = clock.trim().to_lowercase();
5834    let (digits, pm) = clock
5835        .strip_suffix("am")
5836        .map(|d| (d, false))
5837        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5838    let (h, m) = digits.trim().split_once(':')?;
5839    let mut hour: i8 = h.trim().parse().ok()?;
5840    let minute: i8 = m.trim().parse().ok()?;
5841    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5842        return None;
5843    }
5844    if pm && hour != 12 {
5845        hour += 12;
5846    } else if !pm && hour == 12 {
5847        hour = 0;
5848    }
5849    Some((hour, minute))
5850}
5851
5852/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
5853/// and a zone, never a date. A clock reading already past today is read as
5854/// tomorrow's: a CLI naming a same-day reset that has already gone by means
5855/// the window rolled over while nothing was watching.
5856fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5857    let open = text.find('(')?;
5858    let close = text.rfind(')')?;
5859    if close <= open {
5860        return None;
5861    }
5862    let zone = text[open + 1..close].trim();
5863    let (hour, minute) = parse_12h_clock(&text[..open])?;
5864    let tz = jiff::tz::TimeZone::get(zone).ok()?;
5865    let candidate = now
5866        .to_zoned(tz)
5867        .with()
5868        .hour(hour)
5869        .minute(minute)
5870        .second(0)
5871        .millisecond(0)
5872        .microsecond(0)
5873        .nanosecond(0)
5874        .build()
5875        .ok()?;
5876    let mut at = candidate.timestamp();
5877    if at <= now {
5878        at += jiff::SignedDuration::from_hours(24);
5879    }
5880    Some(at)
5881}
5882
5883/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
5884/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
5885/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
5886/// "already past today" correction to make: the year already disambiguates
5887/// it. Scanned as a five-word window so it can be pulled out of the middle
5888/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
5889/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
5890/// any other timestamp with no zone attached.
5891fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5892    let words: Vec<&str> = text.split_whitespace().collect();
5893    if words.len() < 5 {
5894        return None;
5895    }
5896    (0..=words.len() - 5)
5897        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5898}
5899
5900/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
5901/// parenthesis right after the window is refused rather than ignored — it
5902/// reads as an explicit zone annotation on a shape that otherwise carries
5903/// none, and guessing UTC anyway would be exactly the silent misread this
5904/// module's parsing otherwise avoids.
5905fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5906    if trailing.is_some_and(|next| next.starts_with('(')) {
5907        return None;
5908    }
5909    let month = month_number(window[0])?;
5910    let day_token = window[1].strip_suffix(',')?.to_lowercase();
5911    let day_digits = ["st", "nd", "rd", "th"]
5912        .iter()
5913        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5914    let day: i8 = day_digits.parse().ok()?;
5915    let year_token = window[2];
5916    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5917        return None;
5918    }
5919    let year: i16 = year_token.parse().ok()?;
5920    // The am/pm word carries the sentence's own trailing punctuation, e.g.
5921    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
5922    // reusing the same 12-hour clock reader the bracketed shape uses.
5923    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5924    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5925    let date = jiff::civil::Date::new(year, month, day).ok()?;
5926    let candidate = date
5927        .at(hour, minute, 0, 0)
5928        .to_zoned(jiff::tz::TimeZone::UTC)
5929        .ok()?;
5930    Some(candidate.timestamp())
5931}
5932
5933/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
5934/// case-insensitively, into a 1-based month number.
5935fn month_number(name: &str) -> Option<i8> {
5936    const NAMES: [&str; 12] = [
5937        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5938    ];
5939    let lower = name.to_lowercase();
5940    NAMES
5941        .iter()
5942        .position(|n| *n == lower.as_str())
5943        .map(|i| i as i8 + 1)
5944}
5945
5946/// Test probe for the shared resume policy's review-budget exclusion.
5947#[cfg(test)]
5948fn exhausted_review_budget(state: &RunState) -> bool {
5949    // A run whose task-head publication failed has nothing left to review:
5950    // resuming it only retries the publication, so it is never "exhausted".
5951    !crate::handover::can_resume(state)
5952        && state.status == RunStatus::Blocked
5953        && !state.released()
5954        && state.retired_to.is_none()
5955}
5956
5957/// This task's *most recent* run, if resuming it would actually make
5958/// progress. `short` is only for the warning's own message.
5959///
5960/// Only ever `runs.last()` — never a search back through older history.
5961/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
5962/// mint, oldest first, and every entry before the last one was already
5963/// superseded at the moment it was minted: the daemon only ever starts a new
5964/// run when the previous one was not worth resuming (unresumable, exhausted,
5965/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
5966/// opens a fresh review-only run alongside an older, already-failed
5967/// competition. Searching further back would let an old run that merely
5968/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
5969/// behind, say — get resumed instead of the fresh competition
5970/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
5971/// nothing asked to revisit.
5972///
5973/// Two runs paid for the "prefer resuming over restarting" half of this
5974/// lesson, which is why this still checks `runs.last()` rather than always
5975/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
5976/// task a moment later, duplicating two and a half hours of agent work. Then
5977/// b25f stalled on a judge that timed out and one that answered with no JSON
5978/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
5979/// **one second** later, buying three fresh implementations to reach the
5980/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
5981/// the second case: a stall is terminal, and its cheap recovery re-asks only
5982/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
5983/// that is technically `resumable()` but provably cannot progress must not
5984/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
5985/// no-op instead of the fresh competition it promises.
5986///
5987/// A load failure is warned about rather than silently read as "not
5988/// resumable": the alternative is exactly what let a schema mismatch on run
5989/// `eba2` fall through to a full re-competition with nobody told why.
5990/// `crate::conduct` is what actually offers a better answer than
5991/// `Runner::start` here (see `Recovery::Review`), once this task's next
5992/// failure shows it up as `held`/`failed` with the run state unreadable.
5993fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5994    unfinished_run_with(runs, short, RunState::load)
5995}
5996
5997/// [`unfinished_run`] with an injected state reader. Tests provide their
5998/// fixtures directly rather than touching the process-global run home.
5999pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6000where
6001    F: FnMut(&str) -> Result<RunState>,
6002{
6003    let mut id = runs.last()?.clone();
6004    let mut visited = std::collections::BTreeSet::new();
6005    let mut repo = None;
6006    loop {
6007        if !runs.contains(&id) || !visited.insert(id.clone()) {
6008            tracing::warn!("invalid or cyclic recovery authority for task {short}");
6009            return None;
6010        }
6011        let state = match load(&id) {
6012            Ok(state) if state.id == id => state,
6013            Ok(_) => return None,
6014            Err(e) => {
6015                tracing::warn!("could not read run {id} for task {short}: {e:#}");
6016                return None;
6017            }
6018        };
6019        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6020            return None;
6021        }
6022        repo = Some(state.repo.clone());
6023        if let Some(authority) = state.retired_to {
6024            id = authority;
6025            continue;
6026        }
6027        return (crate::handover::can_resume(&state)
6028            && state.liveness(false) != crate::run::Liveness::Live)
6029            .then_some(id);
6030    }
6031}
6032
6033/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
6034/// that [`attempt`] will resume it on its own?
6035///
6036/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
6037/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
6038/// injected reader like its sibling. An unreadable run is not awaiting
6039/// anything: it keeps going to the conductor as before.
6040fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6041where
6042    F: FnOnce(&str) -> Result<RunState>,
6043{
6044    // `Failed` stays: a record an older build wrote for a parked run.
6045    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6046        || task.fresh_start
6047        || task.review_branch.is_some()
6048    {
6049        return false;
6050    }
6051    let Some(id) = task.execution_runs().last() else {
6052        return false;
6053    };
6054    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6055}
6056
6057/// Which of the three ways [`attempt`] can mint or continue a run this task
6058/// should use.
6059#[derive(Debug, Clone, PartialEq, Eq)]
6060enum Starter {
6061    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
6062    /// and that still exists.
6063    Review(String),
6064    /// `crate::graph::Runner::resume` on an unfinished run of this task.
6065    Resume(String),
6066    /// `crate::graph::Runner::start`: a fresh competition.
6067    Start,
6068}
6069
6070/// A second bound independent of inputs and the resettable failure counter.
6071/// Count execution and failed-startup recovery records once per run. Startup
6072/// failures can retain unrecorded preparation assets without an execution pass.
6073/// Unknown history is not evidence that a new set of worktrees is affordable.
6074fn retained_attempt_hold(
6075    task: &Task,
6076    starter: &Starter,
6077    limit: usize,
6078    mut load: impl FnMut(&str) -> Result<RunState>,
6079) -> Option<String> {
6080    if limit == 0 || matches!(starter, Starter::Resume(_)) {
6081        return None;
6082    }
6083    let mut retained = 0;
6084    for id in task
6085        .runs
6086        .iter()
6087        .chain(task.startup_failures.iter().map(|failure| &failure.run))
6088        .collect::<std::collections::BTreeSet<_>>()
6089    {
6090        let state = match load(id) {
6091            Ok(state) if state.id == *id => state,
6092            _ => {
6093                return Some(format!(
6094                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6095                ));
6096            }
6097        };
6098        if state.retired_to.is_some() || state.released() {
6099            continue;
6100        }
6101        // Neither a completed status nor an empty candidate array proves that
6102        // all recovery sources (including unrecorded preparation) were retired.
6103        retained += 1;
6104    }
6105    (retained >= limit).then(|| format!(
6106        "[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."
6107    ))
6108}
6109
6110/// A selected public implementation overrides every historical candidate and pin.
6111fn selected_starter(
6112    selected: &crate::pr_recovery::Selection,
6113    previous: Option<&RunState>,
6114    unfinished: Option<&str>,
6115) -> Starter {
6116    if let Some(id) = unfinished
6117        && previous.is_some_and(|r| {
6118            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6119        })
6120    {
6121        Starter::Resume(id.to_owned())
6122    } else {
6123        Starter::Review(selected.branch.clone())
6124    }
6125}
6126
6127/// The owner's answer to this branch's divergence question, consumed from the
6128/// task so a later, different divergence asks again. The runner applies it
6129/// (see `Runner::review_taking_over`), after the earlier worktree is released.
6130fn take_divergence_answer(
6131    branch: &str,
6132    remote: &str,
6133    task: &mut Task,
6134) -> Option<crate::reconcile::Choice> {
6135    let summary = crate::reconcile::summary_for(branch, remote);
6136    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6137        (a.question == summary)
6138            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6139            .flatten()
6140            .map(|c| (i, c))
6141    })?;
6142    task.answers.remove(idx);
6143    Some(choice)
6144}
6145
6146/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
6147/// this attempt should use. Pure, and separate from [`attempt`], so the
6148/// routing itself is assertable without spawning a real graph or a git
6149/// process: `attempt`'s own `crate::git::branch_exists` call has already
6150/// happened by the time this is called.
6151///
6152/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
6153/// whose branch is gone falls all the way through to [`Starter::Start`], not
6154/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
6155/// old (likely `Blocked`) run in the first place, and a branch that vanished
6156/// out from under that choice is not evidence resuming it would fare better.
6157fn choose_starter(
6158    review_branch: Option<&str>,
6159    branch_exists: bool,
6160    unfinished: Option<&str>,
6161) -> Starter {
6162    match review_branch {
6163        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6164        Some(_) => Starter::Start,
6165        None => match unfinished {
6166            Some(id) => Starter::Resume(id.to_owned()),
6167            None => Starter::Start,
6168        },
6169    }
6170}
6171
6172/// Reuse a compatible latest review owner instead of taking its checked-out
6173/// branch into a new run. Different branches and changed criteria still use
6174/// the ordinary review/takeover policy.
6175fn review_retry_starter(
6176    task: &Task,
6177    previous: Option<&RunState>,
6178    branch: Option<&str>,
6179    exists: bool,
6180    unfinished: Option<&str>,
6181) -> Starter {
6182    if let Some(run) = previous
6183        && unfinished == Some(run.id.as_str())
6184        && run.reviewed_commits.is_some()
6185        && branch.is_some_and(|branch| {
6186            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6187        })
6188        && may_resume_run(run, task)
6189    {
6190        return Starter::Resume(run.id.clone());
6191    }
6192    match (branch, unfinished, &task.review_of) {
6193        (None, None, Some(branch)) => Starter::Review(branch.clone()),
6194        _ => choose_starter(branch, exists, unfinished),
6195    }
6196}
6197
6198/// Consume a retained review only while its authored criteria still match.
6199fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
6200    let branch = task.review_branch.take();
6201    let instruction = task.review_instruction.take();
6202    branch.filter(|branch| match &instruction {
6203        Some(authored) => *authored == task.instruction,
6204        // Legacy retained branches must agree with their prior run; only an
6205        // explicitly pinned review can proceed without recoverable provenance.
6206        None => previous.map_or_else(
6207            || task.review_of.as_ref() == Some(branch),
6208            |run| compatible_run_instruction(run, task),
6209        ),
6210    })
6211}
6212
6213/// A current explicit pin can select an otherwise incompatible run. Edits
6214/// and subsequent approvals invalidate pins selected for earlier criteria.
6215fn may_resume_run(run: &RunState, task: &Task) -> bool {
6216    if !task.assignment_accepts(run) {
6217        return false;
6218    }
6219    task.resume_override
6220        .as_ref()
6221        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6222        || compatible_run_instruction(run, task)
6223}
6224
6225/// Review scaffolding is execution context, not evidence of an operator edit.
6226pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6227    if let Some(authored) = &run.task_instruction {
6228        return compatible_instruction(authored, task);
6229    }
6230    if compatible_instruction(&run.instruction, task) {
6231        return true;
6232    }
6233    // Recognize only the existing generated review shapes on legacy runs.
6234    // Ordinary authored text with a similar heading is left intact.
6235    if run.reviewed_commits.is_some() {
6236        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6237            return strip_answers_block(authored, task).trim() == task.instruction.trim();
6238        }
6239        if let Some(branch) = &task.review_of {
6240            let canonical = format!(
6241                "Review the branch `{branch}` (review-only: no implementation, no judging)."
6242            );
6243            let generated = format!(
6244                "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"
6245            );
6246            return task.instruction == canonical && run.instruction.starts_with(&generated);
6247        }
6248    }
6249    false
6250}
6251
6252/// Compare authored instructions, excluding answer blocks appended by the daemon.
6253pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6254    strip_answers_block(old, task) == task.instruction
6255}
6256
6257/// Which repository a task runs in. A task that names none — the normal case
6258/// for one filed from a phone — runs in the daemon's own default.
6259fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6260    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6261        return fallback.to_path_buf();
6262    }
6263    task.repo.clone()
6264}
6265
6266/// The header [`append_answers`] appends operator answers under. Shared with
6267/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
6268/// rather than grown a new block on every resume.
6269const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6270
6271/// Render the first `count` answers in the block appended to an instruction.
6272fn answers_block(task: &Task, count: usize) -> String {
6273    let mut s = ANSWERS_HEADER.to_owned();
6274    for a in &task.answers[..count] {
6275        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6276    }
6277    s
6278}
6279
6280/// Render the approval independently of transient task state, so historical
6281/// suffixes remain recognizable after another explicit release.
6282fn resumption_block(r: &crate::queue::Resumption) -> String {
6283    format!(
6284        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6285         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6286        r.generation, r.at, r.instruction, r.answers_through,
6287    )
6288}
6289
6290/// Append audit answers and the latest explicit approval to the instruction.
6291fn append_answers(base: &str, task: &Task) -> String {
6292    let mut s = base.to_owned();
6293    if !task.answers.is_empty() {
6294        s.push_str(&answers_block(task, task.answers.len()));
6295    }
6296    if let Some(r) = &task.resumption {
6297        s.push_str(&resumption_block(r));
6298    }
6299    s
6300}
6301
6302/// Drop the prior answer block only when it is exactly the suffix this task
6303/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6304/// the task author is ordinary instruction text, not a block to remove.
6305fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6306    let mut instruction = instruction;
6307    for approval in task
6308        .resumption
6309        .iter()
6310        .chain(task.resumption_history.iter().rev())
6311    {
6312        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6313            instruction = base;
6314            break;
6315        }
6316    }
6317    for count in (1..=task.answers.len()).rev() {
6318        let block = answers_block(task, count);
6319        if let Some(base) = instruction.strip_suffix(&block) {
6320            return base;
6321        }
6322    }
6323    instruction
6324}
6325
6326/// The instruction handed to `Runner::start`: the task's own text, plus any
6327/// operator answers `crate::conduct` collected for it (see
6328/// [`Task::answers`]), so a decision the operator actually made reaches the
6329/// implementers rather than only clearing the block that was waiting on it.
6330///
6331/// Appended rather than merged into [`Task::instruction`] itself, so the
6332/// task's own record stays exactly what its author wrote.
6333fn instruction_for(task: &Task) -> String {
6334    append_answers(&task.instruction, task)
6335}
6336
6337/// The instruction a resumed run should carry on with: whatever it already
6338/// had, refreshed with the task's *current* operator answers.
6339///
6340/// A resumable run's own `RunState::instruction` predates any answer
6341/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6342/// the behaviour before this function existed — silently drops the very
6343/// decision the operator made to unblock it. Re-stripping any block this
6344/// function appended on an earlier resume before re-appending the current
6345/// list (rather than blindly appending again) is what keeps a task resumed
6346/// three times over three answered questions from carrying the same answer
6347/// three times.
6348fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6349    append_answers(strip_answers_block(old_instruction, task), task)
6350}
6351
6352/// Preserve the producer's verified boundary and target, independent of prose.
6353fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6354    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6355    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6356    if let Some(cause) = task.hold_notice_cause.as_mut() {
6357        cause.target = failure.map(|f| f.target.clone());
6358    }
6359}
6360
6361#[derive(Debug, thiserror::Error)]
6362#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6363struct MissingAttachment {
6364    name: String,
6365    path: PathBuf,
6366}
6367
6368/// The task's attachments as absolute paths, each checked to still exist.
6369fn task_attachments(
6370    queue: &Queue,
6371    task: &Task,
6372) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6373    let paths = queue.attachment_paths(task);
6374    for (name, path) in task.attachments.iter().zip(&paths) {
6375        if !path.is_file() {
6376            return Err(MissingAttachment {
6377                name: name.clone(),
6378                path: path.clone(),
6379            });
6380        }
6381    }
6382    Ok(paths)
6383}
6384
6385/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6386/// answers before handing it to `Runner` — the actual boundary between
6387/// [`choose_starter`]'s routing and the graph, factored out so it is
6388/// assertable without a real repository, git branch, or agent CLI.
6389///
6390/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6391/// instruction from the reviewed branch's own commit log because there is no
6392/// task statement to speak of for hand-written work, and splicing operator
6393/// answers into that text would contradict the very message it sends
6394/// reviewers ("there is no task statement").
6395fn prepare_instruction(
6396    starter: &Starter,
6397    old_instruction: Option<&str>,
6398    task: &Task,
6399) -> Option<String> {
6400    match starter {
6401        Starter::Start => Some(instruction_for(task)),
6402        Starter::Resume(_) => Some(resumed_instruction(
6403            old_instruction.expect("a resumed run always has a prior instruction"),
6404            task,
6405        )),
6406        Starter::Review(_) => None,
6407    }
6408}
6409
6410/// Persist a transition. A queue write failure is logged rather than fatal: the
6411/// run already happened, and taking the daemon down would only add a lost
6412/// backlog to a full disk.
6413fn record(queue: &Queue, task: &mut Task) {
6414    if let Err(e) = queue.put(task) {
6415        tracing::error!("could not record task {}: {e:#}", task.short());
6416        let notice = Notice::error(
6417            "loop:record",
6418            format!(
6419                "Task {} state could not be saved: {}. Check the disk.",
6420                task.id,
6421                e.to_string().lines().next().unwrap_or("unknown save error")
6422            ),
6423        )
6424        .link(Link::Task {
6425            id: task.id.clone(),
6426        });
6427        // The queue lives at `<home>/queue`, so its parent is the home.
6428        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6429            Some(home) => notices::raise_in(home, notice),
6430            None => notices::raise(notice),
6431        }
6432    }
6433}
6434
6435/// Every runnable task, in the order the loop should try them.
6436///
6437/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6438/// tail exists so that a claim somebody else holds costs the loop the next
6439/// candidate rather than a whole poll interval of idleness.
6440fn runnable(queue: &Queue) -> Vec<Task> {
6441    let mut tasks: Vec<Task> = queue
6442        .list()
6443        .into_iter()
6444        .filter(|t| t.status.runnable())
6445        .collect();
6446    tasks.sort_unstable_by(crate::queue::dispatch_order);
6447    tasks
6448}
6449
6450/// Why a run ended where it did, in one line, for [`Task::last_error`].
6451///
6452/// A stalled run names the seats the quota took out: "out of quota" is not
6453/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6454/// agent to replace or which plan to top up.
6455///
6456/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6457/// purpose: unlike `label`'s other callers (an internal log line, an
6458/// already-a-bug fallback message), this string becomes `Task::last_error`
6459/// verbatim, which the phone renders in the same alarm-styled box an
6460/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6461/// `.err` styling. A bare `verified_noop` there would read exactly like the
6462/// failure this whole feature exists to tell apart from one.
6463fn describe(state: &RunState) -> String {
6464    let p = phrases(&state.config.graph.language);
6465    let mut detail = if state.status == RunStatus::Stalled {
6466        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6467        seats.sort_unstable();
6468        seats.dedup();
6469        if seats.is_empty() {
6470            p.quorum_lost.to_owned()
6471        } else {
6472            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6473        }
6474    } else {
6475        format!("{}{}", p.run_ended, state.status.display_label())
6476    };
6477    if let Some(cause) = state.verification_blocking_cause() {
6478        detail.push_str(&format!(" ({cause})"));
6479    } else if let Some(last) = state.events.last() {
6480        // The review loop's "never answered" stop is the one event worth
6481        // translating; it is recognised from structured state, not by
6482        // matching the English event text (which stays as recorded).
6483        let unanswered = state
6484            .reviews
6485            .last()
6486            .filter(|r| {
6487                state.status == RunStatus::Blocked
6488                    && last.node == "review"
6489                    && r.incomplete()
6490                    && r.blocking == 0
6491                    && r.round == state.config.graph.review_rounds
6492                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6493            })
6494            .map(|r| (r.expected - r.answered, r.round));
6495        match unanswered {
6496            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6497                detail.push_str(&format!(
6498                    " ({}: {})",
6499                    last.node,
6500                    (p.reviewers_never_answered)(missing, rounds)
6501                ));
6502            }
6503            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6504        }
6505    }
6506    detail.push_str(&format!(" [run {}]", state.id));
6507    detail
6508}
6509
6510/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6511///
6512/// The task file lives in the backlog indefinitely; a diagnostic is an
6513/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6514/// stay small regardless of how much a gate command or a candidate printed.
6515const DIAGNOSTIC_MAX: usize = 4_000;
6516
6517/// Tail kept from a single failing command's output inside a diagnostic.
6518/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6519/// pointer for a human deciding whether to go read the full artifact by hand,
6520/// not a replacement for reading it.
6521const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6522
6523/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6524/// `magi task show` says more than the one-line reason in [`describe`].
6525///
6526/// The one-liner answers "where did the run stop"; this answers "what would a
6527/// human have found opening `artifacts/` by hand" — the point of the whole
6528/// feature is the case that one-liner actively misleads on: a run held as "no
6529/// candidate produced a change" can mean the implementer actually finished
6530/// the task (opened a PR, merged it, tagged a release) and only left a clean
6531/// local worktree behind, which reads as "nothing happened" unless someone
6532/// goes and reads what the agent actually said. `None` when the run carries
6533/// none of the three shapes this recognises — an ordinary run held for
6534/// something not diagnosable from `RunState` alone still explains itself
6535/// through `Task::last_error`.
6536fn diagnostic(state: &RunState) -> Option<String> {
6537    let mut parts: Vec<String> = Vec::new();
6538
6539    // Gate failure: which check(s), and the tail of what each printed.
6540    for o in state.gate.iter().filter(|o| !o.ok()) {
6541        parts.push(format!(
6542            "gate `{}` failed ({}):\n{}",
6543            o.command,
6544            notices::exit_status(o.code),
6545            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6546        ));
6547    }
6548
6549    // The land loop gave up because the fixer declined while checks were
6550    // still red: the message already names them (see `land::run`).
6551    if let Some(last) = state
6552        .events
6553        .iter()
6554        .rev()
6555        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6556    {
6557        parts.push(last.message.clone());
6558    }
6559
6560    // No viable candidate: every implementer's own final word, sanitized the
6561    // same way a judge would have read it, so a run that actually finished
6562    // the job does not read as an unexplained failure. A verified no-op is
6563    // called out ahead of its own summary and apart from an ordinary
6564    // failure's `why` — this is the one candidate shape whose diagnostic a
6565    // human is expected to actually judge, not just skim.
6566    if state.viable().is_empty() {
6567        for c in &state.candidates {
6568            if let Some(evidence) = &c.verified_noop {
6569                parts.push(format!(
6570                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6571                    c.label
6572                ));
6573            } else if !c.summary.trim().is_empty() {
6574                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6575            } else if let Some(why) = &c.failed {
6576                parts.push(format!("candidate {}: {why}", c.label));
6577            }
6578        }
6579    }
6580
6581    if parts.is_empty() {
6582        return None;
6583    }
6584    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6585    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6586    // back slightly over. Leave it enough room to always land under the
6587    // limit.
6588    Some(crate::run::tail(
6589        &parts.join("\n\n"),
6590        DIAGNOSTIC_MAX.saturating_sub(100),
6591    ))
6592}
6593
6594/// Stable lower-case name for a run status, for an internal log line and the
6595/// "graph stopped without reaching a terminal status" bug message in
6596/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6597/// doc for why that one reads [`RunStatus::display_label`] instead. One
6598/// definition of a status's name, on the type that owns it: this table used
6599/// to live here as a second copy, and a status renamed in one place would
6600/// have gone on reading correctly in the other.
6601fn label(status: RunStatus) -> &'static str {
6602    status.as_str()
6603}
6604
6605/// Parse a merge mode override.
6606pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6607    match mode {
6608        "none" => Ok(MergeMode::None),
6609        "local" => Ok(MergeMode::Local),
6610        "pr" => Ok(MergeMode::Pr),
6611        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6612    }
6613}
6614
6615/// Take the status lock, recovering from a poisoned one.
6616///
6617/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6618/// data, and the worst a poisoned lock can hold is a stale timestamp.
6619fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6620    mutex
6621        .lock()
6622        .unwrap_or_else(std::sync::PoisonError::into_inner)
6623}
6624
6625#[cfg(test)]
6626mod tests {
6627    use super::*;
6628    use crate::queue::{Source, TaskStatus};
6629    use crate::run::{Candidate, CommandOutcome};
6630    use pretty_assertions::assert_eq;
6631
6632    fn task() -> Task {
6633        Task::new(
6634            "add retries".to_owned(),
6635            "add retries".to_owned(),
6636            PathBuf::from("/repo"),
6637            Source::Human,
6638        )
6639    }
6640
6641    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6642        let job = crate::worker::Job {
6643            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6644            sequence: 1,
6645            kind: "task".into(),
6646            key: format!("task:{}", request.task),
6647            payload: serde_json::to_value(request).unwrap(),
6648            generation: "a".repeat(64),
6649            version: None,
6650            status: crate::worker::Status::Starting,
6651            result: None,
6652            pid: None,
6653            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6654            finished_at: None,
6655        };
6656        let dir = home.join("workers/jobs").join(&job.id);
6657        std::fs::create_dir_all(&dir).unwrap();
6658        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6659        job
6660    }
6661
6662    #[test]
6663    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6664        let home = tempfile::tempdir().unwrap();
6665        let request = TaskWorker {
6666            opts: Opts::default(),
6667            queue: home.path().join("queue"),
6668            task: "startup".into(),
6669            lane: PermitKind::Ordinary,
6670            standalone: false,
6671        };
6672        let job = starting_task_reservation(home.path(), &request);
6673        let error = task_worker_spawn_error(
6674            home.path(),
6675            &request,
6676            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6677        )
6678        .expect_err("our own reservation must not turn a failed spawn into a resync");
6679        let active = crate::worker::active(home.path()).unwrap();
6680        assert_eq!(active.len(), 1);
6681        assert_eq!(active[0].id, job.id);
6682        assert_eq!(active[0].status, crate::worker::Status::Starting);
6683        assert!(
6684            crate::worker::control(home.path(), &job.key)
6685                .unwrap()
6686                .is_none()
6687        );
6688        let notices = notices::Notices::at(home.path().join("notifications")).list();
6689        assert_eq!(notices.len(), 1);
6690        assert_eq!(notices[0].key, "loop:worker-startup");
6691        assert!(!notices[0].message.contains("private-error-detail"));
6692        assert!(notices[0].message.contains(&request.task));
6693        assert!(
6694            notices[0]
6695                .message
6696                .contains("could not be started or acknowledged")
6697        );
6698        assert!(notices[0].message.contains("worker.log"));
6699        assert_eq!(
6700            notices[0].link,
6701            Some(Link::Task {
6702                id: request.task.clone()
6703            })
6704        );
6705        assert!(format!("{error:#}").contains("private-error-detail"));
6706    }
6707
6708    #[test]
6709    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6710        let home = tempfile::tempdir().unwrap();
6711        let mut request = TaskWorker {
6712            opts: Opts::default(),
6713            queue: home.path().join("queue"),
6714            task: "handoff".into(),
6715            lane: PermitKind::Ordinary,
6716            standalone: true,
6717        };
6718        let job = starting_task_reservation(home.path(), &request);
6719        request.standalone = false;
6720        task_worker_spawn_error(
6721            home.path(),
6722            &request,
6723            anyhow::anyhow!("operation key is already reserved for a different request"),
6724        )
6725        .expect("a different standalone request is the handoff race, not our startup failure");
6726        let active = crate::worker::active(home.path()).unwrap();
6727        assert_eq!(active.len(), 1);
6728        assert_eq!(active[0].id, job.id);
6729        assert_eq!(active[0].payload, job.payload);
6730        assert!(
6731            notices::Notices::at(home.path().join("notifications"))
6732                .list()
6733                .is_empty()
6734        );
6735    }
6736
6737    #[test]
6738    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6739        let home = tempfile::tempdir().unwrap();
6740        let queue = Queue::at(home.path().join("queue"));
6741        let mut task = task();
6742        task.runs = vec!["previous".into()];
6743        queue.put(&mut task).unwrap();
6744        let request = TaskWorker {
6745            opts: Opts::default(),
6746            queue: home.path().join("queue"),
6747            task: task.id.clone(),
6748            lane: PermitKind::Ordinary,
6749            standalone: false,
6750        };
6751        let job = starting_task_reservation(home.path(), &request);
6752        let claims = current_work(home.path(), Timestamp::now());
6753        assert_eq!(claims.len(), 1);
6754        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6755        assert_eq!(claims[0].run, "previous");
6756        assert!(other_claims_run(&claims, "previous", None));
6757        // Only after confirming the executing caller may admission ignore
6758        // this exact projection. Cleanup continues to observe it as live.
6759        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6760        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6761    }
6762
6763    #[test]
6764    fn admission_excludes_only_the_callers_exact_reservation() {
6765        let own = Current {
6766            worker: Some("own".into()),
6767            task: "same-task".into(),
6768            run: "previous".into(),
6769        };
6770        assert!(!other_claims_run(
6771            std::slice::from_ref(&own),
6772            "previous",
6773            Some("own")
6774        ));
6775        assert!(other_claims_run(
6776            std::slice::from_ref(&own),
6777            "previous",
6778            None
6779        ));
6780        for worker in [None, Some("other".into())] {
6781            let other = Current {
6782                worker,
6783                ..own.clone()
6784            };
6785            assert!(other_claims_run(
6786                &[own.clone(), other],
6787                "previous",
6788                Some("own")
6789            ));
6790        }
6791        let legacy: Current =
6792            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6793        assert!(other_claims_run(&[legacy], "previous", Some("own")));
6794    }
6795
6796    #[test]
6797    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6798        let mut task = task();
6799        let mut run = run_state(RunStatus::Reviewing);
6800        run.task_instruction = Some(task.instruction.clone());
6801        run.reviewed_commits = Some(vec!["committed-fix".into()]);
6802        let branch = "magi/test/B";
6803        run.candidates.push(crate::run::Candidate {
6804            branch: branch.into(),
6805            ..candidate('B', "preserved work", false, None)
6806        });
6807        task.runs = vec![run.id.clone()];
6808        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6809        assert_eq!(
6810            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6811            Starter::Resume(run.id.clone())
6812        );
6813        assert!(matches!(
6814            review_retry_starter(
6815                &task,
6816                Some(&run),
6817                Some("different"),
6818                true,
6819                unfinished.as_deref()
6820            ),
6821            Starter::Review(_)
6822        ));
6823        assert_eq!(
6824            review_retry_starter(
6825                &task,
6826                Some(&run),
6827                Some(branch),
6828                false,
6829                unfinished.as_deref()
6830            ),
6831            Starter::Start
6832        );
6833        task.instruction.push_str(" changed criteria");
6834        assert!(matches!(
6835            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6836            Starter::Review(_)
6837        ));
6838        assert!(matches!(
6839            review_retry_starter(&task, Some(&run), Some(branch), true, None),
6840            Starter::Review(_)
6841        ));
6842    }
6843
6844    #[test]
6845    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6846        let dir = tempfile::tempdir().unwrap();
6847        let queue = Queue::at(dir.path().join("queue"));
6848        let mut task = task();
6849        task.status = TaskStatus::Running;
6850        task.attempts = 1;
6851        queue.put(&mut task).unwrap();
6852        let live = std::collections::BTreeSet::from([task.id.clone()]);
6853        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6854        drop(queue.claim(&task.id).unwrap());
6855        let saved = queue.get(&task.id).unwrap();
6856        assert_eq!(saved.status, TaskStatus::Running);
6857        assert_eq!(saved.attempts, 1);
6858        assert!(saved.last_error.is_none());
6859    }
6860
6861    #[test]
6862    fn standalone_workers_do_not_consume_scheduler_lanes() {
6863        let request = |task: &str, lane, standalone| TaskWorker {
6864            opts: Opts::default(),
6865            queue: PathBuf::from("/queue"),
6866            task: task.to_owned(),
6867            lane,
6868            standalone,
6869        };
6870        let mut jobs = vec![
6871            request("ordinary", PermitKind::Ordinary, false),
6872            request("standalone-urgent", PermitKind::Urgent, true),
6873            request("standalone-ordinary", PermitKind::Ordinary, true),
6874            request("decision", PermitKind::None, false),
6875        ];
6876        assert_eq!(available_slots(&jobs, 2), (1, 1));
6877        jobs.push(request("urgent", PermitKind::Urgent, false));
6878        assert_eq!(available_slots(&jobs, 2), (1, 0));
6879        assert_eq!(available_slots(&jobs, 0), (0, 0));
6880    }
6881
6882    #[test]
6883    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6884        let now = Timestamp::now();
6885        let mut reading = Reading {
6886            pid: Some(std::process::id()),
6887            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6888            ..Reading::default()
6889        };
6890        assert!(!reading.running(now));
6891        assert!(legacy_scheduler_running(&reading, now, 0));
6892        reading.worker_protocol = Some(1);
6893        assert!(!legacy_scheduler_running(&reading, now, 0));
6894    }
6895
6896    #[test]
6897    fn selected_public_head_overrides_historical_resume_and_pin() {
6898        let mut t = task();
6899        let mut old = run_state(RunStatus::Blocked);
6900        let selection = crate::pr_recovery::Selection {
6901            url: "url".into(),
6902            branch: format!("magi/task-{}", t.id),
6903            head: "a".repeat(40),
6904            source_head: None,
6905            source_run: None,
6906            source_proof: None,
6907            disposition: Some(crate::pr_recovery::Disposition::Review),
6908            instruction: t.instruction.clone(),
6909            approved_at: Timestamp::now(),
6910        };
6911        t.resume_override = Some(crate::queue::OperatorResume {
6912            pinned_run: Some(old.id.clone()),
6913            question_id: "choice".into(),
6914            at: Timestamp::now(),
6915            conductor_rehold: None,
6916            forced: false,
6917        });
6918        assert_eq!(
6919            selected_starter(&selection, Some(&old), Some(&old.id)),
6920            Starter::Review(selection.branch.clone())
6921        );
6922        old.pr_recovery = Some(selection.clone());
6923        assert_eq!(
6924            selected_starter(&selection, Some(&old), Some(&old.id)),
6925            Starter::Review(selection.branch.clone())
6926        );
6927        old.reviewed_commits = Some(vec!["implementation".into()]);
6928        assert_eq!(
6929            selected_starter(&selection, Some(&old), Some(&old.id)),
6930            Starter::Resume(old.id.clone())
6931        );
6932        let mut changed = selection.clone();
6933        changed.head = "b".repeat(40);
6934        assert_eq!(
6935            selected_starter(&changed, Some(&old), Some(&old.id)),
6936            Starter::Review(changed.branch)
6937        );
6938    }
6939
6940    #[test]
6941    fn candidate_transplant_failure_is_one_actionable_hold() {
6942        let dir = tempfile::tempdir().unwrap();
6943        let q = Queue::at(dir.path().join("queue"));
6944        let mut t = task();
6945        let mut state = run_state(RunStatus::Blocked);
6946        state.event("prep", "cannot apply referenced commit: conflict");
6947        state.prep_failure = Some("conflict".into());
6948        t.start(state.id.clone());
6949        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6950        assert_eq!(t.attempts, 1);
6951        assert_eq!(t.status, TaskStatus::Held);
6952        assert!(t.operator_held());
6953        assert!(!t.status.runnable());
6954        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6955        let first = t.chat_notice_key().unwrap();
6956        t.chat_notices.push(first.clone());
6957        t.release_operator("test", None);
6958        state.id = "another-unprepared-run".into();
6959        t.start(state.id.clone());
6960        finish_attempt(
6961            3,
6962            &q,
6963            &mut t,
6964            &state,
6965            &[],
6966            Err(anyhow::anyhow!("still conflicts")),
6967        );
6968        assert_eq!(
6969            t.chat_notice_key().as_ref(),
6970            Some(&first),
6971            "no work happened"
6972        );
6973        t.release_operator("test", None);
6974        state.prep_failure = None;
6975        state.status = RunStatus::Failed;
6976        state.begin_pass();
6977        t.start(state.id.clone());
6978        finish_attempt(
6979            1,
6980            &q,
6981            &mut t,
6982            &state,
6983            &[],
6984            Err(anyhow::anyhow!("new gate failure")),
6985        );
6986        let failure = t.chat_notice_key().unwrap();
6987        assert_ne!(failure, first, "approved recovery reached a real failure");
6988        t.release_operator("test", None);
6989        state.begin_pass();
6990        t.start(state.id.clone());
6991        finish_attempt(
6992            1,
6993            &q,
6994            &mut t,
6995            &state,
6996            &[],
6997            Err(anyhow::anyhow!("new failure on resume")),
6998        );
6999        assert_ne!(
7000            t.chat_notice_key().as_ref(),
7001            Some(&failure),
7002            "a new settled pass"
7003        );
7004    }
7005
7006    #[test]
7007    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7008        for source in ["cli", "web"] {
7009            let mut t = task();
7010            let mut run = run_state(RunStatus::Blocked);
7011            run.instruction = "Run A original criteria".into();
7012            run.task_instruction = Some(run.instruction.clone());
7013            t.start(run.id.clone());
7014            t.release_operator("choice", Some("resume-question"));
7015            t.resume_override = Some(crate::queue::OperatorResume {
7016                question_id: "resume-question".into(),
7017                at: Timestamp::now(),
7018                conductor_rehold: None,
7019                forced: true,
7020                pinned_run: Some(run.id.clone()),
7021            });
7022            t.hold_machine(Some("not enough free space to start a run".into()));
7023            let mut unchanged = t.clone();
7024            unchanged
7025                .edit("title changed".into(), unchanged.instruction.clone())
7026                .unwrap();
7027            unchanged.release_operator(source, None);
7028            assert_eq!(
7029                unchanged
7030                    .resume_override
7031                    .as_ref()
7032                    .unwrap()
7033                    .pinned_run
7034                    .as_deref(),
7035                Some(run.id.as_str())
7036            );
7037            assert!(!compatible_run_instruction(&run, &unchanged));
7038            assert!(may_resume_run(&run, &unchanged));
7039
7040            t.edit(
7041                "approved recovery".into(),
7042                "Reuse measured PR head B; fix Clippy; review".into(),
7043            )
7044            .unwrap();
7045            assert!(t.resume_override.is_none());
7046            t.release_operator(source, None);
7047            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7048            assert!(reloaded.resume_override.is_none());
7049            assert!(!may_resume_run(&run, &reloaded));
7050            let unfinished =
7051                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7052                    .filter(|_| may_resume_run(&run, &reloaded));
7053            assert_eq!(
7054                choose_starter(None, false, unfinished.as_deref()),
7055                Starter::Start
7056            );
7057            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7058            assert_eq!(
7059                reloaded.resumption_history[0].question_id.as_deref(),
7060                Some("resume-question")
7061            );
7062
7063            // A revision already persisted with the old approval/pin is also
7064            // invalidated when the new operator release is recorded.
7065            unchanged.instruction = "Reuse measured PR head B".into();
7066            unchanged.hold_machine(Some("disk hold".into()));
7067            unchanged.release_operator(source, None);
7068            assert!(unchanged.resume_override.is_none());
7069            assert!(!may_resume_run(&run, &unchanged));
7070        }
7071    }
7072
7073    #[test]
7074    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7075        let mut t = task();
7076        let mut run = run_state(RunStatus::Blocked);
7077        t.review_of = Some("approved-head".into());
7078        t.instruction =
7079            "Review the branch `approved-head` (review-only: no implementation, no judging)."
7080                .into();
7081        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();
7082        run.reviewed_commits = Some(vec!["Commit log".into()]);
7083        t.start(run.id.clone());
7084        t.hold_machine(Some("interrupted review".into()));
7085        t.release_operator("cli", None);
7086        assert!(
7087            compatible_run_instruction(&run, &t),
7088            "legacy explicit review remains resumable"
7089        );
7090        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7091            .filter(|_| compatible_run_instruction(&run, &t));
7092        assert_eq!(
7093            choose_starter(None, false, unfinished.as_deref()),
7094            Starter::Resume(run.id.clone())
7095        );
7096        run.task_instruction = Some(t.instruction.clone());
7097        assert!(compatible_run_instruction(&run, &t));
7098        let reloaded: RunState =
7099            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7100        assert!(compatible_run_instruction(&reloaded, &t));
7101        t.edit(
7102            "new approved head".into(),
7103            "Reuse measured PR head B".into(),
7104        )
7105        .unwrap();
7106        assert!(!compatible_run_instruction(&run, &t));
7107
7108        // Legacy recovery reviews retain the task criteria ahead of the log.
7109        t.review_of = None;
7110        t.instruction = "Fix Clippy on approved head".into();
7111        run.task_instruction = None;
7112        run.instruction = format!(
7113            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7114            t.instruction
7115        );
7116        assert!(compatible_run_instruction(&run, &t));
7117        t.instruction.push('\n');
7118        assert!(
7119            compatible_run_instruction(&run, &t),
7120            "legacy generated review trimmed the original criteria"
7121        );
7122        t.hold_for_handover(Some("approved-head".into()), "refused".into());
7123        let mut unchanged = t.clone();
7124        assert_eq!(
7125            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
7126            Some("approved-head")
7127        );
7128        t.edit("new plan".into(), "Reuse measured PR head B".into())
7129            .unwrap();
7130        assert!(take_review_branch(&mut t, Some(&run)).is_none());
7131        assert!(!compatible_run_instruction(&run, &t));
7132        t.review_branch = Some("approved-head".into());
7133        t.review_instruction = None;
7134        assert!(
7135            take_review_branch(&mut t, Some(&run)).is_none(),
7136            "legacy retained candidate cannot replace a revised approved head"
7137        );
7138    }
7139
7140    #[test]
7141    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7142        let home = crate::run::test_home();
7143        crate::run::pin_test_home();
7144        let dir = tempfile::tempdir().unwrap();
7145        let queue = Queue::at(dir.path().join("queue"));
7146        for resume in [true, false] {
7147            let state = run_state(RunStatus::Blocked);
7148            let mut t = task();
7149            t.start(state.id.clone());
7150            let action = if resume {
7151                ask::ChoiceAction::Resume {
7152                    run: state.id.clone(),
7153                }
7154            } else {
7155                ask::ChoiceAction::Requeue
7156            };
7157            let mut q = action_question(&state.id, action);
7158            q.status = ask::QuestionStatus::Open;
7159            q.answer = None;
7160            q.answered_at = None;
7161            t.fail("run stopped with a question", 3);
7162            hold_if_runnable(&queue, &mut t);
7163            assert!(t.operator_decided_at.is_none());
7164            assert!(t.operator_held());
7165            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7166            let expected = if resume {
7167                ActionDecision::Resume(state.id.clone())
7168            } else {
7169                ActionDecision::Requeue
7170            };
7171            assert_eq!(
7172                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7173                expected
7174            );
7175            t.hold_manual(Some("later explicit hold".into()));
7176            assert_eq!(
7177                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7178                ActionDecision::Stale
7179            );
7180        }
7181    }
7182
7183    #[test]
7184    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7185        let mut t = task();
7186        t.answers.push(crate::queue::AnsweredQuestion {
7187            question: "Inspect the remote?".into(),
7188            answer: "Inspect then wait".into(),
7189        });
7190        let old = instruction_for(&t);
7191        assert!(compatible_instruction(&old, &t));
7192        t.instruction = "Reuse approved PR head and review".into();
7193        t.release_operator("cli", None);
7194        assert!(!compatible_instruction(&old, &t));
7195        let approved = instruction_for(&t);
7196        assert!(approved.contains("waiting premises are superseded"));
7197        assert!(compatible_instruction(&approved, &t));
7198        assert_eq!(resumed_instruction(&approved, &t), approved);
7199        t.release_operator("web", None);
7200        assert!(compatible_instruction(&approved, &t));
7201        assert_eq!(t.resumption_history.len(), 1);
7202        t.start("run".into());
7203        assert!(instruction_for(&t).contains("Explicit operator resumption"));
7204    }
7205
7206    /// A run that stopped on an infrastructure wait asked no agent anything:
7207    /// the task is held by the machine under a `[resource]` reason (resumable,
7208    /// re-checked by triage), and the attempt it started is given back.
7209    #[test]
7210    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7211        let mut state = RunState::new(
7212            PathBuf::from("/repo"),
7213            "main".into(),
7214            "base".into(),
7215            "task".into(),
7216            Config::default(),
7217        );
7218        state.status = RunStatus::Landing;
7219        state.parked = true;
7220        state.pr_pushed_head = Some("head".into());
7221        state.land_unrelated = Some(
7222            serde_json::from_value(serde_json::json!({
7223                "head": "head", "question": "ci-question",
7224                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7225            }))
7226            .unwrap(),
7227        );
7228        let mut t = task();
7229        t.start(state.id.clone());
7230        let verdict = Verdict {
7231            status: RunStatus::Landing,
7232            left_pr: true,
7233            quota_hit: false,
7234            parked: true,
7235            no_viable_candidates: false,
7236        };
7237        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7238        assert_eq!(t.attempts, 0);
7239        assert_eq!(t.status, TaskStatus::Held);
7240        assert!(!t.operator_held());
7241        assert!(
7242            t.hold_reason
7243                .as_deref()
7244                .unwrap()
7245                .starts_with("[ci-unrelated]")
7246        );
7247        // A second settlement must not refund an earlier task attempt.
7248        t.attempts = 1;
7249        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7250        assert_eq!(t.attempts, 1);
7251        assert_eq!(t.passes.len(), 1);
7252        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7253        state.pr_pushed_head = Some("new-head".into());
7254        state.parked = false;
7255        state.status = RunStatus::Blocked;
7256        let stale = Verdict {
7257            status: RunStatus::Blocked,
7258            parked: false,
7259            ..verdict
7260        };
7261        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7262        assert_eq!(t.attempts, 1);
7263        // A new execution pass can refund its own newly charged attempt.
7264        state.begin_pass();
7265        state.begin_pass();
7266        state.status = RunStatus::Landing;
7267        state.parked = true;
7268        state.pr_pushed_head = Some("head".into());
7269        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7270        assert_eq!(t.attempts, 0);
7271        assert_eq!(t.passes.len(), 2);
7272    }
7273
7274    #[test]
7275    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7276        let mut state = run_state(RunStatus::Failed);
7277        state
7278            .quota
7279            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7280        state.begin_pass();
7281        let mut t = task();
7282        t.start(state.id.clone());
7283        reclaim(&mut t, Some(state), 2, "en");
7284        assert_eq!(t.attempts, 1);
7285    }
7286
7287    #[test]
7288    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7289        let mut state = run_state(RunStatus::Blocked);
7290        let losses: Vec<_> = ["alpha", "beta"]
7291            .into_iter()
7292            .enumerate()
7293            .map(|(i, agent)| {
7294                QuotaLoss::from_report(
7295                    format!("advisor-{i}"),
7296                    "advise",
7297                    Some(&crate::agent::Quota {
7298                        cause: crate::agent::QuotaCause::Authentication,
7299                        agent: agent.to_owned(),
7300                        reset: None,
7301                    }),
7302                )
7303            })
7304            .collect();
7305        crate::graph::block_machine_outage(&mut state, "advise", &losses);
7306        state.quota = losses;
7307        let mut t = task();
7308        t.start(state.id.clone());
7309        let verdict = Verdict {
7310            status: state.status,
7311            left_pr: false,
7312            quota_hit: true,
7313            parked: false,
7314            no_viable_candidates: true,
7315        };
7316        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7317        assert_eq!(t.attempts, 0);
7318        assert_eq!(t.status, TaskStatus::Held);
7319        assert!(!t.operator_held());
7320        let reason = t.hold_reason.as_deref().unwrap();
7321        assert!(reason.starts_with("[authentication]"));
7322        assert!(
7323            reason.contains("alpha")
7324                && reason.contains("beta")
7325                && reason.contains("re-authenticate")
7326        );
7327        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7328        // Orphan recovery uses the same settlement and cannot spend an attempt.
7329        let mut orphan = task();
7330        orphan.start(state.id.clone());
7331        reclaim(&mut orphan, Some(state), 2, "en");
7332        assert_eq!(orphan.attempts, 0);
7333        assert_eq!(orphan.status, TaskStatus::Held);
7334    }
7335
7336    #[test]
7337    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7338        let mut state = RunState::new(
7339            PathBuf::from("/repo"),
7340            "main".to_owned(),
7341            "abc1234".to_owned(),
7342            "task".to_owned(),
7343            Config::default(),
7344        );
7345        state.status = RunStatus::Blocked;
7346        state.resource_block = Some(crate::run::ResourceBlock {
7347            cause: crate::run::ResourceBlockCause::Other,
7348            node: "graft".to_owned(),
7349            kind: "shared build cache".to_owned(),
7350            detail: "timed out".to_owned(),
7351            at: jiff::Timestamp::now(),
7352        });
7353        let mut t = task();
7354        t.start("20260902-000000-aaaa".to_owned());
7355        assert_eq!(t.attempts, 1);
7356        let verdict = Verdict {
7357            status: RunStatus::Blocked,
7358            left_pr: false,
7359            quota_hit: false,
7360            parked: false,
7361            no_viable_candidates: false,
7362        };
7363        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7364        assert_eq!(t.status, TaskStatus::Held);
7365        assert_eq!(t.attempts, 0, "the attempt is refunded");
7366        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7367        assert!(
7368            !t.operator_held(),
7369            "a machine hold, released without a human"
7370        );
7371
7372        let mut selected = task();
7373        selected.start("20260902-000000-cccc".into());
7374        selected.replacement = Some(crate::merge_decision::Replacement {
7375            question: "fixture".into(),
7376            run: "earlier".into(),
7377            pr: "https://example.invalid/pr/1".into(),
7378            agent: "selected".into(),
7379            context: "fixture".into(),
7380        });
7381        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7382        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7383        assert_eq!(selected.attempts, 0);
7384        assert!(
7385            !selected.operator_held(),
7386            "a selected agent also retains a machine resource hold"
7387        );
7388        assert!(
7389            selected
7390                .hold_reason
7391                .as_deref()
7392                .unwrap()
7393                .starts_with("[resource] ")
7394        );
7395
7396        // A park request outranks it: still the operator's doing.
7397        let mut p = task();
7398        p.start("20260902-000000-bbbb".to_owned());
7399        settle_and_diagnose(
7400            &mut p,
7401            Verdict {
7402                parked: true,
7403                ..verdict
7404            },
7405            "parked",
7406            2,
7407            &state,
7408        );
7409        assert_eq!(p.status, TaskStatus::Parked);
7410        assert_eq!(
7411            p.attempts, 0,
7412            "parking refunds once rather than also settling the resource hold"
7413        );
7414    }
7415
7416    #[test]
7417    fn record_failure_notice_links_the_task() {
7418        let dir = tempfile::tempdir().unwrap();
7419        // A regular file where the queue directory should be makes every
7420        // `put` fail, on every platform and whoever runs the test.
7421        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7422        let queue = Queue::at(dir.path().join("queue"));
7423        let mut t = interrupt_task("rec-fail-1");
7424        record(&queue, &mut t);
7425
7426        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7427        assert_eq!(found.len(), 1);
7428        assert_eq!(found[0].key, "loop:record");
7429        assert_eq!(
7430            found[0].link,
7431            Some(Link::Task {
7432                id: "rec-fail-1".to_owned()
7433            })
7434        );
7435    }
7436
7437    /// A runnable task marked to interrupt, with an id fixed for assertions
7438    /// rather than the random one [`Task::new`] mints.
7439    fn interrupt_task(id: &str) -> Task {
7440        let mut t = task();
7441        t.id = id.to_owned();
7442        t.interrupt = true;
7443        t
7444    }
7445
7446    /// An ordinary runnable task with an id fixed for assertions.
7447    fn task_with_id(id: &str) -> Task {
7448        let mut t = task();
7449        t.id = id.to_owned();
7450        t
7451    }
7452
7453    /// A runnable task marked `--urgent`, with an id fixed for assertions.
7454    fn urgent_task(id: &str) -> Task {
7455        let mut t = task();
7456        t.id = id.to_owned();
7457        t.urgent = true;
7458        t
7459    }
7460
7461    #[test]
7462    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7463        let dir = tempfile::tempdir().unwrap();
7464        let queue = Queue::at(dir.path().join("queue"));
7465        let mut parked = task_with_id("parked");
7466        parked.start("run".into());
7467        parked.park("upgrade");
7468        parked.record_pass_at(
7469            "run",
7470            0,
7471            Some(Timestamp::now()),
7472            1,
7473            Some(crate::run::ParkCause::Upgrade {
7474                from: "old".into(),
7475                to: None,
7476            }),
7477        );
7478        let mut fresh = task_with_id("fresh");
7479        fresh.priority = 100;
7480        let mut urgent_task = urgent_task("urgent");
7481        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7482            queue.put(t).unwrap();
7483        }
7484        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7485        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7486        let candidates = runnable(&queue);
7487        assert_eq!(candidates[0].id, parked.id);
7488        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7489        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
7490        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
7491        drop(first);
7492        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7493        let next = runnable(&queue)
7494            .into_iter()
7495            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
7496            .unwrap();
7497        assert_eq!(next.task.id, fresh.id);
7498        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7499        drop(claimed_elsewhere);
7500        drop(next);
7501        assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7502    }
7503
7504    #[test]
7505    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7506        let dir = tempfile::tempdir().unwrap();
7507        let queue = Queue::at(dir.path().join("queue"));
7508        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7509        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7510        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7511        let mut first = task();
7512        queue.put(&mut first).unwrap();
7513        let stale_plain = queue.get(&first.id).unwrap();
7514        first.set_urgent(true).unwrap();
7515        queue.put(&mut first).unwrap();
7516        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7517        let mut second = urgent_task("second");
7518        queue.put(&mut second).unwrap();
7519        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7520        drop(queue.claim(&second.id).unwrap());
7521        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7522        drop(dispatched);
7523        let stale_urgent = queue.get(&first.id).unwrap();
7524        first.set_urgent(false).unwrap();
7525        queue.put(&mut first).unwrap();
7526        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7527        assert_eq!(urgent.available_permits(), 1);
7528        drop(queue.claim(&first.id).unwrap());
7529        drop(occupied);
7530    }
7531
7532    #[test]
7533    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7534        let dir = tempfile::tempdir().unwrap();
7535        let queue = Queue::at(dir.path().join("queue"));
7536        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7537        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7538        let mut t = task();
7539        queue.put(&mut t).unwrap();
7540        for enabled in [true, false] {
7541            let stale = queue.get(&t.id).unwrap();
7542            t.set_urgent(enabled).unwrap();
7543            queue.put(&mut t).unwrap();
7544            assert_ne!(stale.urgent, enabled);
7545            let DispatchClaim {
7546                task: fresh,
7547                claim,
7548                permit,
7549            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7550            assert_eq!(fresh.urgent, enabled);
7551            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7552            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7553            assert!(queue.claim(&t.id).is_err());
7554            assert_eq!(fresh.attempts, stale.attempts);
7555            drop((claim, permit));
7556            assert_eq!(ordinary.available_permits(), 1);
7557            assert_eq!(urgent.available_permits(), 1);
7558        }
7559        t.set_urgent(true).unwrap();
7560        queue.put(&mut t).unwrap();
7561        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7562        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7563        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7564        drop(queue.claim(&t.id).unwrap());
7565        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7566        drop(occupied);
7567        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7568        drop(queue.claim(&t.id).unwrap());
7569        let held = queue.claim(&t.id).unwrap();
7570        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7571        drop(held);
7572        t.status = TaskStatus::Held;
7573        queue.put(&mut t).unwrap();
7574        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7575        drop(queue.claim(&t.id).unwrap());
7576        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7577        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7578        drop(queue.claim(&t.id).unwrap());
7579        assert_eq!(urgent.available_permits(), 1);
7580    }
7581
7582    /// The land-resume exemption wins outright, whether or not the candidate
7583    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7584    /// queue behind anything" guarantee cannot be weaker just because the
7585    /// same task was also filed with `--urgent`.
7586    #[test]
7587    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7588        assert_eq!(permit_kind(true, false), PermitKind::None);
7589        assert_eq!(permit_kind(true, true), PermitKind::None);
7590    }
7591
7592    /// The one property this whole feature exists for: `--urgent` draws from
7593    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7594    /// ordinary candidate draws from the ordinary pool exactly as before,
7595    /// untouched by the urgent slot's existence.
7596    #[test]
7597    fn permit_kind_separates_urgent_from_ordinary() {
7598        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7599        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7600    }
7601
7602    /// The exact wiring `attempt` runs before minting anything: a config's
7603    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7604    /// Free space is injected rather than asked of the real disk - the point
7605    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7606    /// is deterministic on every machine this test runs on, never dependent
7607    /// on how full the CI runner's own disk happens to be.
7608    #[test]
7609    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7610        let cfg = Config::default();
7611        let repo = Path::new("/any/repo/path");
7612
7613        let reason =
7614            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7615        assert!(reason.contains("1024"), "{reason}");
7616        assert!(
7617            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7618            "{reason}"
7619        );
7620
7621        assert_eq!(
7622            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7623            None,
7624            "exactly at the floor is open"
7625        );
7626        assert_eq!(
7627            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7628            None,
7629            "comfortably above the floor is open"
7630        );
7631    }
7632
7633    #[test]
7634    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
7635        let dir = tempfile::tempdir().unwrap();
7636        let repo = dir.path().join("repo");
7637        let cache = dir.path().join("cache");
7638        let worktrees = dir.path().join("worktrees");
7639        for path in [&repo, &cache, &worktrees] {
7640            std::fs::create_dir(path).unwrap();
7641        }
7642        let mut cfg = Config::default();
7643        cfg.graph.worktree_root = Some(worktrees.clone());
7644        cfg.verify.gate = vec![format!(
7645            "CARGO_TARGET_DIR='{}' cargo build",
7646            cache.display()
7647        )];
7648        for blocked in [&cache, &worktrees] {
7649            for unmeasured in [false, true] {
7650                assert!(
7651                    disk_gate_with(&repo, &cfg, |path| {
7652                        if path == blocked {
7653                            if unmeasured {
7654                                Err(anyhow::anyhow!("measurement failed"))
7655                            } else {
7656                                Ok(0)
7657                            }
7658                        } else {
7659                            Ok(u64::MAX)
7660                        }
7661                    })
7662                    .is_some(),
7663                    "a blocked secondary output volume must close admission"
7664                );
7665            }
7666        }
7667        assert!(disk_gate_with(&repo, &cfg, |_| Ok(u64::MAX)).is_none());
7668    }
7669
7670    #[test]
7671    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7672        let mut cfg = Config::default();
7673        cfg.disk.min_free_bytes = 0;
7674        let repo = Path::new("/any/repo/path");
7675        assert_eq!(
7676            disk_gate_with(repo, &cfg, |_| Ok(0)),
7677            None,
7678            "a zero floor never measures at all"
7679        );
7680    }
7681
7682    #[test]
7683    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7684        let cfg = Config::default();
7685        let repo = Path::new("/any/repo/path");
7686        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7687            .expect("a measurement failure must close the gate, not open it");
7688        assert!(reason.contains("could not measure"), "{reason}");
7689    }
7690
7691    #[test]
7692    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7693        let ordinary = task();
7694        let next = advance_interrupt(
7695            Interrupt::Idle,
7696            std::slice::from_ref(&ordinary.id),
7697            std::slice::from_ref(&ordinary),
7698        );
7699        assert_eq!(next, Interrupt::Idle);
7700    }
7701
7702    #[test]
7703    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7704        // Nothing to interrupt - this is just an ordinary candidate, and the
7705        // loop's normal dispatch will pick it up like any other.
7706        let marked = interrupt_task("marked");
7707        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7708        assert_eq!(next, Interrupt::Idle);
7709    }
7710
7711    #[test]
7712    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7713        let marked = interrupt_task("marked");
7714        let next = advance_interrupt(
7715            Interrupt::Idle,
7716            &["running".to_owned()],
7717            std::slice::from_ref(&marked),
7718        );
7719        assert_eq!(
7720            next,
7721            Interrupt::Parking {
7722                parked: vec!["running".to_owned()],
7723                interrupt_task: "marked".to_owned(),
7724            }
7725        );
7726    }
7727
7728    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
7729    /// one run can be in flight when a task becomes runnable and marked.
7730    /// Parking all of them would mean `Resuming` later has more than one id
7731    /// to release back to ordinary dispatch, which cannot be made safe
7732    /// against that same setting's own extra concurrency slots letting two
7733    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
7734    /// The simplification the task's own constraints ask for: do not begin
7735    /// a sequence at all until the herd settles back to exactly one.
7736    #[test]
7737    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7738        let marked = interrupt_task("marked");
7739
7740        let two = advance_interrupt(
7741            Interrupt::Idle,
7742            &["a".to_owned(), "b".to_owned()],
7743            std::slice::from_ref(&marked),
7744        );
7745        assert_eq!(two, Interrupt::Idle);
7746
7747        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7748        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7749    }
7750
7751    #[test]
7752    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7753        let state = Interrupt::Parking {
7754            parked: vec!["running".to_owned()],
7755            interrupt_task: "marked".to_owned(),
7756        };
7757        // Still in flight: no change.
7758        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7759        assert_eq!(still_going, state);
7760
7761        // Left flight, but the interrupt task has not been dispatched yet on
7762        // this tick - stays `Parking` so `interrupt_gate` can let it through,
7763        // as long as it is still runnable.
7764        let stopped_but_not_yet_dispatched =
7765            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7766        assert_eq!(stopped_but_not_yet_dispatched, state);
7767
7768        // Left flight, and the interrupt task is now in flight itself.
7769        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7770        assert_eq!(
7771            dispatched,
7772            Interrupt::Running {
7773                parked: vec!["running".to_owned()],
7774                interrupt_task: "marked".to_owned(),
7775            }
7776        );
7777    }
7778
7779    #[test]
7780    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7781        let state = Interrupt::Running {
7782            parked: vec!["running".to_owned()],
7783            interrupt_task: "marked".to_owned(),
7784        };
7785        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7786        assert_eq!(still_running, state);
7787
7788        // Whatever it ended as - merged, failed, held - is not this
7789        // function's concern: leaving flight is the only trigger, driven
7790        // straight off the same in-flight list `poll` already reaps. It does
7791        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
7792        // why that would let an unrelated task start ahead of, or alongside,
7793        // the guaranteed resume.
7794        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7795        assert_eq!(
7796            ended,
7797            Interrupt::Resuming {
7798                parked: vec!["running".to_owned()]
7799            }
7800        );
7801    }
7802
7803    #[test]
7804    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7805        let state = Interrupt::Resuming {
7806            parked: vec!["running".to_owned()],
7807        };
7808        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7809        assert_eq!(still_waiting, state);
7810
7811        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7812        assert_eq!(dispatched, Interrupt::Idle);
7813    }
7814
7815    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
7816    /// or otherwise moved on by an operator with no claim standing in the
7817    /// way - must not wedge the sequence (and so the whole loop's dispatch,
7818    /// via `interrupt_gate`) waiting forever for a dispatch that can never
7819    /// come. The parked run still gets its resume.
7820    #[test]
7821    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7822    {
7823        let state = Interrupt::Parking {
7824            parked: vec!["running".to_owned()],
7825            interrupt_task: "marked".to_owned(),
7826        };
7827        // `marked` has been held/blocked/deleted since the sequence began:
7828        // it no longer appears in `runnable` at all.
7829        let next = advance_interrupt(state, &[], &[]);
7830        assert_eq!(
7831            next,
7832            Interrupt::Resuming {
7833                parked: vec!["running".to_owned()]
7834            },
7835            "abandoning the interrupt must not abandon the resume it owes"
7836        );
7837    }
7838
7839    /// The same abandonment, one step later: `Resuming` itself must not wait
7840    /// forever for a parked task that has since become unrunnable.
7841    #[test]
7842    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7843        let state = Interrupt::Resuming {
7844            parked: vec!["running".to_owned()],
7845        };
7846        let next = advance_interrupt(state, &[], &[]);
7847        assert_eq!(
7848            next,
7849            Interrupt::Idle,
7850            "nothing is left to wait for; the loop must not stay wedged"
7851        );
7852    }
7853
7854    #[test]
7855    fn disabled_by_config_the_sequence_can_never_leave_idle() {
7856        let marked = interrupt_task("marked");
7857        let next = advance_interrupt_tick(
7858            false,
7859            Interrupt::Idle,
7860            &["running".to_owned()],
7861            std::slice::from_ref(&marked),
7862        );
7863        assert_eq!(
7864            next,
7865            Interrupt::Idle,
7866            "an unmarked, unconfigured daemon must behave exactly as before"
7867        );
7868    }
7869
7870    #[test]
7871    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7872        let state = Interrupt::Parking {
7873            parked: vec!["running".to_owned()],
7874            interrupt_task: "marked".to_owned(),
7875        };
7876        let candidates = vec![interrupt_task("marked"), task()];
7877        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7878        assert!(
7879            allowed.is_empty(),
7880            "nothing may dispatch - not even the interrupt task itself - \
7881             until the parked run has actually stopped"
7882        );
7883    }
7884
7885    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
7886    /// grow a special case for it: an urgent candidate that is not the
7887    /// interrupt task withholds exactly like an ordinary one for as long as
7888    /// the parked run it is racing has not actually left flight. A version
7889    /// of this feature once bypassed the gate for urgent candidates, on the
7890    /// theory that a genuinely separate concurrency lane could not collide
7891    /// with 75dd's own; it could, and did - the bypassed task dispatched
7892    /// alongside a run 75dd's own state machine had only *asked* to park,
7893    /// not yet confirmed gone, which is exactly the second run
7894    /// `Interrupt::Parking`'s own doc says must never happen. There is no
7895    /// tick during Parking/Running/Resuming where letting an extra
7896    /// candidate through is safe, urgent or not - the parked run may still
7897    /// be genuinely mid-call.
7898    #[test]
7899    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7900        for state in [
7901            Interrupt::Parking {
7902                parked: vec!["running".to_owned()],
7903                interrupt_task: "marked".to_owned(),
7904            },
7905            Interrupt::Running {
7906                parked: vec!["running".to_owned()],
7907                interrupt_task: "marked".to_owned(),
7908            },
7909            Interrupt::Resuming {
7910                parked: vec!["running".to_owned()],
7911            },
7912        ] {
7913            let candidates = vec![
7914                interrupt_task("marked"),
7915                urgent_task("hot"),
7916                task_with_id("ordinary"),
7917            ];
7918            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7919            assert!(
7920                !allowed.iter().any(|t| t.id == "hot"),
7921                "an urgent candidate must wait out the same gate as anything \
7922                 else while the run it would run alongside has not actually \
7923                 left flight, for state {state:?}: {allowed:?}"
7924            );
7925        }
7926    }
7927
7928    /// The one case where marking a task `--urgent` and `interrupt` at once
7929    /// is not redundant: once the interrupt sequence's own guaranteed
7930    /// resume/dispatch actually admits the task, it is unaffected by also
7931    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
7932    /// never on the urgent flag.
7933    #[test]
7934    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7935        let state = Interrupt::Resuming {
7936            parked: vec!["hot".to_owned()],
7937        };
7938        let candidates = vec![urgent_task("hot"), task()];
7939        let allowed = interrupt_gate(&state, &[], candidates);
7940        assert_eq!(
7941            allowed.iter().filter(|t| t.id == "hot").count(),
7942            1,
7943            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7944        );
7945    }
7946
7947    #[test]
7948    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7949        let state = Interrupt::Parking {
7950            parked: vec!["running".to_owned()],
7951            interrupt_task: "marked".to_owned(),
7952        };
7953        let other = task();
7954        let candidates = vec![interrupt_task("marked"), other.clone()];
7955        let allowed = interrupt_gate(&state, &[], candidates);
7956        assert_eq!(allowed.len(), 1);
7957        assert_eq!(allowed[0].id, "marked");
7958    }
7959
7960    #[test]
7961    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7962        let state = Interrupt::Running {
7963            parked: vec!["running".to_owned()],
7964            interrupt_task: "marked".to_owned(),
7965        };
7966        let candidates = vec![task(), task()];
7967        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7968        assert!(allowed.is_empty());
7969    }
7970
7971    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
7972    /// sequence began (only reachable above the default
7973    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
7974    /// never both in the same tick, which is what "exactly one resume, no
7975    /// simultaneous run" actually requires structurally rather than by
7976    /// coincidence of how many ordinary slots happen to be free.
7977    #[test]
7978    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7979        let state = Interrupt::Resuming {
7980            parked: vec!["a".to_owned(), "c".to_owned()],
7981        };
7982        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7983        let allowed = interrupt_gate(&state, &[], candidates);
7984        assert_eq!(
7985            allowed.len(),
7986            1,
7987            "at most one candidate may be offered while resuming: {allowed:?}"
7988        );
7989        assert_eq!(allowed[0].id, "a");
7990    }
7991
7992    #[test]
7993    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7994        let state = Interrupt::Resuming {
7995            parked: vec!["a".to_owned()],
7996        };
7997        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7998        assert!(allowed.is_empty());
7999    }
8000
8001    /// The invariant the completion criteria ask for by name: across a whole
8002    /// simulated sequence, there is never a tick where the gate would let
8003    /// through both the parked run's resume and the interrupt task, and
8004    /// exactly one candidate resumes the instant the interrupt task's run
8005    /// ends - never zero, never more than one.
8006    #[test]
8007    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8008        let running = task(); // id: whatever `Task::new` minted
8009        let marked = interrupt_task("marked");
8010
8011        let mut state = Interrupt::Idle;
8012        // Tick 1: `running` is in flight, `marked` becomes runnable.
8013        let in_flight = vec![running.id.clone()];
8014        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8015        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8016        assert!(gated.is_empty(), "still waiting on `running` to park");
8017
8018        // Tick 2: `running` parked and left flight; nothing dispatched yet.
8019        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8020        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8021        assert_eq!(
8022            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8023            vec!["marked"],
8024            "only the interrupt task may be offered to the dispatcher now"
8025        );
8026
8027        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
8028        state = advance_interrupt_tick(
8029            true,
8030            state,
8031            &["marked".to_owned()],
8032            std::slice::from_ref(&running),
8033        );
8034        let gated = interrupt_gate(
8035            &state,
8036            &["marked".to_owned()],
8037            vec![marked.clone(), running.clone()],
8038        );
8039        assert!(
8040            gated.is_empty(),
8041            "the parked run must not be offered back while the interrupt \
8042             task is still running"
8043        );
8044
8045        // Tick 4: `marked`'s run reached a terminal status and left flight.
8046        // A higher-priority ordinary task `other` is also runnable now - it
8047        // must not be let through instead of, or alongside, `running`.
8048        let other = task_with_id("other");
8049        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8050        assert_eq!(
8051            state,
8052            Interrupt::Resuming {
8053                parked: vec![running.id.clone()]
8054            }
8055        );
8056        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8057        assert_eq!(
8058            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8059            vec![running.id.as_str()],
8060            "exactly the parked run resumes - not the unrelated task, even \
8061             though it was offered first"
8062        );
8063
8064        // Tick 5: `running` is now in flight (dispatched from tick 4's
8065        // gate). Only now does the sequence end and ordinary dispatch fully
8066        // resume.
8067        state = advance_interrupt_tick(
8068            true,
8069            state,
8070            std::slice::from_ref(&running.id),
8071            std::slice::from_ref(&other),
8072        );
8073        assert_eq!(state, Interrupt::Idle);
8074        let gated = interrupt_gate(
8075            &state,
8076            std::slice::from_ref(&running.id),
8077            vec![other.clone()],
8078        );
8079        assert_eq!(
8080            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8081            vec![other.id.as_str()],
8082            "ordinary dispatch is unrestricted again"
8083        );
8084    }
8085
8086    #[test]
8087    fn every_run_status_settles_the_task_it_came_from() {
8088        // run status, resulting task status, attempts still standing after one
8089        let table = [
8090            (RunStatus::Merged, TaskStatus::Done, 1),
8091            (RunStatus::Ready, TaskStatus::Done, 1),
8092            (RunStatus::Stalled, TaskStatus::Failed, 0),
8093            (RunStatus::Blocked, TaskStatus::Failed, 1),
8094            (RunStatus::Failed, TaskStatus::Failed, 1),
8095            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8096            (RunStatus::Prep, TaskStatus::Failed, 1),
8097            (RunStatus::Implementing, TaskStatus::Failed, 1),
8098            (RunStatus::Judging, TaskStatus::Failed, 1),
8099            (RunStatus::Deliberating, TaskStatus::Failed, 1),
8100            (RunStatus::Voting, TaskStatus::Failed, 1),
8101            (RunStatus::Reviewing, TaskStatus::Failed, 1),
8102            (RunStatus::Gating, TaskStatus::Failed, 1),
8103        ];
8104        for (run, want, attempts) in table {
8105            let mut t = task();
8106            t.start("20260902-000000-aaaa".to_owned());
8107            settle(
8108                &mut t,
8109                Verdict {
8110                    status: run,
8111                    left_pr: false,
8112                    parked: false,
8113                    quota_hit: matches!(run, RunStatus::Stalled),
8114                    no_viable_candidates: false,
8115                },
8116                "why",
8117                2,
8118            );
8119            assert_eq!(t.status, want, "task status after {}", label(run));
8120            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8121        }
8122    }
8123
8124    #[test]
8125    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8126        let mut stalled = task();
8127        stalled.start("20260902-000000-aaaa".to_owned());
8128        settle(
8129            &mut stalled,
8130            Verdict {
8131                status: RunStatus::Stalled,
8132                left_pr: false,
8133                parked: false,
8134                quota_hit: true,
8135                no_viable_candidates: false,
8136            },
8137            "quota",
8138            1,
8139        );
8140        assert_eq!(stalled.attempts, 0);
8141        assert!(
8142            stalled.status.runnable(),
8143            "a machine problem must leave the task in line"
8144        );
8145
8146        let mut blocked = task();
8147        blocked.start("20260902-000000-aaaa".to_owned());
8148        settle(
8149            &mut blocked,
8150            Verdict {
8151                status: RunStatus::Blocked,
8152                left_pr: false,
8153                parked: false,
8154                quota_hit: false,
8155                no_viable_candidates: false,
8156            },
8157            "findings open",
8158            1,
8159        );
8160        assert_eq!(blocked.attempts, 1);
8161        assert_eq!(
8162            blocked.status,
8163            TaskStatus::Held,
8164            "the last attempt hands the task to a human"
8165        );
8166    }
8167
8168    #[test]
8169    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8170        // Attempts to spare: without the pull request this task would go
8171        // straight back in line and run the whole competition again.
8172        let mut delivered = task();
8173        delivered.start("20260903-080619-01c2".to_owned());
8174        settle(
8175            &mut delivered,
8176            Verdict {
8177                status: RunStatus::Blocked,
8178                left_pr: true,
8179                parked: false,
8180                quota_hit: false,
8181                no_viable_candidates: false,
8182            },
8183            "no check status",
8184            4,
8185        );
8186        assert_eq!(
8187            delivered.status,
8188            TaskStatus::Held,
8189            "a pull request waiting on CI or a person is not a retryable failure"
8190        );
8191        assert!(
8192            !delivered.status.runnable(),
8193            "the loop must not pick this task up again"
8194        );
8195        assert_eq!(
8196            delivered.last_error.as_deref(),
8197            Some("no check status"),
8198            "the operator needs to be told what the gate was waiting for"
8199        );
8200
8201        // The same status without a pull request is a plain failure, and with
8202        // attempts left it is retried.
8203        let mut empty_handed = task();
8204        empty_handed.start("20260903-080619-01c2".to_owned());
8205        settle(
8206            &mut empty_handed,
8207            Verdict {
8208                status: RunStatus::Blocked,
8209                left_pr: false,
8210                parked: false,
8211                quota_hit: false,
8212                no_viable_candidates: false,
8213            },
8214            "findings open",
8215            4,
8216        );
8217        assert_eq!(empty_handed.status, TaskStatus::Failed);
8218        assert!(empty_handed.status.runnable());
8219    }
8220
8221    #[test]
8222    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8223        // Every candidate agreed, with evidence, that nothing belonged in the
8224        // worktree. That is not a confirmed success to close automatically -
8225        // a human still has to check the claim - and it is not an ordinary
8226        // failure either, so this settles exactly like a pull request nobody
8227        // merged yet: `Held`, same as `Blocked` with a PR.
8228        let mut noop = task();
8229        noop.start("20260912-131304-391f".to_owned());
8230        settle(
8231            &mut noop,
8232            Verdict {
8233                status: RunStatus::VerifiedNoop,
8234                left_pr: false,
8235                parked: false,
8236                quota_hit: false,
8237                no_viable_candidates: true,
8238            },
8239            "candidate A: already fixed by b32cfc4, on main",
8240            4,
8241        );
8242        assert_eq!(
8243            noop.status,
8244            TaskStatus::Held,
8245            "an unverified claim is a request for a human, not a failure"
8246        );
8247        assert!(
8248            !noop.status.runnable(),
8249            "the loop must not requeue this on the same unverified claim"
8250        );
8251        // `Task::release` resets attempts to zero the moment a human looks at
8252        // the evidence and lets it run again, so it does not matter here
8253        // whether the one attempt already spent stays spent - what matters is
8254        // that nothing retries this task unattended in the meantime.
8255        assert_eq!(noop.attempts, 1);
8256    }
8257
8258    #[test]
8259    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8260        // Parking is the operator asking for the process back - to replace the
8261        // binary, most of all. The run's work is intact on disk, so this is
8262        // not a failed attempt, and charging for it would mean a few upgrades
8263        // could exhaust a budget meant for agents that misbehaved.
8264        let mut parked = task();
8265        parked.start("20260903-183634-2d98".to_owned());
8266        settle(
8267            &mut parked,
8268            Verdict {
8269                status: RunStatus::Implementing,
8270                left_pr: false,
8271                quota_hit: false,
8272                parked: true,
8273                no_viable_candidates: false,
8274            },
8275            "parked after `implementing`",
8276            2,
8277        );
8278        assert_eq!(parked.attempts, 0, "a park is refunded");
8279        assert!(
8280            parked.status.runnable(),
8281            "and the task stays in line so the next loop resumes its run"
8282        );
8283        assert_eq!(parked.status, TaskStatus::Parked);
8284        assert_eq!(
8285            parked.park_reason.as_deref(),
8286            Some("parked after `implementing`"),
8287            "the card says where it stopped"
8288        );
8289        assert_eq!(parked.last_error, None, "nothing failed");
8290
8291        // Without the park flag the same non-terminal status is what it always
8292        // was: `execute` returning mid-flight, which is a bug and spends an
8293        // attempt so a task cannot loop on it forever.
8294        let mut broken = task();
8295        broken.start("20260903-183634-2d98".to_owned());
8296        settle(
8297            &mut broken,
8298            Verdict {
8299                status: RunStatus::Implementing,
8300                left_pr: false,
8301                quota_hit: false,
8302                parked: false,
8303                no_viable_candidates: false,
8304            },
8305            "returned mid-flight",
8306            2,
8307        );
8308        assert_eq!(broken.attempts, 1);
8309    }
8310
8311    #[test]
8312    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
8313        // Run e633: quorum lost because two judges answered with the wrong
8314        // JSON shape, `quota: []`. Refunding that takes the bound off the
8315        // retry loop, and each retry pays for a fresh hour-long implement
8316        // wave before it can fail the same way.
8317        let mut flaky = task();
8318        flaky.start("20260903-123023-e633".to_owned());
8319        settle(
8320            &mut flaky,
8321            Verdict {
8322                status: RunStatus::Stalled,
8323                left_pr: false,
8324                parked: false,
8325                quota_hit: false,
8326                no_viable_candidates: false,
8327            },
8328            "verdict rests on 1 of 3 judges",
8329            2,
8330        );
8331        assert_eq!(
8332            flaky.attempts, 1,
8333            "flakiness spends an attempt, so `max_attempts` still bounds it"
8334        );
8335        assert!(flaky.status.runnable(), "and it is still worth retrying");
8336
8337        // The same status, lost to a rate limit, is the machine's fault.
8338        let mut limited = task();
8339        limited.start("20260903-123023-e633".to_owned());
8340        settle(
8341            &mut limited,
8342            Verdict {
8343                status: RunStatus::Stalled,
8344                left_pr: false,
8345                parked: false,
8346                quota_hit: true,
8347                no_viable_candidates: false,
8348            },
8349            "judge-2, judge-3 out of quota",
8350            2,
8351        );
8352        assert_eq!(limited.attempts, 0, "a quota window is refunded");
8353        assert!(limited.status.runnable());
8354
8355        // And the bound really binds: a task that keeps stalling on flakiness
8356        // reaches a human instead of running the roster forever.
8357        let mut worn = task();
8358        for _ in 0..2 {
8359            worn.release();
8360        }
8361        worn.start("20260903-123023-e633".to_owned());
8362        worn.attempts = 2;
8363        settle(
8364            &mut worn,
8365            Verdict {
8366                status: RunStatus::Stalled,
8367                left_pr: false,
8368                parked: false,
8369                quota_hit: false,
8370                no_viable_candidates: false,
8371            },
8372            "no quorum again",
8373            2,
8374        );
8375        assert_eq!(worn.status, TaskStatus::Held);
8376        assert!(!worn.status.runnable());
8377    }
8378
8379    #[test]
8380    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8381        // The implement wave loses every seat to the same rate limit and
8382        // `after_implement` bails with nothing viable, which surfaces as
8383        // `Failed` rather than `Stalled`. That is the same machine fact the
8384        // `Stalled`-quota row already refunds, and must be refunded the same
8385        // way, or a quota outage quietly holds every task it touches instead
8386        // of leaving them in line for the reset.
8387        let mut wiped_out = task();
8388        wiped_out.start("20260907-025000-a1b2".to_owned());
8389        settle(
8390            &mut wiped_out,
8391            Verdict {
8392                status: RunStatus::Failed,
8393                left_pr: false,
8394                parked: false,
8395                quota_hit: true,
8396                no_viable_candidates: true,
8397            },
8398            "no candidate produced a change; nothing to judge",
8399            2,
8400        );
8401        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8402        assert!(
8403            wiped_out.status.runnable(),
8404            "a machine problem must leave the task in line"
8405        );
8406
8407        // This is the exemption that must stay narrow: a candidate that did
8408        // produce a change, and then failed for some other reason, still
8409        // spends the attempt even though a seat elsewhere hit its quota.
8410        // Otherwise every ordinary failure that happens to share a run with
8411        // an unrelated rate limit would be refunded for free.
8412        let mut partial_progress = task();
8413        partial_progress.start("20260907-025500-c3d4".to_owned());
8414        settle(
8415            &mut partial_progress,
8416            Verdict {
8417                status: RunStatus::Failed,
8418                left_pr: false,
8419                parked: false,
8420                quota_hit: true,
8421                no_viable_candidates: false,
8422            },
8423            "gate failed on the winning candidate",
8424            2,
8425        );
8426        assert_eq!(
8427            partial_progress.attempts, 1,
8428            "a candidate that actually produced a change spends the attempt \
8429             even though some other seat hit its quota"
8430        );
8431        assert!(partial_progress.status.runnable());
8432    }
8433
8434    #[test]
8435    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8436        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
8437        // disk, and that construction must reach the same conclusion as the
8438        // one `attempt` builds from a live run, or a crash at exactly the
8439        // wrong moment gives a recovered task a different policy than one a
8440        // daemon finished settling itself.
8441        let mut t = task();
8442        t.start("20260907-025000-a1b2".to_owned());
8443        let mut state = run_state(RunStatus::Failed);
8444        state.quota.push(QuotaLoss {
8445            cause: crate::agent::QuotaCause::UsageLimit,
8446            agent: String::new(),
8447            seat: "cand-a".to_owned(),
8448            node: "implement".to_owned(),
8449            at: Timestamp::now(),
8450            reset: None,
8451        });
8452        assert!(
8453            state.viable().is_empty(),
8454            "no candidate was added, so nothing is viable"
8455        );
8456        reclaim(&mut t, Some(state), 2, "en");
8457        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8458        assert!(t.status.runnable());
8459    }
8460
8461    #[test]
8462    fn a_held_task_is_never_offered_to_the_loop() {
8463        let dir = tempfile::tempdir().unwrap();
8464        let queue = Queue::at(dir.path().to_path_buf());
8465        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8466            let mut t = task();
8467            t.id = format!("2026090{n}-000000-000{n}");
8468            t.priority = priority;
8469            queue.put(&mut t).unwrap();
8470        }
8471        let mut held = task();
8472        held.id = "20260909-000000-9999".to_owned();
8473        held.priority = 99;
8474        held.hold_machine(None);
8475        queue.put(&mut held).unwrap();
8476
8477        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8478        assert_eq!(order.len(), 3);
8479        assert!(!order.contains(&held.id));
8480        assert_eq!(
8481            order.first().cloned(),
8482            queue.next_runnable().map(|t| t.id),
8483            "the loop's first candidate is exactly what the queue offers"
8484        );
8485        assert_eq!(
8486            order,
8487            vec![
8488                "20260902-000000-0002".to_owned(),
8489                "20260903-000000-0003".to_owned(),
8490                "20260901-000000-0001".to_owned(),
8491            ],
8492            "priority first, then oldest, so nothing starves"
8493        );
8494    }
8495
8496    #[test]
8497    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8498        let dir = tempfile::tempdir().unwrap();
8499        let queue = Queue::at(dir.path().to_path_buf());
8500        let mut old = task();
8501        old.id = "20260101-000000-old0".to_owned();
8502        queue.put(&mut old).unwrap();
8503        let mut fresh = task();
8504        fresh.id = "20260101-000000-new0".to_owned();
8505        queue.put(&mut fresh).unwrap();
8506
8507        // No parseable pid at all, so age is the only signal there is to
8508        // check - unlike a real `Queue::claim`, which always names a real,
8509        // and therefore alive, pid this test cannot fake as dead.
8510        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8511        std::thread::sleep(Duration::from_millis(60));
8512        let live = queue.claim(&fresh.id).unwrap();
8513
8514        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8515        assert_eq!(swept, vec![old.id.clone()]);
8516        assert!(
8517            queue.claim(&old.id).is_ok(),
8518            "an unparseable lock older than the threshold is swept"
8519        );
8520        assert!(
8521            queue.claim(&fresh.id).is_err(),
8522            "a live pid protects its lock regardless of age"
8523        );
8524        drop(live);
8525    }
8526
8527    #[test]
8528    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8529        // A live worker's claim remains authoritative even beyond the sweep's
8530        // age limit. Sweeping it would permit a second competing attempt.
8531        let dir = tempfile::tempdir().unwrap();
8532        let queue = Queue::at(dir.path().to_path_buf());
8533        let mut t = task();
8534        t.id = "20260101-000000-live".to_owned();
8535        queue.put(&mut t).unwrap();
8536
8537        let claim = queue.claim(&t.id).unwrap();
8538        std::thread::sleep(Duration::from_millis(60));
8539
8540        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8541        assert!(
8542            swept.is_empty(),
8543            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8544        );
8545        assert!(
8546            queue.claim(&t.id).is_err(),
8547            "the lock still protects its task"
8548        );
8549        drop(claim);
8550    }
8551
8552    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8553    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8554    fn injected_dead_pid() -> u32 {
8555        std::process::id().checked_add(1).unwrap_or(1)
8556    }
8557
8558    #[test]
8559    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8560        let dir = tempfile::tempdir().unwrap();
8561        let queue = Queue::at(dir.path().to_path_buf());
8562        let mut t = task();
8563        t.id = "20260101-000000-dead".to_owned();
8564        queue.put(&mut t).unwrap();
8565        let dead_pid = injected_dead_pid();
8566
8567        // Written directly rather than through `Queue::claim`, which would
8568        // stamp this test process's own very much alive pid and defeat the
8569        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8570        // like moments after it died, not six hours later.
8571        std::fs::write(
8572            dir.path().join(format!("{}.lock", t.id)),
8573            dead_pid.to_string(),
8574        )
8575        .unwrap();
8576
8577        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8578            pid != dead_pid
8579        });
8580        assert_eq!(
8581            swept,
8582            vec![t.id.clone()],
8583            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8584        );
8585        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8586    }
8587
8588    #[test]
8589    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8590        let dir = tempfile::tempdir().unwrap();
8591        let queue = Queue::at(dir.path().to_path_buf());
8592        let mut t = task();
8593        t.id = "20260101-000000-late".to_owned();
8594        queue.put(&mut t).unwrap();
8595        let dead_pid = injected_dead_pid();
8596
8597        // Tick one, standing in for the sweep `poll` already runs at
8598        // startup: nothing to find yet.
8599        assert!(
8600            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8601            "nothing has claimed the task yet"
8602        );
8603
8604        // A second daemon claims the task and dies before it ever writes
8605        // `running`, well after this loop's own startup sweep already ran.
8606        std::fs::write(
8607            dir.path().join(format!("{}.lock", t.id)),
8608            dead_pid.to_string(),
8609        )
8610        .unwrap();
8611
8612        // Tick two, standing in for a poll long into this daemon's uptime:
8613        // the same function, called again, notices what only just appeared -
8614        // proving the sweep is not a one-shot startup check.
8615        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8616            pid != dead_pid
8617        });
8618        assert_eq!(swept, vec![t.id.clone()]);
8619    }
8620
8621    #[test]
8622    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8623        // `reclaim_orphaned_running` looks up the task's last run, which
8624        // touches `run::home()`; the first call anywhere in this binary wins,
8625        // so this is a no-op if another test already pinned one, and either
8626        // way the run id below is never written under it.
8627        crate::run::pin_test_home();
8628        let dir = tempfile::tempdir().unwrap();
8629        let queue = Queue::at(dir.path().to_path_buf());
8630        let mut t = task();
8631        t.id = "20260101-000000-crsh".to_owned();
8632        t.status = TaskStatus::Running;
8633        t.attempts = 1;
8634        // No `run.json` behind this id: standing in for a run this test does
8635        // not need to make readable, since the point is the lock, not the
8636        // recovery table `reclaim` already has its own tests for.
8637        t.runs.push("20260904-000000-4043".to_owned());
8638        queue.put(&mut t).unwrap();
8639        let dead_pid = injected_dead_pid();
8640
8641        // The crashed daemon's own claim, naming a pid nothing on the
8642        // machine holds anymore.
8643        std::fs::write(
8644            dir.path().join(format!("{}.lock", t.id)),
8645            dead_pid.to_string(),
8646        )
8647        .unwrap();
8648
8649        // Before the lock is swept the task looks claimed, and
8650        // `reclaim_orphaned_running` must leave it alone - this is exactly
8651        // the bug: a `running` task stranded behind a dead daemon's lock,
8652        // invisible to the claim-as-proof check because the lock outlived
8653        // the process that wrote it.
8654        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8655        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8656
8657        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8658            pid != dead_pid
8659        });
8660        assert_eq!(swept, vec![t.id.clone()]);
8661
8662        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8663        assert_eq!(reclaimed, vec![t.id.clone()]);
8664        let after = queue.get(&t.id).unwrap();
8665        assert_eq!(
8666            after.status,
8667            TaskStatus::Held,
8668            "no run.json to recover from, so a human is asked"
8669        );
8670        assert_eq!(
8671            after.runs,
8672            vec!["20260904-000000-4043".to_owned()],
8673            "the crashed run's id is kept as evidence, not discarded"
8674        );
8675    }
8676
8677    #[test]
8678    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8679        let dir = tempfile::tempdir().unwrap();
8680        let queue = Queue::at(dir.path().to_path_buf());
8681        let mut t = task();
8682        t.id = "20260101-000000-unknown".to_owned();
8683        queue.put(&mut t).unwrap();
8684        let dead_pid = injected_dead_pid();
8685        std::fs::write(
8686            dir.path().join(format!("{}.lock", t.id)),
8687            dead_pid.to_string(),
8688        )
8689        .unwrap();
8690
8691        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8692        assert!(swept.is_empty(), "an unknown pid must keep its lock");
8693        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8694    }
8695
8696    fn run_state_in(status: RunStatus, language: &str) -> RunState {
8697        let mut s = run_state(status);
8698        s.config.graph.language = language.to_owned();
8699        s
8700    }
8701
8702    fn unstarted_verdict(status: RunStatus) -> Verdict {
8703        Verdict {
8704            status,
8705            left_pr: false,
8706            quota_hit: false,
8707            parked: false,
8708            no_viable_candidates: false,
8709        }
8710    }
8711
8712    #[test]
8713    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8714        let mut t = task();
8715        t.attempts = 1;
8716        settle_in(
8717            &mut t,
8718            unstarted_verdict(RunStatus::AlreadyInBase),
8719            "already in main",
8720            1,
8721            phrases("en"),
8722        );
8723        assert_eq!(t.status, TaskStatus::Done);
8724        assert_eq!(t.attempts, 0);
8725    }
8726
8727    #[test]
8728    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8729        let reason = |language: &str| {
8730            let mut t = task();
8731            settle_in(
8732                &mut t,
8733                unstarted_verdict(RunStatus::Judging),
8734                "boom",
8735                1,
8736                phrases(language),
8737            );
8738            t.last_error.or(t.hold_reason).unwrap_or_default()
8739        };
8740        assert!(
8741            reason("en").starts_with("the graph stopped at `"),
8742            "{}",
8743            reason("en")
8744        );
8745        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8746        assert!(reason("日本語").contains("boom"));
8747        assert_eq!(reason("fr"), reason("en"));
8748    }
8749
8750    #[test]
8751    fn describe_follows_the_run_language_and_keeps_the_run_id() {
8752        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8753        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8754        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8755        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8756        assert!(ja.contains("[run "), "{ja}");
8757        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8758        assert!(ended.starts_with("run 終了: "), "{ended}");
8759        let mut de = run_state_in(RunStatus::Failed, "de");
8760        let mut en = run_state_in(RunStatus::Failed, "en");
8761        de.id = "same".to_owned();
8762        en.id = "same".to_owned();
8763        assert_eq!(describe(&de), describe(&en));
8764    }
8765
8766    #[test]
8767    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8768        use crate::handover::Refused;
8769        let cases = [
8770            Refused::Foreign {
8771                branch: "b".into(),
8772                path: "/w/x".into(),
8773                why: "made by hand".into(),
8774            },
8775            Refused::Unsafe {
8776                branch: "b".into(),
8777                path: "/w/x".into(),
8778                why: "its worktree has uncommitted changes (a.rs)".into(),
8779            },
8780            Refused::ReleaseFailed {
8781                branch: "b".into(),
8782                path: "/w/x".into(),
8783                run: "ab12".into(),
8784            },
8785        ];
8786        for r in &cases {
8787            let en = (phrases("en").handover_refused)(r);
8788            assert_eq!(en, r.to_string());
8789            let ja = (phrases("ja").handover_refused)(r);
8790            assert!(
8791                !ja.contains("is checked out") && !ja.contains("try again"),
8792                "{ja}"
8793            );
8794            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8795            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8796                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8797            }
8798        }
8799        assert!(phrases("en").handover_hint.contains("release the task"));
8800        assert!(phrases("ja").handover_hint.contains("解放"));
8801    }
8802
8803    #[test]
8804    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8805        let build = |lang: &str| {
8806            let mut s = run_state_in(RunStatus::Blocked, lang);
8807            s.id = "same".to_owned();
8808            s.config.graph.review_rounds = 3;
8809            let mut r = review_round(3);
8810            r.expected = 3;
8811            r.answered = 1;
8812            s.reviews.push(r);
8813            s.event(
8814                "review",
8815                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8816            );
8817            s
8818        };
8819        let en = describe(&build("en"));
8820        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8821        let ja = describe(&build("ja"));
8822        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8823        assert!(!ja.contains("never answered"), "{ja}");
8824        assert!(ja.contains("[run "), "{ja}");
8825
8826        // An incomplete panel whose verification failed is a different stop:
8827        // the real event must survive in ja too.
8828        let mut failed = build("ja");
8829        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8830            command: "cargo test".to_owned(),
8831            code: Some(1),
8832            output_tail: String::new(),
8833            duration_ms: 0,
8834            resource_blocked: false,
8835        });
8836        failed.event("review", "stopped; e2e failed: cargo test");
8837        let ja = describe(&failed);
8838        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8839        assert!(!ja.contains("席のレビュアー"), "{ja}");
8840    }
8841
8842    #[test]
8843    fn refusals_and_recovery_prose_follow_the_language() {
8844        let home = crate::run::test_home();
8845        let t = held_task_with("r1");
8846        let q = action_question(
8847            "r1",
8848            ask::ChoiceAction::Resume {
8849                run: "r1".to_owned(),
8850            },
8851        );
8852        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
8853            ActionDecision::Refuse(s) => s,
8854            other => panic!("{other:?}"),
8855        };
8856        assert!(refuse(phrases("en")).contains("could not be read: gone"));
8857        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8858        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8859
8860        let mut held = task();
8861        reclaim(&mut held, None, 2, "ja");
8862        assert!(held.hold_reason.unwrap().contains("保留にしました"));
8863        let mut held = task();
8864        reclaim(&mut held, None, 2, "xx");
8865        assert!(held.hold_reason.unwrap().contains("held for a human"));
8866    }
8867
8868    fn run_state(status: RunStatus) -> RunState {
8869        let mut state = RunState::new(
8870            PathBuf::from("/repo"),
8871            "main".to_owned(),
8872            "abc1234def".to_owned(),
8873            "add retries".to_owned(),
8874            Config::default(),
8875        );
8876        state.status = status;
8877        state
8878    }
8879
8880    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8881        Candidate {
8882            index: 0,
8883            label,
8884            agent: "claude".to_owned(),
8885            branch: format!("magi/x/{label}"),
8886            worktree: PathBuf::from("/repo"),
8887            summary: summary.to_owned(),
8888            stat: String::new(),
8889            files: 0,
8890            commits: usize::from(!empty),
8891            empty,
8892            failed: failed.map(str::to_owned),
8893            verified_noop: None,
8894            duration_ms: 0,
8895            folded: false,
8896        }
8897    }
8898
8899    #[test]
8900    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8901        let mut state = run_state(RunStatus::Blocked);
8902        state.gate = vec![
8903            CommandOutcome {
8904                command: "cargo make check".to_owned(),
8905                code: Some(0),
8906                output_tail: "ok".to_owned(),
8907                duration_ms: 0,
8908                resource_blocked: false,
8909            },
8910            CommandOutcome {
8911                command: "cargo test".to_owned(),
8912                code: Some(101),
8913                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8914                duration_ms: 0,
8915                resource_blocked: false,
8916            },
8917        ];
8918        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8919        assert!(d.contains("cargo test"), "{d}");
8920        assert!(
8921            !d.contains("cargo make check"),
8922            "a passing check is not a diagnostic: {d}"
8923        );
8924        assert!(d.contains("assertion failed"), "{d}");
8925    }
8926
8927    #[test]
8928    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8929        let mut state = run_state(RunStatus::Blocked);
8930        state.event(
8931            "land",
8932            "stopped: the fixer produced no commit while 2 check(s) were failing \
8933             (build, lint); stopping instead of looping on an unchanged tree",
8934        );
8935        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8936        assert!(d.contains("build"), "{d}");
8937        assert!(d.contains("lint"), "{d}");
8938        assert!(d.contains("fixer produced no commit"), "{d}");
8939    }
8940
8941    #[test]
8942    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8943        // `describe`'s output becomes `Task::last_error` verbatim, and the
8944        // phone renders that in the same alarm-styled box an ordinary
8945        // failure gets. A bare `verified_noop` there would read exactly like
8946        // the failure this status exists to be told apart from.
8947        let state = run_state(RunStatus::VerifiedNoop);
8948        let d = describe(&state);
8949        assert!(
8950            d.contains("agent-verified no-op"),
8951            "expected the display label, not the wire spelling: {d}"
8952        );
8953        assert!(!d.contains("verified_noop"), "{d}");
8954    }
8955
8956    #[test]
8957    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
8958        let mut state = run_state(RunStatus::Failed);
8959        state.gate.push(crate::run::CommandOutcome {
8960            command: "cargo test".into(),
8961            code: Some(101),
8962            output_tail: format!(
8963                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
8964                "  41: 0x1234 - backtrace frame\n".repeat(10000)
8965            ),
8966            duration_ms: 1,
8967            resource_blocked: false,
8968        });
8969        let d = diagnostic(&state).unwrap();
8970        assert!(d.contains("panicked at widget.rs:12"), "{d}");
8971        assert!(d.contains("assertion failed: widget missing"));
8972        assert!(d.contains("widget log"));
8973    }
8974
8975    #[test]
8976    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8977        // The whole point of the feature: a run held as "no candidate produced
8978        // a change" can mean the implementer actually finished the task and
8979        // only left a clean local tree behind - see AGENTS.md on this exact
8980        // failure mode. The diagnostic has to carry what the agent actually
8981        // said, not just the fact that nothing was there to judge.
8982        let mut state = run_state(RunStatus::Failed);
8983        state.candidates = vec![candidate(
8984            'A',
8985            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8986            true,
8987            None,
8988        )];
8989        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8990        assert!(d.contains("candidate A"), "{d}");
8991        assert!(d.contains("tagged v1.2.3"), "{d}");
8992    }
8993
8994    #[test]
8995    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8996        let mut state = run_state(RunStatus::Failed);
8997        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8998        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8999        assert!(d.contains("candidate A"), "{d}");
9000        assert!(d.contains("agent timed out"), "{d}");
9001    }
9002
9003    #[test]
9004    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9005        // A viable candidate existed, the gate never ran, and nothing land
9006        // said matches - `Task::last_error` is left to explain this one alone.
9007        let mut state = run_state(RunStatus::Failed);
9008        state.candidates = vec![candidate('A', "did the work", false, None)];
9009        assert!(diagnostic(&state).is_none());
9010    }
9011
9012    #[test]
9013    fn diagnostic_is_bounded_however_much_a_run_printed() {
9014        let mut state = run_state(RunStatus::Blocked);
9015        state.gate = vec![
9016            CommandOutcome {
9017                command: "cargo test".to_owned(),
9018                code: Some(101),
9019                output_tail: "x".repeat(50_000),
9020                duration_ms: 0,
9021                resource_blocked: false,
9022            },
9023            CommandOutcome {
9024                command: "cargo clippy".to_owned(),
9025                code: Some(1),
9026                output_tail: "y".repeat(50_000),
9027                duration_ms: 0,
9028                resource_blocked: false,
9029            },
9030        ];
9031        state.candidates = vec![
9032            candidate('A', &"z".repeat(50_000), true, None),
9033            candidate('B', &"w".repeat(50_000), true, None),
9034        ];
9035        let d = diagnostic(&state).expect("plenty here to diagnose");
9036        assert!(
9037            d.len() <= DIAGNOSTIC_MAX,
9038            "diagnostic grew to {} bytes, unbounded",
9039            d.len()
9040        );
9041    }
9042
9043    #[test]
9044    fn selected_delivery_guards_survive_recovery_failure_accounting() {
9045        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9046            let mut t = task();
9047            let mut state = run_state(status);
9048            t.pr_recovery = Some(crate::pr_recovery::Selection {
9049                url: "url".into(),
9050                branch: format!("magi/task-{}", t.id),
9051                head: "a".repeat(40),
9052                source_head: None,
9053                source_run: None,
9054                source_proof: None,
9055                disposition: Some(crate::pr_recovery::Disposition::Land),
9056                instruction: t.instruction.clone(),
9057                approved_at: Timestamp::now(),
9058            });
9059            state.pr_recovery = t.pr_recovery.clone();
9060            t.start(state.id.clone());
9061            settle_and_diagnose(
9062                &mut t,
9063                Verdict {
9064                    status,
9065                    left_pr: false,
9066                    quota_hit: false,
9067                    parked: false,
9068                    no_viable_candidates: false,
9069                },
9070                "delivery stopped",
9071                5,
9072                &state,
9073            );
9074            assert_eq!(t.status, TaskStatus::Held);
9075            let reason = t.hold_reason.as_deref().unwrap();
9076            if status == RunStatus::Ready {
9077                assert!(reason.contains("Selected PR delivery is incomplete"));
9078                assert!(t.recovery_budget.is_none());
9079            } else {
9080                assert!(reason.contains("Selected recovery stopped"));
9081                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9082            }
9083            assert!(t.pr_recovery.is_some());
9084        }
9085    }
9086
9087    #[test]
9088    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9089        let mut state = run_state(RunStatus::Voting);
9090        state.base_sync = Some(crate::run::BaseSync {
9091            tip: "base-tip".into(),
9092            behind: 3,
9093            attempts: 4,
9094            conflict: Some("base stopped".into()),
9095            already_in: None,
9096        });
9097        state.record_base_sync_stop("candidate-head");
9098        let mut t = task();
9099        t.start(state.id.clone());
9100        let verdict = Verdict {
9101            status: RunStatus::Blocked,
9102            left_pr: false,
9103            quota_hit: false,
9104            parked: false,
9105            no_viable_candidates: false,
9106        };
9107        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9108        assert_eq!(
9109            t.status,
9110            TaskStatus::Held,
9111            "unspent task attempts cannot start another competition"
9112        );
9113        let at = t.held_at;
9114        let cause = t.hold_notice_cause.clone();
9115        state.begin_pass();
9116        t.release_operator("test-resume", None);
9117        t.start(state.id.clone());
9118        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9119        assert_eq!(t.status, TaskStatus::Held);
9120        assert_eq!(t.held_at, at);
9121        assert_eq!(t.hold_notice_cause, cause);
9122    }
9123
9124    #[test]
9125    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9126        let mut state = run_state(RunStatus::Blocked);
9127        state.gate = vec![CommandOutcome {
9128            command: "cargo test".to_owned(),
9129            code: Some(101),
9130            output_tail: "assertion failed".to_owned(),
9131            duration_ms: 0,
9132            resource_blocked: false,
9133        }];
9134        let verdict = Verdict {
9135            status: RunStatus::Blocked,
9136            left_pr: false,
9137            quota_hit: false,
9138            parked: false,
9139            no_viable_candidates: false,
9140        };
9141
9142        // Attempt one of two still has a retry coming: no diagnostic yet, the
9143        // task is going to run again and this run's evidence would go stale.
9144        let mut t = task();
9145        t.start("run-1".to_owned());
9146        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9147        assert_eq!(t.status, TaskStatus::Failed);
9148        assert!(t.diagnostic.is_none());
9149
9150        // Attempt two exhausts the budget: now it is held, and the
9151        // diagnostic is what `magi task show` has to say more than one line.
9152        t.start("run-2".to_owned());
9153        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9154        assert_eq!(t.status, TaskStatus::Held);
9155        let d = t.diagnostic.expect("a held task must carry its diagnostic");
9156        assert!(d.contains("cargo test"), "{d}");
9157    }
9158
9159    #[test]
9160    fn a_held_task_names_the_open_question_it_is_waiting_on() {
9161        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
9162        // `magi ask` question settled Held with `hold_reason: null`, so the
9163        // notification said nothing actionable. `note_open_question` should
9164        // append the question id to whatever `handed_off` already wrote.
9165        crate::run::pin_test_home();
9166        let home = crate::run::home();
9167        let state = run_state(RunStatus::VerifiedNoop);
9168        let mut q = ask::Question::new(
9169            state.id.clone(),
9170            "implement".to_owned(),
9171            "impl-A".to_owned(),
9172            "is this really a no-op?".to_owned(),
9173            String::new(),
9174            Vec::new(),
9175        );
9176        Questions::at(home.join("questions")).put(&mut q).unwrap();
9177
9178        let verdict = Verdict {
9179            status: RunStatus::VerifiedNoop,
9180            left_pr: false,
9181            quota_hit: false,
9182            parked: false,
9183            no_viable_candidates: false,
9184        };
9185        let mut t = task();
9186        t.start(state.id.clone());
9187        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9188
9189        assert_eq!(t.status, TaskStatus::Held);
9190        let reason = t.hold_reason.expect("a held task must record why");
9191        assert!(
9192            reason.starts_with("run ended agent-verified no-op"),
9193            "the original settle reason must survive unchanged: {reason}"
9194        );
9195        assert!(
9196            reason.contains(q.short()),
9197            "the open question's id must be named so the notice is actionable: {reason}"
9198        );
9199    }
9200
9201    #[test]
9202    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9203        crate::run::pin_test_home();
9204        let state = run_state(RunStatus::VerifiedNoop);
9205
9206        let verdict = Verdict {
9207            status: RunStatus::VerifiedNoop,
9208            left_pr: false,
9209            quota_hit: false,
9210            parked: false,
9211            no_viable_candidates: false,
9212        };
9213        let mut t = task();
9214        t.start(state.id.clone());
9215        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9216
9217        assert_eq!(t.status, TaskStatus::Held);
9218        assert_eq!(
9219            t.hold_reason.as_deref(),
9220            Some("run ended agent-verified no-op"),
9221            "nothing to append when the question was already answered or never asked"
9222        );
9223    }
9224
9225    #[test]
9226    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
9227        crate::run::pin_test_home();
9228        let mut first = run_state(RunStatus::Blocked);
9229        first.id = "20260101-000000-sup1".to_owned();
9230        first.save().unwrap();
9231        let mut second = run_state(RunStatus::Merged);
9232        second.id = "20260101-000000-sup2".to_owned();
9233        second.save().unwrap();
9234
9235        let mut t = task();
9236        t.runs = vec![first.id.clone(), second.id.clone()];
9237        t.status = TaskStatus::Done;
9238
9239        supersede_prior_runs(&t, &crate::run::home());
9240
9241        assert_eq!(
9242            RunState::load(&first.id).unwrap().status,
9243            RunStatus::Superseded,
9244            "the first attempt's Blocked no longer needs anyone's attention"
9245        );
9246        assert_eq!(
9247            RunState::load(&second.id).unwrap().status,
9248            RunStatus::Merged,
9249            "the run that actually succeeded is left exactly as it was"
9250        );
9251    }
9252
9253    #[test]
9254    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
9255        // `is_working_on` alone only proves a *daemon* claim; a `magi run
9256        // --resume` invoked by hand outside the daemon never touches
9257        // `daemon.json` at all, so it would look identical to a genuinely
9258        // idle run without also consulting `RunState::liveness`, which reads
9259        // this run's own recorded `driver_pid` instead.
9260        crate::run::pin_test_home();
9261        let mut first = run_state(RunStatus::Blocked);
9262        first.id = "20260101-000000-sup9".to_owned();
9263        // This test process's own pid: guaranteed alive without needing a
9264        // real second process or daemon.
9265        first.driver_pid = Some(std::process::id());
9266        first.driver_started_at = Some(
9267            crate::proc::process_started_at(std::process::id())
9268                .expect("this test process's own start time must be queryable"),
9269        );
9270        first.save().unwrap();
9271        let mut second = run_state(RunStatus::Merged);
9272        second.id = "20260101-000000-supa".to_owned();
9273        second.save().unwrap();
9274
9275        let mut t = task();
9276        t.runs = vec![first.id.clone(), second.id.clone()];
9277        t.status = TaskStatus::Done;
9278
9279        supersede_prior_runs(&t, &crate::run::home());
9280
9281        assert_eq!(
9282            RunState::load(&first.id).unwrap().status,
9283            RunStatus::Blocked,
9284            "a live driver_pid means something is still actually working this run, \
9285             even though no daemon claims it - rewriting under it would just be \
9286             undone the next time that process saves"
9287        );
9288    }
9289
9290    #[test]
9291    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
9292        // The first resweep must skip a still-live attempt exactly like
9293        // `supersede_prior_runs` itself does; a later resweep, once that
9294        // process is no longer actually driving it, is what closes the gap
9295        // `supersede_prior_runs` alone leaves - a task only ever reaches
9296        // `Done` once, so nothing else would ever look at this run again.
9297        let dir = tempfile::tempdir().unwrap();
9298        let home = dir.path().to_path_buf();
9299        let queue = Queue::at(dir.path().join("queue"));
9300
9301        let mut first = run_state(RunStatus::Blocked);
9302        first.id = "20260101-000000-supd".to_owned();
9303        first.driver_pid = Some(std::process::id());
9304        first.driver_started_at = Some(
9305            crate::proc::process_started_at(std::process::id())
9306                .expect("this test process's own start time must be queryable"),
9307        );
9308        first.save_under(&home).unwrap();
9309        let mut second = run_state(RunStatus::Merged);
9310        second.id = "20260101-000000-supe".to_owned();
9311        second.save_under(&home).unwrap();
9312
9313        let mut t = task();
9314        t.runs = vec![first.id.clone(), second.id.clone()];
9315        t.status = TaskStatus::Done;
9316        queue.put(&mut t).unwrap();
9317
9318        resweep_superseded_attempts(&queue, &home);
9319        assert_eq!(
9320            RunState::load_under(&first.id, &home).unwrap().status,
9321            RunStatus::Blocked,
9322            "still live on the first pass, so still untouched"
9323        );
9324
9325        // Stand in for the manual process no longer being the one driving
9326        // this run: same pid (this test process really is still alive), but
9327        // an identity marker that no longer matches it - see
9328        // `RunState::liveness`'s own doc for why a mismatched
9329        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
9330        let mut stale = RunState::load_under(&first.id, &home).unwrap();
9331        stale.driver_started_at = Some("1".to_owned());
9332        stale.save_under(&home).unwrap();
9333
9334        resweep_superseded_attempts(&queue, &home);
9335        assert_eq!(
9336            RunState::load_under(&first.id, &home).unwrap().status,
9337            RunStatus::Superseded,
9338            "the second pass catches up what the first one correctly skipped"
9339        );
9340    }
9341
9342    #[test]
9343    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
9344        crate::run::pin_test_home();
9345        let mut first = run_state(RunStatus::Blocked);
9346        first.id = "20260101-000000-sup3".to_owned();
9347        first.save().unwrap();
9348        let mut second = run_state(RunStatus::Blocked);
9349        second.id = "20260101-000000-sup4".to_owned();
9350        second.save().unwrap();
9351
9352        let mut t = task();
9353        t.runs = vec![first.id.clone(), second.id.clone()];
9354        // Still retrying: nothing about this task's story is settled yet, so
9355        // neither Blocked run may be relabelled, even though a later attempt
9356        // already exists.
9357        t.status = TaskStatus::Failed;
9358
9359        supersede_prior_runs(&t, &crate::run::home());
9360
9361        assert_eq!(
9362            RunState::load(&first.id).unwrap().status,
9363            RunStatus::Blocked
9364        );
9365        assert_eq!(
9366            RunState::load(&second.id).unwrap().status,
9367            RunStatus::Blocked
9368        );
9369    }
9370
9371    #[test]
9372    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9373        // `magi task done` (or the API's equivalent) can close a task with no
9374        // run of its own ever having succeeded - there is nothing here that
9375        // counts as "the attempt that finished it", so nothing is rewritten.
9376        crate::run::pin_test_home();
9377        let mut first = run_state(RunStatus::Blocked);
9378        first.id = "20260101-000000-sup5".to_owned();
9379        first.save().unwrap();
9380
9381        let mut t = task();
9382        t.runs = vec![first.id.clone()];
9383        t.status = TaskStatus::Done;
9384
9385        supersede_prior_runs(&t, &crate::run::home());
9386
9387        assert_eq!(
9388            RunState::load(&first.id).unwrap().status,
9389            RunStatus::Blocked,
9390            "a single-attempt task has no earlier run to supersede"
9391        );
9392    }
9393
9394    #[test]
9395    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9396        // `magi task done` (or the web/conductor equivalents) can close a
9397        // task in any status, including one whose *last* recorded attempt is
9398        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
9399        // never watched, say. `runs.last()` being `Done`-adjacent is not
9400        // proof it actually succeeded, so nothing earlier may be relabelled
9401        // on its say-so alone.
9402        crate::run::pin_test_home();
9403        let mut first = run_state(RunStatus::Blocked);
9404        first.id = "20260101-000000-supb".to_owned();
9405        first.save().unwrap();
9406        let mut second = run_state(RunStatus::Failed);
9407        second.id = "20260101-000000-supc".to_owned();
9408        second.save().unwrap();
9409
9410        let mut t = task();
9411        t.runs = vec![first.id.clone(), second.id.clone()];
9412        t.status = TaskStatus::Done;
9413
9414        supersede_prior_runs(&t, &crate::run::home());
9415
9416        assert_eq!(
9417            RunState::load(&first.id).unwrap().status,
9418            RunStatus::Blocked,
9419            "the task's last attempt never landed, so there is nothing here \
9420             actually superseding it"
9421        );
9422    }
9423
9424    #[test]
9425    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9426        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
9427        // to look" - `Failed` and `VerifiedNoop` are already their own
9428        // terminal answers and must not be relabelled into a third one.
9429        crate::run::pin_test_home();
9430        let mut failed = run_state(RunStatus::Failed);
9431        failed.id = "20260101-000000-sup6".to_owned();
9432        failed.save().unwrap();
9433        let mut noop = run_state(RunStatus::VerifiedNoop);
9434        noop.id = "20260101-000000-sup7".to_owned();
9435        noop.save().unwrap();
9436        let mut winner = run_state(RunStatus::Ready);
9437        winner.id = "20260101-000000-sup8".to_owned();
9438        winner.save().unwrap();
9439
9440        let mut t = task();
9441        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9442        t.status = TaskStatus::Done;
9443
9444        supersede_prior_runs(&t, &crate::run::home());
9445
9446        assert_eq!(
9447            RunState::load(&failed.id).unwrap().status,
9448            RunStatus::Failed
9449        );
9450        assert_eq!(
9451            RunState::load(&noop.id).unwrap().status,
9452            RunStatus::VerifiedNoop
9453        );
9454    }
9455
9456    fn approval_question(run: &str) -> ask::Question {
9457        ask::Question::new(
9458            run.to_owned(),
9459            land::APPROVAL_NODE.to_owned(),
9460            "land".to_owned(),
9461            "merge?".to_owned(),
9462            String::new(),
9463            vec!["merge".to_owned(), "hold".to_owned()],
9464        )
9465    }
9466
9467    #[test]
9468    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9469        crate::run::pin_test_home();
9470        let mut state = run_state(RunStatus::Landing);
9471        state.id = "20260101-000000-fre1".to_owned();
9472        state.parked = true;
9473        state.save().unwrap();
9474        ask::Questions::open()
9475            .put(&mut approval_question(&state.id))
9476            .unwrap();
9477
9478        let mut t = task();
9479        t.runs.push(state.id.clone());
9480        assert_eq!(
9481            land_resume_state(&t),
9482            LandResume::StillWaiting,
9483            "nobody has answered and the timeout has not passed"
9484        );
9485    }
9486
9487    #[test]
9488    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9489        crate::run::pin_test_home();
9490        let mut state = run_state(RunStatus::Gating);
9491        state.id = "20260101-000000-gt01".to_owned();
9492        state.parked = true;
9493        state.config.graph.answer_timeout = 60;
9494        state.github_text = Some(crate::run::GithubTextAsk {
9495            rewrite: None,
9496            fingerprint: "f".into(),
9497            title: true,
9498            body: false,
9499            categories: vec!["title-language".into()],
9500            question: None,
9501            asks: 1,
9502            resolved: false,
9503            chosen_title: None,
9504            choice: None,
9505            publication: None,
9506        });
9507        state.save().unwrap();
9508        let store = ask::Questions::open();
9509        let mut q = ask::Question::new(
9510            state.id.clone(),
9511            crate::github_text::ASK_NODE.to_owned(),
9512            crate::github_text::ASK_SEAT.to_owned(),
9513            "s".into(),
9514            String::new(),
9515            vec!["use fallback".into()],
9516        );
9517        store.put(&mut q).unwrap();
9518        let mut t = task();
9519        t.runs.push(state.id.clone());
9520        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9521        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9522        store.put(&mut q).unwrap();
9523        assert_eq!(land_resume_state(&t), LandResume::Ready);
9524        assert!(!store.get(&q.id).unwrap().status.open());
9525        // Once decided, a parked run is an ordinary candidate again.
9526        state.github_text.as_mut().unwrap().resolved = true;
9527        state.save().unwrap();
9528        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9529    }
9530
9531    #[test]
9532    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9533        // `ask::ask_and_wait`'s own deadline used to retire a question
9534        // nobody answered; land's approval bypasses that wait (see
9535        // `land::approval_gate`), so this is now the only place
9536        // `graph.answer_timeout` is enforced for a land approval at all.
9537        crate::run::pin_test_home();
9538        let mut state = run_state(RunStatus::Landing);
9539        state.id = "20260101-000000-exp1".to_owned();
9540        state.parked = true;
9541        state.config.graph.answer_timeout = 60;
9542        state.save().unwrap();
9543
9544        let store = ask::Questions::open();
9545        let mut q = approval_question(&state.id);
9546        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9547        store.put(&mut q).unwrap();
9548
9549        let mut t = task();
9550        t.runs.push(state.id.clone());
9551        assert_eq!(
9552            land_resume_state(&t),
9553            LandResume::Ready,
9554            "an expired question must not be waited on forever"
9555        );
9556
9557        let after = store.get(&q.id).unwrap();
9558        assert!(
9559            !after.status.open(),
9560            "the question is abandoned, not silently ignored"
9561        );
9562        assert!(
9563            after.resolution().is_none(),
9564            "an abandoned question is not read as a decision"
9565        );
9566    }
9567
9568    #[test]
9569    fn reclaim_settles_a_running_task_against_its_last_run() {
9570        let mut t = task();
9571        t.start("20260904-000000-4043".to_owned());
9572        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9573        assert_eq!(
9574            t.status,
9575            TaskStatus::Done,
9576            "a run that actually finished must not stay `running` forever"
9577        );
9578    }
9579
9580    #[test]
9581    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
9582        let dir = tempfile::tempdir().unwrap();
9583        let queue = Queue::at(dir.path().join("queue"));
9584        let mut task = task();
9585        let mut run = run_state(RunStatus::Blocked);
9586        run.reserve_under(dir.path()).unwrap();
9587        run.driver_exited = true;
9588        run.save_under(dir.path()).unwrap();
9589        queue.put(&mut task).unwrap();
9590        let stale = task.clone();
9591        task.resume_override = Some(crate::queue::OperatorResume {
9592            question_id: "pending-resume".into(),
9593            at: Timestamp::now(),
9594            conductor_rehold: None,
9595            forced: true,
9596            pinned_run: Some(run.id.clone()),
9597        });
9598        task.start(run.id.clone());
9599        queue.put(&mut task).unwrap();
9600        // Discard every in-memory handoff, as a worker death before execute does.
9601        let mut recovered = queue.get(&task.id).unwrap();
9602        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
9603        reclaim(&mut recovered, Some(disk), 2, "en");
9604        queue.put(&mut recovered).unwrap();
9605        assert!(recovered.resume_override.is_none());
9606        assert_eq!(
9607            recovered.dispatched_resumes.get("pending-resume"),
9608            Some(&run.id)
9609        );
9610        let mut stale = stale;
9611        queue.put(&mut stale).unwrap();
9612        assert_eq!(
9613            stale.dispatched_resumes, recovered.dispatched_resumes,
9614            "a stale task writer cannot erase dispatch ownership"
9615        );
9616        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
9617        assert!(resumed.decision_starts.is_empty());
9618        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
9619        assert!(
9620            resumed.decision_starts.is_empty(),
9621            "handoff is not execution proof"
9622        );
9623        resumed.begin_pass();
9624        resumed.save_under(dir.path()).unwrap();
9625        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
9626        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
9627        disk.carry_dispatched_resumes(&recovered);
9628        disk.begin_pass();
9629        assert_eq!(
9630            disk.decision_starts.get("pending-resume"),
9631            Some(&0),
9632            "later execution must preserve the original pass receipt"
9633        );
9634    }
9635
9636    #[test]
9637    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
9638        let mut t = task();
9639        t.start("20260904-000000-4043".to_owned());
9640        t.last_error = Some("earlier trouble".to_owned());
9641        let mut state = run_state(RunStatus::Judging);
9642        state.parked = true;
9643        reclaim(&mut t, Some(state), 1, "en");
9644        assert_eq!(t.status, TaskStatus::Parked);
9645        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
9646        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9647        assert!(t.park_reason.is_some());
9648        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
9649        assert!(!t.fresh_start);
9650        assert!(t.status.runnable());
9651    }
9652
9653    #[test]
9654    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9655        let mut t = task();
9656        t.start("20260904-000000-4043".to_owned());
9657        t.last_error = Some("earlier trouble".to_owned());
9658        settle(
9659            &mut t,
9660            Verdict {
9661                status: RunStatus::Judging,
9662                left_pr: false,
9663                quota_hit: false,
9664                parked: true,
9665                no_viable_candidates: false,
9666            },
9667            "parked after `judging`",
9668            1,
9669        );
9670        assert_eq!(t.status, TaskStatus::Parked);
9671        assert_eq!(t.attempts, 0);
9672        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9673        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9674        assert_eq!(t.schema, crate::queue::SCHEMA);
9675        assert!(
9676            crate::notices::task_held(&t).is_none(),
9677            "a park is not news"
9678        );
9679        t.start("20260904-000000-4043".to_owned());
9680        assert_eq!(t.park_reason, None);
9681    }
9682
9683    #[test]
9684    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9685        // A blocked run with attempts left goes back to `Failed`, exactly as
9686        // it would from `attempt` itself - `reclaim` must not invent a second
9687        // policy for a task a daemon merely stopped without reporting.
9688        let mut t = task();
9689        t.start("20260904-000000-4043".to_owned());
9690        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9691        assert_eq!(t.status, TaskStatus::Failed);
9692        assert!(t.status.runnable());
9693    }
9694
9695    #[test]
9696    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9697        let mut t = task();
9698        t.start("20260904-000000-4043".to_owned());
9699        assert_eq!(t.attempts, 1);
9700        let mut run = run_state(RunStatus::Implementing);
9701        run.id = "20260904-000000-4043".to_owned();
9702        run.begin_pass();
9703        let cause = crate::run::ParkCause::Upgrade {
9704            from: "0.121.0".to_owned(),
9705            to: Some("0.121.1".to_owned()),
9706        };
9707        run.end_pass_parked(cause.clone());
9708        run.parked = true;
9709        let verdict = Verdict {
9710            status: run.status,
9711            left_pr: false,
9712            quota_hit: false,
9713            parked: true,
9714            no_viable_candidates: false,
9715        };
9716        // A crash after the checkpoint but before queue settlement must
9717        // recover exactly the same scheduling evidence and refund.
9718        let mut orphan = t.clone();
9719        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9720        assert_eq!(orphan.status, TaskStatus::Parked);
9721        assert_eq!(orphan.attempts, 0);
9722        assert_eq!(
9723            orphan.upgrade_resume_key(),
9724            Some((run.passes[0].started_at, orphan.id.as_str()))
9725        );
9726        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9727        assert_eq!(t.attempts, 0);
9728        assert_eq!(t.passes.len(), 1);
9729        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9730        assert_eq!(t.passes[0].parked, Some(cause));
9731        assert_eq!(t.passes[0].pass_index, 0);
9732        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9733        assert!(t.upgrade_resume_key().is_some());
9734
9735        // A resumed pass that then fails spends its attempt, and the earlier
9736        // pass's entry is untouched.
9737        t.start("20260904-000000-4043".to_owned());
9738        run.begin_pass();
9739        run.status = RunStatus::Failed;
9740        let verdict = Verdict {
9741            status: RunStatus::Failed,
9742            left_pr: false,
9743            quota_hit: false,
9744            parked: false,
9745            no_viable_candidates: false,
9746        };
9747        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9748        assert_eq!(t.passes.len(), 2);
9749        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9750        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9751        assert_eq!(t.passes[1].pass_index, 1);
9752        assert_eq!(t.attempts, 1);
9753    }
9754
9755    #[test]
9756    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9757        let mut t = task();
9758        t.start("20260904-000000-4043".to_owned());
9759        reclaim(&mut t, None, 2, "en");
9760        assert_eq!(t.status, TaskStatus::Held);
9761        assert!(
9762            t.last_error
9763                .as_deref()
9764                .is_some_and(|e| e.contains("running")),
9765            "the operator needs to know why this task was held"
9766        );
9767    }
9768
9769    #[test]
9770    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9771        let dir = tempfile::tempdir().unwrap();
9772        let queue = Queue::at(dir.path().to_path_buf());
9773
9774        // No run recorded, so this never has to touch `RunState::load`.
9775        let mut orphaned = task();
9776        orphaned.id = "20260904-000000-orph".to_owned();
9777        orphaned.status = TaskStatus::Running;
9778        orphaned.attempts = 1;
9779        queue.put(&mut orphaned).unwrap();
9780
9781        let mut alive = task();
9782        alive.id = "20260904-000000-live".to_owned();
9783        alive.status = TaskStatus::Running;
9784        alive.attempts = 1;
9785        queue.put(&mut alive).unwrap();
9786        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9787
9788        let mut queued = task();
9789        queued.id = "20260904-000000-wait".to_owned();
9790        queue.put(&mut queued).unwrap();
9791
9792        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9793        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9794
9795        assert_eq!(
9796            queue.get(&orphaned.id).unwrap().status,
9797            TaskStatus::Held,
9798            "nothing was driving it and there was no run to recover"
9799        );
9800        assert_eq!(
9801            queue.get(&alive.id).unwrap().status,
9802            TaskStatus::Running,
9803            "a live claim must protect the task it belongs to"
9804        );
9805        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9806    }
9807
9808    /// Read a run.json back from an explicit `home`, the same way
9809    /// `reclaim_abandoned_runs` itself does - never through the
9810    /// process-global `RunState::load`, which this test's own `home` (an
9811    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
9812    /// use at all.
9813    fn read_run_under(home: &Path, id: &str) -> RunState {
9814        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9815        serde_json::from_str(&body).unwrap()
9816    }
9817
9818    #[test]
9819    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9820        let dir = tempfile::tempdir().unwrap();
9821        let home = dir.path().to_path_buf();
9822        let now = Timestamp::now();
9823        let overrun_seat = || crate::run::ActiveSeat {
9824            node: "implement".to_owned(),
9825            started_at: now - jiff::SignedDuration::new(21_000, 0),
9826            timeout_secs: 3_600,
9827            attempt: 0,
9828            task: None,
9829            command: None,
9830            index: None,
9831            total: None,
9832        };
9833
9834        let mut dead = run_state(RunStatus::Implementing);
9835        dead.id = "20260101-000000-dead".to_owned();
9836        dead.active.insert("impl-A".to_owned(), overrun_seat());
9837        // A `driver_pid` the injected query below confirms gone outright —
9838        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
9839        dead.driver_pid = Some(4242);
9840        dead.save_under(&home).unwrap();
9841
9842        // Same shape, but a live daemon's heartbeat names it: must be left
9843        // exactly alone, however far past its own timeout the seat sits.
9844        let mut alive = run_state(RunStatus::Implementing);
9845        alive.id = "20260101-000000-aliv".to_owned();
9846        alive.active.insert("impl-A".to_owned(), overrun_seat());
9847        alive.save_under(&home).unwrap();
9848        let mut status = Status::new();
9849        status.current = vec![Current {
9850            worker: None,
9851            task: "20260101-000000-task".to_owned(),
9852            run: alive.id.clone(),
9853        }];
9854        write_status_to(&home.join("daemon.json"), &status).unwrap();
9855
9856        // The abandoned seat left an open question behind: nobody is left to
9857        // read an answer once the run is failed, and this must not wait for
9858        // some later daemon startup's own sweep to notice that.
9859        let questions = Questions::at(home.join("questions"));
9860        let mut q = ask::Question::new(
9861            dead.id.clone(),
9862            "implement".to_owned(),
9863            "impl-A".to_owned(),
9864            "Which storage backend?".to_owned(),
9865            String::new(),
9866            vec!["SQLite".to_owned(), "Redis".to_owned()],
9867        );
9868        questions.put(&mut q).unwrap();
9869
9870        let abandoned = reclaim_abandoned_runs_with(
9871            &home,
9872            now,
9873            |pid| if pid == 4242 { Some(false) } else { None },
9874            |_| panic!("a query answering Dead outright needs no identity corroboration"),
9875        );
9876        assert_eq!(abandoned, vec![dead.id.clone()]);
9877
9878        let reloaded = read_run_under(&home, &dead.id);
9879        assert_eq!(reloaded.status, RunStatus::Failed);
9880        assert!(reloaded.active.is_empty());
9881        assert!(
9882            !questions.get(&q.id).unwrap().status.open(),
9883            "the failed run's own open question must be settled in the same pass"
9884        );
9885
9886        let still_alive = read_run_under(&home, &alive.id);
9887        assert_eq!(
9888            still_alive.status,
9889            RunStatus::Implementing,
9890            "a live daemon's claim protects it"
9891        );
9892        assert!(!still_alive.active.is_empty());
9893    }
9894
9895    /// The exact shape a review round flagged as broken: `magi serve` running
9896    /// in this same `home` scans *every* run on disk, including a manual
9897    /// `magi review` / `magi run` this daemon never started and that
9898    /// therefore claims no heartbeat of its own. Before this scan asked
9899    /// `liveness` rather than just `is_working_on`, a manual run whose active
9900    /// seat merely ran a little past its own timeout — the CLI finishing up,
9901    /// its result still being collected — got wiped and failed by a daemon
9902    /// that had nothing to do with it, out from under a process that was
9903    /// still very much running.
9904    #[test]
9905    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9906        let dir = tempfile::tempdir().unwrap();
9907        let home = dir.path().to_path_buf();
9908        let now = Timestamp::now();
9909
9910        let mut manual = run_state(RunStatus::Reviewing);
9911        manual.id = "20260101-000000-manl".to_owned();
9912        manual.active.insert(
9913            "review-1".to_owned(),
9914            crate::run::ActiveSeat {
9915                node: "review".to_owned(),
9916                started_at: now - jiff::SignedDuration::new(21_000, 0),
9917                timeout_secs: 3_600,
9918                attempt: 0,
9919                task: None,
9920                command: None,
9921                index: None,
9922                total: None,
9923            },
9924        );
9925        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
9926        // but a real, still-running process: `liveness` must corroborate this
9927        // as `Live`, not read the missing daemon claim as death.
9928        manual.driver_pid = Some(4242);
9929        manual.driver_started_at = Some("1790000000".to_owned());
9930        manual.save_under(&home).unwrap();
9931
9932        let abandoned = reclaim_abandoned_runs_with(
9933            &home,
9934            now,
9935            |pid| if pid == 4242 { Some(true) } else { None },
9936            |pid| {
9937                if pid == 4242 {
9938                    Some("1790000000".to_owned())
9939                } else {
9940                    None
9941                }
9942            },
9943        );
9944        assert!(
9945            abandoned.is_empty(),
9946            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9947        );
9948
9949        let reloaded = read_run_under(&home, &manual.id);
9950        assert_eq!(reloaded.status, RunStatus::Reviewing);
9951        assert!(!reloaded.active.is_empty());
9952    }
9953
9954    #[test]
9955    fn an_already_claimed_task_is_skipped_rather_than_failed() {
9956        let dir = tempfile::tempdir().unwrap();
9957        let queue = Queue::at(dir.path().to_path_buf());
9958        let mut only = task();
9959        queue.put(&mut only).unwrap();
9960
9961        let _elsewhere = queue.claim(&only.id).unwrap();
9962        let candidates = runnable(&queue);
9963        assert_eq!(candidates.len(), 1, "the task is still runnable");
9964        assert!(
9965            queue.claim(&candidates[0].id).is_err(),
9966            "the loop cannot take a claim somebody else holds"
9967        );
9968
9969        let after = queue.get(&only.id).unwrap();
9970        assert_eq!(after.status, TaskStatus::Queued);
9971        assert_eq!(
9972            after.attempts, 0,
9973            "losing the race is not an attempt at the task"
9974        );
9975        assert_eq!(after.last_error, None);
9976    }
9977
9978    #[test]
9979    fn the_status_file_round_trips_and_its_heartbeat_advances() {
9980        let dir = tempfile::tempdir().unwrap();
9981        let path = dir.path().join("daemon.json");
9982
9983        let mut status = Status::new();
9984        status.idle = false;
9985        status.completed = 7;
9986        status.current = vec![Current {
9987            worker: None,
9988            task: "20260902-000000-t111".to_owned(),
9989            run: "20260902-000001-r111".to_owned(),
9990        }];
9991        write_status_to(&path, &status).unwrap();
9992        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9993        assert_eq!(first.schema, SCHEMA);
9994        assert_eq!(first.pid, std::process::id());
9995        assert!(!first.idle);
9996        assert_eq!(first.completed, 7);
9997        assert_eq!(first.current, status.current);
9998        assert!(
9999            !path.with_extension("json.tmp").exists(),
10000            "the temp file is renamed, not left behind"
10001        );
10002
10003        std::thread::sleep(Duration::from_millis(5));
10004        status.updated_at = Timestamp::now();
10005        status.polls = 3;
10006        write_status_to(&path, &status).unwrap();
10007        let second: Status =
10008            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10009        assert!(
10010            second.updated_at > first.updated_at,
10011            "a reader can only detect staleness if the heartbeat moves"
10012        );
10013        assert_eq!(
10014            second.started_at, first.started_at,
10015            "the start time is not a heartbeat"
10016        );
10017        assert_eq!(second.polls, 3);
10018    }
10019
10020    #[test]
10021    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
10022        let dir = tempfile::tempdir().unwrap();
10023
10024        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
10025
10026        let mut status = Status::new();
10027        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
10028        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10029        let stale = read_status(dir.path()).unwrap();
10030        assert!(
10031            !stale.running(Timestamp::now()),
10032            "a minute without a heartbeat is a dead daemon, not a busy one"
10033        );
10034        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
10035
10036        status.updated_at = Timestamp::now();
10037        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10038        let fresh = read_status(dir.path()).unwrap();
10039        assert!(fresh.running(Timestamp::now()));
10040    }
10041
10042    #[test]
10043    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
10044        let dir = tempfile::tempdir().unwrap();
10045        let now = Timestamp::now();
10046        let mine = "20260903-080619-01c2";
10047
10048        assert!(
10049            !is_working_on(dir.path(), mine, now),
10050            "no status file means nobody is working on anything"
10051        );
10052
10053        let mut status = Status::new();
10054        status.current = vec![Current {
10055            worker: None,
10056            task: "20260903-080340-0167".to_owned(),
10057            run: mine.to_owned(),
10058        }];
10059        status.updated_at = now;
10060        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10061        assert!(is_working_on(dir.path(), mine, now));
10062        assert!(
10063            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
10064            "a daemon busy with one run is not working on another"
10065        );
10066
10067        // A killed daemon stops writing heartbeats but leaves the file behind
10068        // naming the run it died in. That run must not be undeletable forever.
10069        status.updated_at = now - jiff::SignedDuration::from_secs(600);
10070        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10071        assert!(
10072            !is_working_on(dir.path(), mine, now),
10073            "a stale heartbeat is a dead daemon, so its run is a leftover"
10074        );
10075    }
10076
10077    #[test]
10078    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
10079        let dir = tempfile::tempdir().unwrap();
10080        let now = Timestamp::now();
10081
10082        assert!(
10083            !is_working_on_short(dir.path(), "01c2", now),
10084            "no status file means nobody is working on anything"
10085        );
10086
10087        let mut status = Status::new();
10088        status.current = vec![Current {
10089            worker: None,
10090            task: "20260903-080340-0167".to_owned(),
10091            run: "20260903-080619-01c2".to_owned(),
10092        }];
10093        status.updated_at = now;
10094        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10095        assert!(
10096            is_working_on_short(dir.path(), "01c2", now),
10097            "the run's short id is the last block of its full id"
10098        );
10099        assert!(
10100            !is_working_on_short(dir.path(), "3cbf", now),
10101            "a daemon busy with one worktree bay is not working on another"
10102        );
10103    }
10104
10105    #[test]
10106    fn a_newer_status_file_still_yields_a_reading() {
10107        let dir = tempfile::tempdir().unwrap();
10108        // A field this build has never heard of must not turn the reading into
10109        // nothing at all; that is the whole reason the reader is permissive.
10110        std::fs::write(
10111            dir.path().join("daemon.json"),
10112            serde_json::json!({
10113                "schema": 2,
10114                "updated_at": Timestamp::now().to_string(),
10115                "idle": true,
10116                "surprise": { "nested": [1, 2, 3] },
10117            })
10118            .to_string(),
10119        )
10120        .unwrap();
10121
10122        let reading = read_status(dir.path()).expect("a forward-compatible read");
10123        assert!(reading.running(Timestamp::now()));
10124        assert!(reading.idle);
10125        assert!(reading.current.is_empty());
10126    }
10127
10128    #[test]
10129    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
10130        // A daemon started before `current` became a list keeps writing this
10131        // shape on every heartbeat until it is restarted. A rolling upgrade
10132        // - a newer `magi web` or `magi doctor` reading an older `magi
10133        // serve`'s heartbeat - must still see the run it is on, not "no
10134        // daemon" from a type mismatch failing the whole struct.
10135        let dir = tempfile::tempdir().unwrap();
10136        std::fs::write(
10137            dir.path().join("daemon.json"),
10138            serde_json::json!({
10139                "schema": 1,
10140                "pid": 4242,
10141                "updated_at": Timestamp::now().to_string(),
10142                "idle": false,
10143                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
10144                "completed": 3,
10145                "polls": 9,
10146            })
10147            .to_string(),
10148        )
10149        .unwrap();
10150
10151        let reading = read_status(dir.path()).expect("an older shape must still parse");
10152        assert!(reading.running(Timestamp::now()));
10153        assert_eq!(
10154            reading.current,
10155            vec![Current {
10156                worker: None,
10157                task: "20260902-140501-aaaa".to_owned(),
10158                run: "20260902-140502-bbbb".to_owned(),
10159            }]
10160        );
10161    }
10162
10163    #[test]
10164    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
10165        let dir = tempfile::tempdir().unwrap();
10166        std::fs::write(
10167            dir.path().join("daemon.json"),
10168            serde_json::json!({
10169                "schema": 1,
10170                "updated_at": Timestamp::now().to_string(),
10171                "idle": true,
10172                "current": null,
10173            })
10174            .to_string(),
10175        )
10176        .unwrap();
10177        let with_null = read_status(dir.path()).expect("null must still parse");
10178        assert!(with_null.current.is_empty());
10179
10180        std::fs::write(
10181            dir.path().join("daemon.json"),
10182            serde_json::json!({
10183                "schema": 1,
10184                "updated_at": Timestamp::now().to_string(),
10185                "idle": true,
10186            })
10187            .to_string(),
10188        )
10189        .unwrap();
10190        let absent = read_status(dir.path()).expect("a missing field must still parse");
10191        assert!(absent.current.is_empty());
10192    }
10193
10194    #[test]
10195    fn a_task_without_a_repository_runs_in_the_daemons_default() {
10196        let fallback = Path::new("/default");
10197        let mut blank = task();
10198        blank.repo = PathBuf::new();
10199        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
10200        let mut dot = task();
10201        dot.repo = PathBuf::from(".");
10202        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
10203        assert_eq!(
10204            repo_for(&task(), fallback),
10205            PathBuf::from("/repo"),
10206            "a task that names a repository keeps it"
10207        );
10208    }
10209
10210    #[test]
10211    fn task_implementers_edit_inherits_daemon_config_and_merge() {
10212        let dir = tempfile::tempdir().unwrap();
10213        let path = dir.path().join("explicit.toml");
10214        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
10215        let opts = Opts {
10216            config: Some(path),
10217            merge: Some("none".into()),
10218            ..Default::default()
10219        };
10220        let mut t = task();
10221        t.set_implementers(
10222            2,
10223            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10224                .unwrap(),
10225        )
10226        .unwrap();
10227        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10228        assert_eq!(cfg.graph.implementers, 2);
10229        assert_eq!(cfg.graph.judges, 1);
10230        assert_eq!(cfg.merge.mode, MergeMode::None);
10231        t.set_implementers(1, &cfg).unwrap();
10232        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10233        apply_task_implementers(&mut cfg, &t);
10234        assert_eq!(cfg.graph.implementers, 1);
10235        assert_eq!(cfg.graph.judges, 1);
10236        assert_eq!(cfg.merge.mode, MergeMode::None);
10237    }
10238
10239    #[test]
10240    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
10241        let dir = tempfile::tempdir().unwrap();
10242        let repo = dir.path().join("repo");
10243        std::fs::create_dir(&repo).unwrap();
10244        std::fs::write(
10245            repo.join("magi.toml"),
10246            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
10247        )
10248        .unwrap();
10249        let daemon_config = dir.path().join("daemon.toml");
10250        std::fs::write(
10251            &daemon_config,
10252            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
10253        )
10254        .unwrap();
10255        let opts = Opts {
10256            config: Some(daemon_config),
10257            merge: Some("pr".into()),
10258            ..Default::default()
10259        };
10260        let q = Queue::at(dir.path().join("queue"));
10261        let validation: Config =
10262            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10263                .unwrap();
10264        // No provenance field on legacy direct tasks: both shapes stay isolated.
10265        for record in ["{}", r#"{"candidates":2}"#] {
10266            let overrides = serde_json::from_str(record).unwrap();
10267            let filing = crate::direct::Filing {
10268                instruction: "work".into(),
10269                title: "direct".into(),
10270                repo: repo.clone(),
10271                source: crate::queue::Source::Human,
10272                solo: false,
10273                overrides,
10274                review_of: None,
10275                sources: Default::default(),
10276            };
10277            let filed =
10278                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
10279            let crate::direct::Filed::Standalone {
10280                mut task,
10281                claim: _claim,
10282            } = filed
10283            else {
10284                panic!("local filing")
10285            };
10286            let before = prepare_for(&repo, &opts, &task).unwrap();
10287            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
10288            assert_eq!(
10289                before.merge.mode,
10290                MergeMode::None,
10291                "daemon --merge must not leak"
10292            );
10293            for n in [2, 1, 2] {
10294                task.set_implementers(n, &validation).unwrap();
10295                q.put(&mut task).unwrap();
10296                task = q.get(&task.id).unwrap();
10297                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
10298                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
10299                apply_task_implementers(&mut cfg, &task);
10300                assert_eq!(cfg.graph.implementers, usize::from(n));
10301                assert_eq!(cfg.graph.judges, 2);
10302                assert_eq!(cfg.merge.mode, MergeMode::None);
10303            }
10304        }
10305    }
10306
10307    #[test]
10308    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
10309        let cfg: Config =
10310            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10311                .unwrap();
10312        let mut t = task();
10313        t.review_of = Some("review-target".into());
10314        t.hold_manual(Some("retry".into()));
10315        let mut previous = RunState::new(
10316            PathBuf::from("/repo"),
10317            "main".into(),
10318            "abc1234".into(),
10319            "review".into(),
10320            cfg.clone(),
10321        );
10322        previous.config.graph.implementers = 2;
10323        for count in [1, 3] {
10324            t.set_implementers(count, &cfg).unwrap();
10325            t.release();
10326            assert_eq!(t.review_of.as_deref(), Some("review-target"));
10327            for proposed in [
10328                Starter::Resume(previous.id.clone()),
10329                Starter::Review("recovery-target".into()),
10330            ] {
10331                assert_eq!(
10332                    starter_with_implementers(&t, Some(&previous), proposed),
10333                    Starter::Review("review-target".into())
10334                );
10335            }
10336            let mut configured = cfg.clone();
10337            apply_task_implementers(&mut configured, &t);
10338            assert_eq!(configured.graph.implementers, usize::from(count));
10339            assert_eq!(previous.config.graph.implementers, 2);
10340        }
10341    }
10342
10343    #[test]
10344    fn task_implementers_dispatch_and_resume_agree() {
10345        let mut t = task();
10346        let cfg: crate::config::Config =
10347            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10348                .unwrap();
10349        let mut run = RunState::new(
10350            PathBuf::from("/repo"),
10351            "main".into(),
10352            "abc1234".into(),
10353            "work".into(),
10354            cfg.clone(),
10355        );
10356        run.config.graph.implementers = 2;
10357        for n in [2, 1, 3, 2] {
10358            t.set_implementers(n, &cfg).unwrap();
10359            let mut dispatched = cfg.clone();
10360            apply_task_implementers(&mut dispatched, &t);
10361            assert_eq!(dispatched.graph.implementers, usize::from(n));
10362            assert_eq!(implementers_match(&t, &run), n == 2);
10363            for proposed in [
10364                Starter::Resume(run.id.clone()),
10365                Starter::Review("old-branch".into()),
10366            ] {
10367                let expected = if n == 2 {
10368                    proposed.clone()
10369                } else {
10370                    Starter::Start
10371                };
10372                assert_eq!(
10373                    starter_with_implementers(&t, Some(&run), proposed),
10374                    expected
10375                );
10376            }
10377            assert_eq!(
10378                run.config.graph.implementers, 2,
10379                "history must not be rewritten"
10380            );
10381        }
10382        t.solo = false;
10383        t.overrides = None;
10384        assert!(implementers_match(&t, &run));
10385    }
10386
10387    #[test]
10388    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
10389        // Three seats said out loud. What `solo` promises is one candidate
10390        // *whatever the config asks for*, so the contrast has to be a number
10391        // this test owns - it used to be `Config::default()`'s, which became
10392        // 1 when one implementation became the default and left the two
10393        // halves of this test asserting the same thing.
10394        let mut solo_cfg = Config::default();
10395        solo_cfg.graph.implementers = 3;
10396        let mut solo_task = task();
10397        solo_task.solo = true;
10398        apply_task_implementers(&mut solo_cfg, &solo_task);
10399        assert_eq!(solo_cfg.graph.implementers, 1);
10400
10401        let mut plain_cfg = Config::default();
10402        plain_cfg.graph.implementers = 3;
10403        let plain_task = task();
10404        assert!(!plain_task.solo);
10405        apply_task_implementers(&mut plain_cfg, &plain_task);
10406        assert_eq!(
10407            plain_cfg.graph.implementers, 3,
10408            "a task that did not ask to run alone keeps the config's candidates"
10409        );
10410    }
10411
10412    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
10413        QuotaLoss {
10414            cause: crate::agent::QuotaCause::UsageLimit,
10415            agent: String::new(),
10416            seat: seat.into(),
10417            node: "judge".into(),
10418            at: at.parse().unwrap(),
10419            reset: reset.map(str::to_string),
10420        }
10421    }
10422
10423    #[test]
10424    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
10425        let now = Timestamp::now();
10426        for reset in [None, Some("in 1h")] {
10427            let auth = crate::agent::Quota {
10428                cause: crate::agent::QuotaCause::Authentication,
10429                agent: "alpha".into(),
10430                reset: reset.map(str::to_owned),
10431            };
10432            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
10433            assert_eq!(cooldown_until(&[loss], now), None);
10434        }
10435    }
10436
10437    #[test]
10438    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
10439        let old: Vec<QuotaLoss> = (1..=4)
10440            .map(|i| {
10441                loss(
10442                    &format!("judge-{i}"),
10443                    "2026-09-23T05:23:00Z",
10444                    Some("2:40pm (Asia/Tokyo)"),
10445                )
10446            })
10447            .collect();
10448        let fresh = losses_this_attempt(&old, &old);
10449        assert!(fresh.is_empty());
10450        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
10451        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
10452    }
10453
10454    #[test]
10455    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
10456        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
10457        let now = Timestamp::now();
10458        let mut after = old.clone();
10459        after.push(loss("judge-2", &now.to_string(), None));
10460        let fresh = losses_this_attempt(&old, &after);
10461        assert_eq!(fresh, vec![after[1].clone()]);
10462        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
10463        assert_eq!(
10464            until,
10465            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
10466        );
10467    }
10468
10469    #[test]
10470    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
10471        // `recover_stall` removes judge-1's loss and the retry then hits quota
10472        // again: the vector is the same length, so an index diff sees nothing.
10473        let before = vec![
10474            loss("judge-1", "2026-09-23T05:23:00Z", None),
10475            loss("judge-2", "2026-09-23T05:24:00Z", None),
10476        ];
10477        let after = vec![
10478            loss("judge-2", "2026-09-23T05:24:00Z", None),
10479            loss("judge-1", "2026-09-24T01:00:00Z", None),
10480        ];
10481        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
10482    }
10483
10484    #[test]
10485    fn merge_overrides_are_parsed_or_refused() {
10486        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
10487        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
10488        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
10489        assert!(merge_mode("squash").is_err());
10490    }
10491
10492    #[test]
10493    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
10494        let now = Timestamp::now();
10495        let fallback = Duration::from_secs(300);
10496        let cap = Duration::from_secs(1800);
10497
10498        // No reset hint at all: the fallback.
10499        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
10500
10501        // A reset ten minutes out, well inside the cap: waited for exactly.
10502        let soon = now + jiff::SignedDuration::from_secs(600);
10503        assert_eq!(
10504            quota_wait(Some(soon), now, fallback, cap),
10505            Duration::from_secs(600)
10506        );
10507
10508        // A reset already in the past is not trusted: the fallback, not a
10509        // zero or negative wait that would spin the loop right back around.
10510        let past = now - jiff::SignedDuration::from_secs(60);
10511        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
10512
10513        // A reset further out than the cap is trusted for direction but not
10514        // for magnitude: a parsing slip must not sleep the loop for a day.
10515        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
10516        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
10517    }
10518
10519    #[test]
10520    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
10521        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10522
10523        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
10524        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
10525
10526        // Same clock reading, but it has already gone by today: read as
10527        // tomorrow's, since the CLI would not still be reporting a limit past
10528        // its own stated reset.
10529        let already_past =
10530            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
10531        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
10532
10533        assert!(
10534            parse_reset_hint("session limit reached", now, now).is_none(),
10535            "free text with no recognised shape is not guessed at"
10536        );
10537        assert!(
10538            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
10539            "an unresolvable zone name is not guessed at either"
10540        );
10541    }
10542
10543    #[test]
10544    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
10545        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10546
10547        let at = parse_reset_hint(
10548            "You've hit your usage limit. Visit \
10549             https://chatgpt.com/codex/settings/usage to purchase more \
10550             credits or try again at Sep 19th, 2026 5:10 PM.",
10551            now,
10552            now,
10553        )
10554        .expect("the codex reset wording is a recognised shape");
10555        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
10556
10557        // The month is explicit, so a date already earlier in the same
10558        // sentence-implied year than `now` is trusted as written rather than
10559        // rolled forward a year the way the bracketed shape rolls a
10560        // same-day clock reading to tomorrow.
10561        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
10562            .expect("an explicit year needs no rollover");
10563        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
10564
10565        assert!(
10566            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
10567            "a two-digit year is not the documented shape and is not guessed at"
10568        );
10569        assert!(
10570            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
10571            "a four-letter month name is not the documented three-letter abbreviation"
10572        );
10573        assert!(
10574            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
10575            "an explicit zone on the dated shape is a format nobody has \
10576             documented, and is refused rather than guessed at as UTC"
10577        );
10578    }
10579
10580    #[test]
10581    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
10582        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
10583        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
10584
10585        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
10586        assert_eq!(at.as_second() - recorded.as_second(), 3769);
10587
10588        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
10589        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
10590
10591        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
10592            assert!(
10593                parse_reset_hint(bad, now, recorded).is_none(),
10594                "{bad:?} must not be guessed at"
10595            );
10596        }
10597    }
10598
10599    /// A loop whose queue lives in a temp tree and whose poll interval is far
10600    /// longer than the test's patience, so anything that waits out a poll
10601    /// instead of noticing the stop fails rather than merely being slow.
10602    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
10603        let config = dir.join("magi.toml");
10604        std::fs::write(
10605            &config,
10606            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
10607        )
10608        .unwrap();
10609        let opts = Opts {
10610            poll: Duration::from_secs(30),
10611            config: Some(config),
10612            // The explicit fixture config keeps startup cleanup from reading
10613            // machine configuration. This fictional repository likewise
10614            // keeps any best-effort git cleanup away from this checkout.
10615            repo: dir.join("repo"),
10616            ..Opts::default()
10617        };
10618        // The status file goes in a directory that does not exist yet, so its
10619        // creation is itself evidence the loop published one. `worktrees`
10620        // must be just as fictional: the janitor reclaims worktrees under it
10621        // for real, and a test that let it fall through to
10622        // `crate::run::default_worktree_root()` would have it reclaim
10623        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
10624        // which is exactly what happened before this function took the
10625        // parameter at all.
10626        let home = dir.join("home");
10627        // These control-only fixtures do not launch native workers. Give the
10628        // independently tested maintenance services a fresh cadence receipt.
10629        let stamps = home.join("service-ticks");
10630        std::fs::create_dir_all(&stamps).unwrap();
10631        for service in ["waiter", "deputies", "release-watch"] {
10632            std::fs::write(
10633                stamps.join(service),
10634                Timestamp::now().as_second().to_string(),
10635            )
10636            .unwrap();
10637        }
10638        for operation in [
10639            "conductor",
10640            "maintenance",
10641            "housekeeping",
10642            "disk-pressure",
10643            "cache",
10644            "fetch",
10645        ] {
10646            std::fs::write(
10647                stamps.join(format!("daemon-{operation}")),
10648                serde_json::to_vec(&Timestamp::now()).unwrap(),
10649            )
10650            .unwrap();
10651        }
10652        let worktrees = dir.join("wt");
10653        (
10654            opts,
10655            Queue::at(dir.join("queue")),
10656            home.join("daemon.json"),
10657            home,
10658            worktrees,
10659        )
10660    }
10661
10662    #[tokio::test]
10663    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
10664        let dir = tempfile::tempdir().unwrap();
10665        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10666        let mut waiting = task();
10667        waiting.repo = opts.repo.clone();
10668        waiting.hold_machine(crate::disk::gate(1, 100));
10669        waiting.mark_disk_capacity();
10670        waiting.attempts = 2;
10671        queue.put(&mut waiting).unwrap();
10672        let mut busy = task();
10673        busy.status = TaskStatus::Running;
10674        queue.put(&mut busy).unwrap();
10675        let payload = serde_json::to_value(ServiceWorker {
10676            opts,
10677            queue: queue.root().to_owned(),
10678            worktrees_root: worktrees,
10679            operation: "maintenance".into(),
10680        })
10681        .unwrap();
10682        run_service_worker(&home, payload.clone()).await.unwrap();
10683        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
10684        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
10685        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
10686        run_service_worker(&home, payload).await.unwrap();
10687        assert!(
10688            crate::worker::active(&home).unwrap().is_empty(),
10689            "monitoring only queues; normal dispatch owns launches"
10690        );
10691        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
10692    }
10693
10694    #[tokio::test]
10695    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
10696        let dir = tempfile::tempdir().unwrap();
10697        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10698        let cfg = Config::default();
10699        start_service(
10700            &home,
10701            &opts,
10702            &queue,
10703            &worktrees,
10704            "housekeeping",
10705            Some(&cfg),
10706            true,
10707        )
10708        .await
10709        .unwrap();
10710        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
10711        let read = |path: &Path| -> serde_json::Value {
10712            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
10713        };
10714        assert_eq!(read(&receipt)["detail"], "cadence not due");
10715        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
10716        start_service(
10717            &home,
10718            &opts,
10719            &queue,
10720            &worktrees,
10721            "housekeeping",
10722            Some(&cfg),
10723            true,
10724        )
10725        .await
10726        .unwrap();
10727        assert_eq!(
10728            read(&receipt)["detail"],
10729            "active work or runnable task queue"
10730        );
10731        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
10732        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
10733        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
10734        start_service(
10735            &home,
10736            &opts,
10737            &queue,
10738            &worktrees,
10739            "disk-pressure",
10740            Some(&cfg),
10741            false,
10742        )
10743        .await
10744        .unwrap();
10745        assert_eq!(
10746            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
10747            "no active work; idle housekeeping owns scan"
10748        );
10749        assert!(crate::worker::active(&home).unwrap().is_empty());
10750    }
10751
10752    #[test]
10753    fn a_stop_is_idempotent_and_once_set_stays_set() {
10754        let stop = Stop::new();
10755        assert!(!stop.stopped());
10756
10757        stop.stop();
10758        assert!(stop.stopped());
10759        stop.stop();
10760        assert!(stop.stopped(), "a second stop is not a toggle");
10761
10762        let shared = stop.clone();
10763        assert!(
10764            shared.stopped(),
10765            "a clone is the same stop; that is how the loop and its caller share one"
10766        );
10767    }
10768
10769    #[tokio::test]
10770    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10771        for operation in ["conductor", "maintenance", "housekeeping"] {
10772            let dir = tempfile::tempdir().unwrap();
10773            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10774            opts.once = true;
10775            opts.poll = Duration::from_millis(1);
10776            let mut task = task();
10777            task.runs.push("fixture-run".into());
10778            queue.put(&mut task).unwrap();
10779            let claim = queue.claim(&task.id).unwrap();
10780
10781            // Model a live service holding the task's claim across the
10782            // scheduler's dispatch scan. No real subprocess or timed race.
10783            let directory = home.join("workers/jobs/abcdef");
10784            std::fs::create_dir_all(&directory).unwrap();
10785            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10786            crate::pr_head::try_lock_file(&lease).unwrap();
10787            let mut job = crate::worker::Job {
10788                id: "abcdef".into(),
10789                sequence: 1,
10790                kind: "daemon-service".into(),
10791                key: format!("service:daemon-{operation}"),
10792                payload: serde_json::Value::Null,
10793                generation: "fixture".into(),
10794                version: None,
10795                status: crate::worker::Status::Running,
10796                result: None,
10797                pid: Some(std::process::id()),
10798                created_at: Timestamp::now().as_second() as u64,
10799                finished_at: None,
10800            };
10801            let record = directory.join("job.json");
10802            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10803
10804            let status = Arc::new(Mutex::new(Status::new()));
10805            let stop = Stop::new();
10806            let mut drain = Box::pin(poll(
10807                &opts,
10808                &queue,
10809                &status,
10810                &home,
10811                &worktrees,
10812                &stop,
10813                DispatchLimits {
10814                    max_concurrent: 1,
10815                    pause_for_interrupts: false,
10816                    recovery_cfg: None,
10817                },
10818            ));
10819            std::future::poll_fn(|cx| {
10820                use std::future::Future;
10821                assert!(
10822                    drain.as_mut().poll(cx).is_pending(),
10823                    "--once must wait for {operation} to release its queue claim"
10824                );
10825                std::task::Poll::Ready(())
10826            })
10827            .await;
10828            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10829
10830            // An answer arrives while the service still owns the claim. A
10831            // fresh scheduling pass must apply it before declaring idle.
10832            let questions = Questions::at(home.join("questions"));
10833            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10834            questions.put(&mut q).unwrap();
10835            drop(claim);
10836            // Model services that took longer than their cadence, without a
10837            // wall-clock sleep. The final scans must not respawn them even
10838            // though their receipts now permit another periodic invocation.
10839            let expired =
10840                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10841            for service in [operation, "housekeeping"] {
10842                std::fs::write(
10843                    home.join("service-ticks").join(format!("daemon-{service}")),
10844                    &expired,
10845                )
10846                .unwrap();
10847            }
10848            job.status = crate::worker::Status::Finished;
10849            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10850            drop(lease);
10851            tokio::time::timeout(Duration::from_secs(2), drain)
10852                .await
10853                .expect("the settled service must allow the drain to finish")
10854                .unwrap();
10855            let after = queue.get(&task.id).unwrap();
10856            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10857            assert!(after.action_applied(&q.id));
10858            for service in [operation, "housekeeping"] {
10859                assert_eq!(
10860                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10861                        .unwrap(),
10862                    expired,
10863                    "the final once rescan must not restart {service}"
10864                );
10865            }
10866        }
10867    }
10868
10869    #[test]
10870    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10871        let stop = Stop::new();
10872        stop.busy.store(1, Ordering::SeqCst);
10873        assert!(
10874            !stop.finishing(),
10875            "a busy loop nobody has asked to stop is just running"
10876        );
10877
10878        stop.stop();
10879        assert!(
10880            stop.finishing(),
10881            "a stop asked for mid-run has not landed until the run is settled"
10882        );
10883
10884        stop.busy.store(0, Ordering::SeqCst);
10885        assert!(
10886            !stop.finishing(),
10887            "once the run is settled the stop has landed and there is nothing to finish"
10888        );
10889    }
10890
10891    #[test]
10892    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10893        let stop = Stop::new();
10894        stop.busy.store(2, Ordering::SeqCst);
10895        stop.stop();
10896        assert!(stop.finishing(), "two runs still in flight");
10897
10898        stop.busy.store(1, Ordering::SeqCst);
10899        assert!(
10900            stop.finishing(),
10901            "one run finished, but a sibling is still working"
10902        );
10903
10904        stop.busy.store(0, Ordering::SeqCst);
10905        assert!(
10906            !stop.finishing(),
10907            "the last run out is what actually lands the stop"
10908        );
10909    }
10910
10911    #[tokio::test]
10912    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10913        let dir = tempfile::tempdir().unwrap();
10914        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10915        let stop = Stop::new();
10916        stop.stop();
10917
10918        let began = std::time::Instant::now();
10919        tokio::time::timeout(
10920            Duration::from_secs(2),
10921            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10922        )
10923        .await
10924        .expect("a stopped loop must return, not sit out its poll interval")
10925        .expect("the loop's own setup and teardown must not fail");
10926        assert!(
10927            began.elapsed() < opts.poll,
10928            "returned only after {:?}, which is a poll interval, not a stop",
10929            began.elapsed()
10930        );
10931    }
10932
10933    #[tokio::test]
10934    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10935        let dir = tempfile::tempdir().unwrap();
10936        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10937        let stop = Stop::new();
10938
10939        // Asked for after the loop is already parked on its empty queue, which
10940        // is the case an operator tapping stop on a phone actually hits.
10941        let asker = {
10942            let stop = stop.clone();
10943            tokio::spawn(async move {
10944                tokio::time::sleep(Duration::from_millis(20)).await;
10945                stop.stop();
10946            })
10947        };
10948
10949        let began = std::time::Instant::now();
10950        tokio::time::timeout(
10951            Duration::from_secs(2),
10952            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10953        )
10954        .await
10955        .expect("a stop asked for while idle must wake the wait")
10956        .expect("the loop's own setup and teardown must not fail");
10957        asker.await.unwrap();
10958        assert!(
10959            began.elapsed() < opts.poll,
10960            "returned only after {:?}, so the stop waited on the sleep",
10961            began.elapsed()
10962        );
10963    }
10964
10965    #[tokio::test]
10966    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10967        let dir = tempfile::tempdir().unwrap();
10968        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10969        let stop = Stop::new();
10970        stop.stop();
10971
10972        tokio::time::timeout(
10973            Duration::from_secs(2),
10974            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10975        )
10976        .await
10977        .expect("a stopped loop must return")
10978        .expect("the loop's own setup and teardown must not fail");
10979
10980        assert!(
10981            home.is_dir(),
10982            "the loop did publish a status file, so its removal is the teardown and not an absence"
10983        );
10984        assert!(
10985            !status_file.exists(),
10986            "a stopped loop clears its status file"
10987        );
10988        assert!(
10989            read_status(&home).is_none(),
10990            "a reader must see no daemon at all, not a heartbeat that merely stopped"
10991        );
10992    }
10993
10994    #[tokio::test]
10995    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10996        let dir = tempfile::tempdir().unwrap();
10997        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10998
10999        let mut settled = RunState::new(
11000            dir.path().join("repo"),
11001            "main".to_owned(),
11002            "abc1234".to_owned(),
11003            "fixture".to_owned(),
11004            Config::default(),
11005        );
11006        settled.status = RunStatus::Ready;
11007        let run_dir = home.join("runs").join(&settled.id);
11008        std::fs::create_dir_all(&run_dir).unwrap();
11009        std::fs::write(
11010            run_dir.join("run.json"),
11011            serde_json::to_string_pretty(&settled).unwrap(),
11012        )
11013        .unwrap();
11014        let questions = Questions::at(home.join("questions"));
11015        let mut question = ask::Question::new(
11016            settled.id.clone(),
11017            "review".to_owned(),
11018            "reviewer-1".to_owned(),
11019            "Continue?".to_owned(),
11020            String::new(),
11021            Vec::new(),
11022        );
11023        questions.put(&mut question).unwrap();
11024
11025        run_service_worker(
11026            &home,
11027            serde_json::to_value(ServiceWorker {
11028                opts,
11029                queue: queue.root().to_path_buf(),
11030                worktrees_root: worktrees,
11031                operation: "housekeeping".to_owned(),
11032            })
11033            .unwrap(),
11034        )
11035        .await
11036        .unwrap();
11037
11038        assert_eq!(
11039            questions.get(&question.id).unwrap().status,
11040            ask::QuestionStatus::Abandoned,
11041            "the independent housekeeping worker settles ended-run questions"
11042        );
11043    }
11044
11045    #[test]
11046    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
11047        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11048
11049        assert!(
11050            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
11051            "never checked before: due at once"
11052        );
11053
11054        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
11055        assert!(
11056            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
11057            "well inside the interval: not due yet"
11058        );
11059
11060        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
11061        assert!(
11062            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
11063            "exactly at the edge: not yet due, same convention as `clean::due`"
11064        );
11065
11066        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11067        assert!(
11068            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
11069            "past the interval: due again"
11070        );
11071    }
11072
11073    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
11074    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
11075    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
11076    /// and the congestion test below both need, and must not drift apart.
11077    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
11078        let config = dir.join("magi.toml");
11079        // A literal (single-quoted) TOML string, not a basic one: the cache
11080        // path is a Windows path full of backslashes, and a basic string
11081        // would have TOML try to interpret `\U` (from `\Users\...`) as a
11082        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
11083        // `{{ vars.cache }}` rendering documents.
11084        std::fs::write(
11085            &config,
11086            format!(
11087                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
11088                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
11089                cache_dir.display()
11090            ),
11091        )
11092        .unwrap();
11093        Opts {
11094            config: Some(config),
11095            repo: dir.join("repo"),
11096            ..Opts::default()
11097        }
11098    }
11099
11100    #[tokio::test]
11101    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
11102        let dir = tempfile::tempdir().unwrap();
11103        let home = dir.path().join("home");
11104        let cache_dir = dir.path().join("cache");
11105        std::fs::create_dir_all(&cache_dir).unwrap();
11106        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11107        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11108
11109        // Nobody has asked this daemon to stop, which is the ordinary case;
11110        // the skip that a stop buys is asserted by its own test below.
11111        let running = Stop::new();
11112        let mut last_checked = None;
11113        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11114        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
11115            .await;
11116        assert_eq!(
11117            crate::disk::dir_size(&cache_dir),
11118            0,
11119            "over the cap on the first check ever: pruned at once, no idle queue required"
11120        );
11121        assert_eq!(last_checked, Some(t0));
11122
11123        // A fresh oversized file lands, but the next check is not due yet.
11124        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
11125        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
11126        maybe_prune_cache_between_runs(
11127            &opts.repo,
11128            &opts,
11129            &home,
11130            &running,
11131            &mut last_checked,
11132            too_soon,
11133        )
11134        .await;
11135        assert_eq!(
11136            crate::disk::dir_size(&cache_dir),
11137            10,
11138            "too soon since the last check: left alone rather than rescanned every call"
11139        );
11140        assert_eq!(
11141            last_checked,
11142            Some(t0),
11143            "an idle check does not reset the clock"
11144        );
11145
11146        // Once the interval elapses, the same oversized cache is caught again.
11147        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11148        maybe_prune_cache_between_runs(
11149            &opts.repo,
11150            &opts,
11151            &home,
11152            &running,
11153            &mut last_checked,
11154            due_again,
11155        )
11156        .await;
11157        assert_eq!(
11158            crate::disk::dir_size(&cache_dir),
11159            0,
11160            "due again: pruned back under the cap"
11161        );
11162    }
11163
11164    /// A stop must not queue behind housekeeping. The prune below is a
11165    /// synchronous walk of the whole cache with no await point in it, so a
11166    /// loop that entered it could not get back to its own `stopped()` test
11167    /// until the walk finished - and because no run is in flight at this
11168    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
11169    /// the stop had already landed. The idle branch has always made this same
11170    /// check before reaching `janitor`; the between-runs path makes it too.
11171    #[tokio::test]
11172    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
11173        let dir = tempfile::tempdir().unwrap();
11174        let home = dir.path().join("home");
11175        let cache_dir = dir.path().join("cache");
11176        std::fs::create_dir_all(&cache_dir).unwrap();
11177        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11178        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11179
11180        let stop = Stop::new();
11181        stop.stop();
11182        assert!(
11183            !stop.finishing(),
11184            "no run is in flight at a between-runs boundary, so nothing else \
11185             would tell the operator this stop had not taken effect yet"
11186        );
11187
11188        let mut last_checked = None;
11189        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11190        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
11191            .await;
11192        assert_eq!(
11193            crate::disk::dir_size(&cache_dir),
11194            10,
11195            "over its cap, and due for the first check ever, but a stop outranks \
11196             it: the cap is a standing policy the next start measures again"
11197        );
11198        assert_eq!(
11199            last_checked, None,
11200            "a check that never happened must not claim the interval"
11201        );
11202    }
11203
11204    /// A backlog must not starve cache pruning. The finite cache worker runs
11205    /// independently of queue drain and must not consume any task attempts.
11206    #[tokio::test]
11207    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
11208        let dir = tempfile::tempdir().unwrap();
11209        let cache_dir = dir.path().join("cache");
11210        std::fs::create_dir_all(&cache_dir).unwrap();
11211        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
11212
11213        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
11214        opts.poll = Duration::from_millis(20);
11215        opts.max_attempts = 1_000;
11216
11217        let queue = Queue::at(dir.path().join("queue"));
11218        for i in 0..128 {
11219            let mut task = Task::new(
11220                format!("queued work {i}"),
11221                format!("queued work {i}"),
11222                opts.repo.clone(),
11223                Source::Human,
11224            );
11225            queue.put(&mut task).unwrap();
11226        }
11227
11228        let home = dir.path().join("home");
11229        let worktrees = dir.path().join("wt");
11230        run_service_worker(
11231            &home,
11232            serde_json::to_value(ServiceWorker {
11233                opts,
11234                queue: queue.root().to_path_buf(),
11235                worktrees_root: worktrees,
11236                operation: "cache".to_owned(),
11237            })
11238            .unwrap(),
11239        )
11240        .await
11241        .unwrap();
11242        let after = queue.list();
11243        assert_eq!(after.len(), 128);
11244        assert!(
11245            after
11246                .iter()
11247                .all(|task| task.status.runnable() && task.attempts == 0)
11248        );
11249
11250        assert_eq!(
11251            crate::disk::dir_size(&cache_dir),
11252            0,
11253            "an oversized cache must not be left to grow unboundedly just because the \
11254             queue kept the loop busy the whole time"
11255        );
11256    }
11257
11258    #[test]
11259    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
11260        let dir = tempfile::tempdir().unwrap();
11261        let queue = Queue::at(dir.path().join("queue"));
11262        let questions = Questions::at(dir.path().join("questions"));
11263        let mut task = task();
11264        queue.put(&mut task).unwrap();
11265
11266        let mut task_question = ask::Question::new(
11267            task.id.clone(),
11268            crate::conduct::NODE.to_owned(),
11269            "conduct".to_owned(),
11270            "Which backend?".to_owned(),
11271            String::new(),
11272            Vec::new(),
11273        );
11274        questions.put(&mut task_question).unwrap();
11275        task.block(vec![task_question.id.clone()], None);
11276        queue.put(&mut task).unwrap();
11277
11278        let mut run_question = ask::Question::new(
11279            "20260101-000000-run1".to_owned(),
11280            "review".to_owned(),
11281            "reviewer-1".to_owned(),
11282            "Run question".to_owned(),
11283            String::new(),
11284            Vec::new(),
11285        );
11286        questions.put(&mut run_question).unwrap();
11287
11288        // A question from another node whose `run` happens to equal this
11289        // task's id — the same field, filled in for an unrelated reason. Only
11290        // `crate::conduct::NODE` questions use `run` as a task id; this one
11291        // must never be touched by this reconciliation, even after release.
11292        let mut coincidental = ask::Question::new(
11293            task.id.clone(),
11294            "review".to_owned(),
11295            "reviewer-1".to_owned(),
11296            "Unrelated review question".to_owned(),
11297            String::new(),
11298            Vec::new(),
11299        );
11300        questions.put(&mut coincidental).unwrap();
11301
11302        reconcile_task_questions(&queue, &questions);
11303        assert!(questions.get(&task_question.id).unwrap().status.open());
11304        assert!(questions.get(&run_question.id).unwrap().status.open());
11305        assert!(questions.get(&coincidental.id).unwrap().status.open());
11306
11307        task.release();
11308        queue.put(&mut task).unwrap();
11309        reconcile_task_questions(&queue, &questions);
11310        assert_eq!(
11311            questions.get(&task_question.id).unwrap().status,
11312            ask::QuestionStatus::Abandoned
11313        );
11314        assert!(
11315            questions.get(&run_question.id).unwrap().status.open(),
11316            "run questions remain the run janitor's responsibility"
11317        );
11318        assert!(
11319            questions.get(&coincidental.id).unwrap().status.open(),
11320            "a non-conductor question must not be abandoned just because its \
11321             run id coincides with a task id"
11322        );
11323    }
11324
11325    #[test]
11326    fn a_freshly_started_running_task_is_never_stalled() {
11327        let dir = tempfile::tempdir().unwrap();
11328        let mut t = task();
11329        t.start("run-1".to_owned());
11330        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
11331        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
11332        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
11333    }
11334
11335    #[test]
11336    fn a_long_running_task_with_no_live_daemon_is_stalled() {
11337        let dir = tempfile::tempdir().unwrap();
11338        let mut t = task();
11339        t.start("run-1".to_owned());
11340        t.updated_at = Timestamp::now()
11341            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
11342        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
11343        assert_eq!(
11344            stalled_tasks(
11345                &Queue::at(dir.path().join("q")),
11346                dir.path(),
11347                Timestamp::now()
11348            )
11349            .len(),
11350            0,
11351            "the task was never written to this queue"
11352        );
11353    }
11354
11355    #[test]
11356    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
11357        let dir = tempfile::tempdir().unwrap();
11358        let mut t = task();
11359        t.id = "20260903-080340-0167".to_owned();
11360        t.start("20260903-080619-01c2".to_owned());
11361        t.updated_at = Timestamp::now()
11362            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
11363
11364        let mut status = Status::new();
11365        status.current = vec![Current {
11366            worker: None,
11367            task: t.id.clone(),
11368            run: "20260903-080619-01c2".to_owned(),
11369        }];
11370        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11371
11372        assert!(
11373            !is_stalled(&t, dir.path(), Timestamp::now()),
11374            "a live daemon's own heartbeat rules out stalled, however long the task has run"
11375        );
11376    }
11377
11378    /// Rewrite a task's `updated_at` on disk directly, bypassing
11379    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
11380    /// a fixture look like it has genuinely been `running` for a while.
11381    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
11382        let path = queue.path_of(id);
11383        let body = std::fs::read_to_string(&path).unwrap();
11384        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
11385        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
11386        v["updated_at"] = serde_json::Value::String(old.to_string());
11387        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
11388    }
11389
11390    #[test]
11391    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
11392        // The realistic `poll()` ordering, not `is_stalled` in isolation:
11393        // `reclaim_orphaned_running` runs first, on every poll, and settles
11394        // any `running` task whose claim it can actually take. For most
11395        // crashes that is immediate - a dead pid is proof enough for
11396        // `sweep_stale_claims` to drop the lock the same tick, and the very
11397        // next claim attempt succeeds. But a lock whose pid cannot be parsed
11398        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
11399        // `sweep_stale_claims`'s own doc), so the lock - and the claim
11400        // failure behind it - can legitimately outlive many polls. This is
11401        // exactly the gap `stalled_tasks` exists to surface well before that
11402        // six-hour sweep would: reclaim leaves the task `running`, and it
11403        // must still reach the conductor as stalled.
11404        let dir = tempfile::tempdir().unwrap();
11405        let queue = Queue::at(dir.path().join("queue"));
11406        let home = dir.path().join("home");
11407
11408        let mut t = task();
11409        t.id = "20260101-000001-lock".to_owned();
11410        t.start("run-1".to_owned());
11411        queue.put(&mut t).unwrap();
11412        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
11413        std::fs::write(
11414            dir.path().join("queue").join(format!("{}.lock", t.id)),
11415            "not a pid",
11416        )
11417        .unwrap();
11418
11419        let now = Timestamp::now();
11420        assert!(
11421            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
11422            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
11423             and reclaim must leave the task alone"
11424        );
11425        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
11426
11427        let stalled = stalled_tasks(&queue, &home, now);
11428        assert_eq!(
11429            stalled.len(),
11430            1,
11431            "reclaim's inability to claim it yet must not hide it from the conductor"
11432        );
11433        assert_eq!(stalled[0].id, t.id);
11434    }
11435
11436    #[test]
11437    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
11438        let dir = tempfile::tempdir().unwrap();
11439        crate::run::set_home(dir.path().join("run-home"));
11440        let queue = Queue::at(dir.path().join("queue"));
11441        let home = dir.path().join("home");
11442        let questions = Questions::at(dir.path().join("questions"));
11443
11444        let mut t = task();
11445        t.id = "20260101-000003-dead".to_owned();
11446        t.start("missing-run".to_owned());
11447        queue.put(&mut t).unwrap();
11448        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
11449
11450        // This is the real poll ordering: retain the deterministic stalled
11451        // input before a claim proves the owner is gone and reclaims it.
11452        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11453        assert_eq!(
11454            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
11455            [&t.id]
11456        );
11457        assert_eq!(
11458            reclaim_orphaned_running(&queue, 2, &Default::default()),
11459            [t.id.clone()]
11460        );
11461        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
11462
11463        // Reclaim drops its guard before conductor decisions are applied, so
11464        // the decision for the captured stalled input has a real write path.
11465        crate::conduct::apply(
11466            &queue,
11467            &questions,
11468            &crate::conduct::Verdict {
11469                decisions: vec![crate::conduct::Decision {
11470                    id: t.id.clone(),
11471                    recovery: Some(crate::conduct::Recovery::Requeue),
11472                    ..crate::conduct::Decision::default()
11473                }],
11474            },
11475        )
11476        .unwrap();
11477        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
11478    }
11479
11480    #[test]
11481    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
11482        let dir = tempfile::tempdir().unwrap();
11483        let queue = Queue::at(dir.path().join("queue"));
11484        let home = dir.path().join("home");
11485
11486        let mut fresh = task();
11487        fresh.id = "20260101-000001-aaaa".to_owned();
11488        fresh.start("run-1".to_owned());
11489        queue.put(&mut fresh).unwrap();
11490
11491        let mut old = task();
11492        old.id = "20260101-000002-bbbb".to_owned();
11493        old.start("run-2".to_owned());
11494        queue.put(&mut old).unwrap();
11495        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
11496
11497        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
11498        assert_eq!(stalled.len(), 1);
11499        assert_eq!(stalled[0].id, old.id);
11500    }
11501
11502    #[test]
11503    fn queued_and_finished_task_views_partition_by_status() {
11504        let dir = tempfile::tempdir().unwrap();
11505        let queue = Queue::at(dir.path().join("queue"));
11506
11507        let mut queued = task();
11508        queued.id = "20260101-000001-aaaa".to_owned();
11509        queue.put(&mut queued).unwrap();
11510
11511        let mut failed = task();
11512        failed.id = "20260101-000002-bbbb".to_owned();
11513        failed.start("run-1".to_owned());
11514        failed.fail("gate red", 5);
11515        queue.put(&mut failed).unwrap();
11516
11517        let mut held = task();
11518        held.id = "20260101-000003-cccc".to_owned();
11519        held.hold_machine(None);
11520        queue.put(&mut held).unwrap();
11521
11522        let mut running = task();
11523        running.id = "20260101-000004-dddd".to_owned();
11524        running.start("run-2".to_owned());
11525        queue.put(&mut running).unwrap();
11526
11527        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
11528        assert_eq!(queued_ids, [queued.id.clone()]);
11529
11530        let mut finished_ids: Vec<String> =
11531            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
11532        finished_ids.sort_unstable();
11533        let mut want = vec![failed.id.clone(), held.id.clone()];
11534        want.sort_unstable();
11535        assert_eq!(finished_ids, want);
11536    }
11537
11538    #[test]
11539    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
11540        for short in [false, true] {
11541            let dir = tempfile::tempdir().unwrap();
11542            let queue = Queue::at(dir.path().join("queue"));
11543            let questions = ask::Questions::at(dir.path().join("questions"));
11544            let mut running = task();
11545            running.id = "20261013-192213-feb2".into();
11546            running.start("existing-run".into());
11547            queue.put(&mut running).unwrap();
11548            let mut middle = task();
11549            middle.id = "20261013-193611-ca5b".into();
11550            middle.block(
11551                vec![if short {
11552                    "feb2".into()
11553                } else {
11554                    running.id.clone()
11555                }],
11556                None,
11557            );
11558            queue.put(&mut middle).unwrap();
11559            let mut waiting = task();
11560            waiting.id = "20261013-202849-ee37".into();
11561            waiting.block(
11562                vec![if short {
11563                    "ca5b".into()
11564                } else {
11565                    middle.id.clone()
11566                }],
11567                Some("wait for implementation".into()),
11568            );
11569            queue.put(&mut waiting).unwrap();
11570            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
11571            let inv = crate::blockers::Inventory::load(&queue, &questions);
11572            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
11573            assert!(inv.stuck().is_empty());
11574            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11575            assert!(report.quarantined.is_empty());
11576            assert!(report.asked.is_empty());
11577            resolve_blockers(&queue, &questions);
11578            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11579            assert!(questions.list().is_empty());
11580            // Finishing the transitive prerequisite alone does not satisfy
11581            // the task's direct dependency.
11582            running.succeed();
11583            queue.put(&mut running).unwrap();
11584            resolve_blockers(&queue, &questions);
11585            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
11586            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11587            middle = queue.get(&middle.id).unwrap();
11588            middle.succeed();
11589            queue.put(&mut middle).unwrap();
11590            resolve_blockers(&queue, &questions);
11591            let after = queue.get(&waiting.id).unwrap();
11592            assert_eq!(after.status, TaskStatus::Queued);
11593            assert!(after.blocked_by.is_empty());
11594            assert_eq!(after.instruction, waiting.instruction);
11595        }
11596    }
11597
11598    #[test]
11599    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
11600        for future_schema in [false, true] {
11601            let name = "20261013-193611-ca5b";
11602            let mut future = task();
11603            future.id = name.into();
11604            future.schema = crate::queue::SCHEMA + 1;
11605            let contents = if future_schema {
11606                serde_json::to_string(&future).unwrap()
11607            } else {
11608                "corrupt".into()
11609            };
11610            let dir = tempfile::tempdir().unwrap();
11611            let queue = Queue::at(dir.path().join("queue"));
11612            let questions = ask::Questions::at(dir.path().join("questions"));
11613            let mut waiting = task();
11614            waiting.id = "20261013-202849-ee37".into();
11615            waiting.block(vec!["ca5b".into()], None);
11616            queue.put(&mut waiting).unwrap();
11617            std::fs::write(queue.path_of(name), contents).unwrap();
11618            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
11619            assert!(
11620                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
11621            );
11622            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11623            assert!(report.asked.is_empty());
11624            resolve_blockers(&queue, &questions);
11625            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11626            assert!(questions.list().is_empty());
11627        }
11628        let dir = tempfile::tempdir().unwrap();
11629        let queue = Queue::at(dir.path().join("queue"));
11630        let questions = ask::Questions::at(dir.path().join("questions"));
11631        let mut waiting = task();
11632        waiting.id = "20261013-202849-ee37".into();
11633        waiting.block(vec!["ca5b".into()], None);
11634        queue.put(&mut waiting).unwrap();
11635        let mut done = task();
11636        done.id = "20261013-193611-ca5b".into();
11637        done.succeed();
11638        queue.put(&mut done).unwrap();
11639        // An unreadable second match must not disappear from uniqueness
11640        // checks just because Queue::list skips it.
11641        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
11642        assert!(queue.get("ca5b").is_err());
11643        assert_eq!(
11644            crate::queue::dependency(&queue, &questions, "ca5b"),
11645            crate::queue::Dependency::Ambiguous
11646        );
11647        resolve_blockers(&queue, &questions);
11648        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
11649        assert!(report.asked.is_empty());
11650        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
11651        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
11652    }
11653
11654    #[test]
11655    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
11656        for held in [false, true] {
11657            for question in [false, true] {
11658                for reference in ["ca5b", "20261013-193611-ca5b"] {
11659                    let dir = tempfile::tempdir().unwrap();
11660                    let queue = Queue::at(dir.path().join("queue"));
11661                    let questions = ask::Questions::at(dir.path().join("questions"));
11662                    let mut prerequisite = task();
11663                    prerequisite.id = "20261013-193611-ca5b".into();
11664                    prerequisite.start("existing-run".into());
11665                    queue.put(&mut prerequisite).unwrap();
11666                    let mut waiting = task();
11667                    waiting.id = "20261013-202849-ee37".into();
11668                    if held {
11669                        waiting.hold_machine(Some("waiting for separate consent".into()));
11670                    }
11671                    queue.put(&mut waiting).unwrap();
11672                    let reason = "Deleting saved data requires separate owner consent";
11673                    crate::conduct::apply(
11674                        &queue,
11675                        &questions,
11676                        &crate::conduct::Verdict {
11677                            decisions: vec![crate::conduct::Decision {
11678                                id: waiting.id.clone(),
11679                                blocked_by: vec![reference.into()],
11680                                question: question.then(|| "May the saved data be deleted?".into()),
11681                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
11682                                reason: Some(reason.into()),
11683                                ..crate::conduct::Decision::default()
11684                            }],
11685                        },
11686                    )
11687                    .unwrap();
11688                    let before = queue.get(&waiting.id).unwrap();
11689                    if question {
11690                        assert_eq!(before.status, TaskStatus::Blocked);
11691                        let q = questions.get(&before.blocked_by[0]).unwrap();
11692                        assert_eq!(q.summary, "May the saved data be deleted?");
11693                        assert!(q.status.open());
11694                    } else {
11695                        assert_eq!(before.status, TaskStatus::Held);
11696                        let recorded_reason = before.hold_reason.as_deref().unwrap();
11697                        assert!(recorded_reason.starts_with(reason));
11698                        if held {
11699                            assert!(recorded_reason.contains("waiting for separate consent"));
11700                        }
11701                    }
11702                    prerequisite.succeed();
11703                    queue.put(&mut prerequisite).unwrap();
11704                    resolve_blockers(&queue, &questions);
11705                    let after = queue.get(&waiting.id).unwrap();
11706                    assert_eq!(after.status, before.status);
11707                    assert_eq!(after.blocked_by, before.blocked_by);
11708                    assert_eq!(after.hold_reason, before.hold_reason);
11709                    assert_eq!(after.instruction, waiting.instruction);
11710                    if question {
11711                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
11712                    }
11713                    assert!(
11714                        queue.next_runnable().is_none(),
11715                        "dependency completion is not consent"
11716                    );
11717                }
11718            }
11719        }
11720    }
11721
11722    #[test]
11723    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
11724        let dir = tempfile::tempdir().unwrap();
11725        let queue = Queue::at(dir.path().join("queue"));
11726        let questions = ask::Questions::at(dir.path().join("questions"));
11727
11728        let mut dep = task();
11729        dep.id = "20260101-000001-dep0".to_owned();
11730        dep.succeed();
11731        queue.put(&mut dep).unwrap();
11732
11733        let mut still_going = task();
11734        still_going.id = "20260101-000002-dep1".to_owned();
11735        queue.put(&mut still_going).unwrap();
11736
11737        let mut blocked = task();
11738        blocked.id = "20260101-000003-main".to_owned();
11739        blocked.block(
11740            vec![dep.id.clone(), still_going.id.clone()],
11741            Some("waits on both".to_owned()),
11742        );
11743        queue.put(&mut blocked).unwrap();
11744
11745        resolve_blockers(&queue, &questions);
11746
11747        let after = queue.get(&blocked.id).unwrap();
11748        assert_eq!(
11749            after.status,
11750            TaskStatus::Blocked,
11751            "one dependency is still outstanding"
11752        );
11753        assert_eq!(after.blocked_by, [still_going.id.clone()]);
11754    }
11755
11756    #[test]
11757    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11758        let dir = tempfile::tempdir().unwrap();
11759        let queue = Queue::at(dir.path().join("queue"));
11760        let questions = ask::Questions::at(dir.path().join("questions"));
11761
11762        let mut q = crate::ask::Question::new(
11763            "20260101-000001-main".to_owned(),
11764            crate::conduct::NODE.to_owned(),
11765            "conduct".to_owned(),
11766            "Which backend?".to_owned(),
11767            String::new(),
11768            Vec::new(),
11769        );
11770        questions.put(&mut q).unwrap();
11771        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11772            .unwrap();
11773        questions.put(&mut q).unwrap();
11774
11775        let mut blocked = task();
11776        blocked.id = "20260101-000001-main".to_owned();
11777        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11778        queue.put(&mut blocked).unwrap();
11779
11780        resolve_blockers(&queue, &questions);
11781
11782        let after = queue.get(&blocked.id).unwrap();
11783        assert_eq!(
11784            after.status,
11785            TaskStatus::Queued,
11786            "the only blocker resolved"
11787        );
11788        assert_eq!(after.answers.len(), 1);
11789        assert_eq!(after.answers[0].question, "Which backend?");
11790        assert_eq!(after.answers[0].answer, "SQLite");
11791
11792        // And the run this task starts next is told about it.
11793        let instruction = instruction_for(&after);
11794        assert!(instruction.contains("Which backend?"));
11795        assert!(instruction.contains("SQLite"));
11796    }
11797
11798    #[test]
11799    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11800        let dir = tempfile::tempdir().unwrap();
11801        let queue = Queue::at(dir.path().join("queue"));
11802        let questions = ask::Questions::at(dir.path().join("questions"));
11803
11804        let mut q = crate::ask::Question::new(
11805            "20260101-000001-main".to_owned(),
11806            crate::conduct::NODE.to_owned(),
11807            "conduct".to_owned(),
11808            "Is the setup done?".to_owned(),
11809            String::new(),
11810            Vec::new(),
11811        );
11812        q.abandon("no answer within 60s of asking");
11813        questions.put(&mut q).unwrap();
11814
11815        let mut blocked = task();
11816        blocked.id = "20260101-000001-main".to_owned();
11817        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11818        queue.put(&mut blocked).unwrap();
11819
11820        resolve_blockers(&queue, &questions);
11821
11822        let after = queue.get(&blocked.id).unwrap();
11823        assert_eq!(
11824            after.status,
11825            TaskStatus::Held,
11826            "never left blocked on nothing"
11827        );
11828        assert!(!after.operator_held(), "a machine hold, for triage");
11829        assert!(
11830            after
11831                .hold_reason
11832                .as_deref()
11833                .unwrap_or_default()
11834                .contains("went unanswered")
11835        );
11836    }
11837
11838    #[test]
11839    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11840        // Reproduces the reported bug (task 3958): a task held out of
11841        // attempts, blocked on a `crate::conduct` follow-up question, must
11842        // come back `held` once that question is answered - never `queued`,
11843        // whatever the answer said - or it silently re-enters the
11844        // competition queue with its attempts already exhausted.
11845        let dir = tempfile::tempdir().unwrap();
11846        let queue = Queue::at(dir.path().join("queue"));
11847        let questions = ask::Questions::at(dir.path().join("questions"));
11848
11849        let mut q = crate::ask::Question::new(
11850            "20260101-000001-main".to_owned(),
11851            crate::conduct::NODE.to_owned(),
11852            "conduct".to_owned(),
11853            "How should this be handled?".to_owned(),
11854            String::new(),
11855            Vec::new(),
11856        );
11857        questions.put(&mut q).unwrap();
11858        q.answer(crate::ask::Answer::Text(
11859            "leave it held, a human will look at it later".to_owned(),
11860        ))
11861        .unwrap();
11862        questions.put(&mut q).unwrap();
11863
11864        let mut held = task();
11865        held.id = "20260101-000001-main".to_owned();
11866        held.hold_machine(Some("out of attempts".to_owned()));
11867        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11868        queue.put(&mut held).unwrap();
11869
11870        resolve_blockers(&queue, &questions);
11871
11872        let after = queue.get(&held.id).unwrap();
11873        assert_eq!(after.status, TaskStatus::Held);
11874        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11875        assert_eq!(
11876            after.answers[0].answer,
11877            "leave it held, a human will look at it later"
11878        );
11879    }
11880
11881    #[test]
11882    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11883        let dir = tempfile::tempdir().unwrap();
11884        let queue = Queue::at(dir.path().join("queue"));
11885        let questions = ask::Questions::at(dir.path().join("questions"));
11886        let mut dep = task();
11887        dep.id = "20260101-000001-gone".to_owned();
11888        queue.put(&mut dep).unwrap();
11889        let mut blocked = task();
11890        blocked.id = "20260101-000003-main".to_owned();
11891        blocked.block(vec![dep.id.clone()], None);
11892        queue.put(&mut blocked).unwrap();
11893
11894        // Claimed, so `remove` cannot rewrite it and the resolver must.
11895        let claim = queue.claim(&blocked.id).unwrap();
11896        queue.remove(&dep.id, false, &questions).unwrap();
11897        drop(claim);
11898        resolve_blockers(&queue, &questions);
11899
11900        let after = queue.get(&blocked.id).unwrap();
11901        assert_eq!(after.status, TaskStatus::Queued);
11902        assert!(after.blocked_by.is_empty());
11903    }
11904
11905    #[test]
11906    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11907        // Reproduces the reported bug: a task blocked on a task id that was
11908        // removed (`magi task rm`, or deleted by hand) can never see that id
11909        // reach `Done`, so the ordinary per-id loop has nothing to notice and
11910        // would otherwise leave the task `blocked` forever with no way for an
11911        // operator to find out why.
11912        let dir = tempfile::tempdir().unwrap();
11913        let queue = Queue::at(dir.path().join("queue"));
11914        let questions = ask::Questions::at(dir.path().join("questions"));
11915
11916        let mut still_going = task();
11917        still_going.id = "20260101-000002-dep1".to_owned();
11918        queue.put(&mut still_going).unwrap();
11919
11920        let mut blocked = task();
11921        blocked.id = "20260101-000003-main".to_owned();
11922        blocked.block(
11923            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11924            Some("waits on both".to_owned()),
11925        );
11926        queue.put(&mut blocked).unwrap();
11927
11928        resolve_blockers(&queue, &questions);
11929
11930        let after = queue.get(&blocked.id).unwrap();
11931        assert_eq!(
11932            after.status,
11933            TaskStatus::Held,
11934            "a missing dependency must not leave the task blocked forever"
11935        );
11936        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11937        assert!(after.blocked_by.is_empty());
11938        let reason = after.hold_reason.as_deref().unwrap_or_default();
11939        assert!(
11940            reason.contains("20260101-000001-gone"),
11941            "the missing id must be named so an operator can tell what happened: {reason}"
11942        );
11943        assert!(
11944            reason.contains(&still_going.id),
11945            "the still-valid dependency must not silently vanish from the record: {reason}"
11946        );
11947    }
11948
11949    #[test]
11950    fn instruction_for_is_unchanged_without_any_answers() {
11951        let t = task();
11952        assert_eq!(instruction_for(&t), t.instruction);
11953    }
11954
11955    #[test]
11956    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11957        let dir = tempfile::tempdir().unwrap();
11958        let q = Queue::at(dir.path().join("queue"));
11959        let src = dir.path().join("shot.png");
11960        std::fs::write(&src, "x").unwrap();
11961        let mut t = task();
11962        q.attach(&mut t, &[src]).unwrap();
11963        let paths = task_attachments(&q, &t).unwrap();
11964        assert_eq!(paths.len(), 1);
11965        assert!(paths[0].is_absolute() && paths[0].is_file());
11966        std::fs::remove_file(&paths[0]).unwrap();
11967        let err = task_attachments(&q, &t).unwrap_err().to_string();
11968        assert!(err.contains("shot.png"), "{err}");
11969    }
11970
11971    #[tokio::test]
11972    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11973        let dir = tempfile::tempdir().unwrap();
11974        let queue_path = dir.path().join("queue");
11975        let queue = Queue::at(queue_path.clone());
11976        let mut t = task();
11977        t.source = Source::Agent {
11978            run: "originating-chat".into(),
11979            node: crate::queue::CHAT_NODE.into(),
11980        };
11981        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11982            stage: "config-fetch",
11983            target: "origin/main".into(),
11984        });
11985        record_config_failure(&mut t, &fetch);
11986        t.hold_machine(Some(format!("{fetch:#}")));
11987        let fetch_key = t.chat_notice_due().unwrap();
11988        t.chat_notices.push(fetch_key.clone());
11989        queue.put(&mut t).unwrap();
11990
11991        let queue = Queue::at(queue_path);
11992        let mut t = queue.get(&t.id).unwrap();
11993        let a = dir.path().join("a.toml");
11994        let b = dir.path().join("b.toml");
11995        for (path, text, new_cause) in [
11996            (&a, "[graph", true),
11997            (&a, "[verify", false),
11998            (&a, "[graph]\nimplementers = 'invalid-type'", true),
11999            (&b, "[graph]\nimplementers = 'invalid-type'", true),
12000        ] {
12001            t.release_operator("test", None);
12002            std::fs::write(path, text).unwrap();
12003            let error = Config::discover_fetched(dir.path(), Some(path))
12004                .await
12005                .unwrap_err();
12006            record_config_failure(&mut t, &error);
12007            t.hold_machine(Some(format!("{error:#}")));
12008            let due = t.chat_notice_due();
12009            assert_eq!(due.is_some(), new_cause, "{error:#}");
12010            if let Some(key) = due {
12011                assert_ne!(key, fetch_key);
12012                t.chat_notices.push(key);
12013            }
12014        }
12015        t.succeed();
12016        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
12017    }
12018
12019    #[test]
12020    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
12021        let dir = tempfile::tempdir().unwrap();
12022        let queue_path = dir.path().join("queue");
12023        let queue = Queue::at(queue_path.clone());
12024        let mut t = task();
12025        t.source = crate::queue::Source::Agent {
12026            run: "originating-chat".into(),
12027            node: crate::queue::CHAT_NODE.into(),
12028        };
12029        let a = dir.path().join("a.png");
12030        let b = dir.path().join("b.png");
12031        std::fs::write(&a, "a").unwrap();
12032        std::fs::write(&b, "b").unwrap();
12033        queue.attach(&mut t, &[a, b]).unwrap();
12034        let paths = task_attachments(&queue, &t).unwrap();
12035        for path in &paths {
12036            std::fs::remove_file(path).unwrap();
12037        }
12038        let missing = task_attachments(&queue, &t).unwrap_err();
12039        t.attempts += 1;
12040        let reason = missing.to_string();
12041        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12042        let first = t.chat_notice_due().expect("first attachment notice");
12043        t.chat_notices.push(first.clone());
12044        queue.put(&mut t).unwrap();
12045
12046        let queue = Queue::at(queue_path.clone());
12047        let mut t = queue.get(&t.id).unwrap();
12048        assert!(t.chat_notice_due().is_none(), "restart does not replay");
12049        t.release_operator("test", None);
12050        t.attempts += 1;
12051        let missing = task_attachments(&queue, &t).unwrap_err();
12052        t.fail_startup_target(
12053            "startup-attachments",
12054            missing.name,
12055            "same missing attachment with regenerated wording",
12056            1,
12057        );
12058        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
12059
12060        std::fs::write(&paths[0], "restored").unwrap();
12061        t.release_operator("test", None);
12062        t.attempts += 1;
12063        let missing = task_attachments(&queue, &t).unwrap_err();
12064        let reason = missing.to_string();
12065        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12066        let second = t
12067            .chat_notice_due()
12068            .expect("different attachment must notify");
12069        assert_ne!(first, second);
12070        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
12071    }
12072
12073    #[test]
12074    fn resumed_instruction_is_unchanged_without_any_answers() {
12075        let t = task();
12076        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
12077    }
12078
12079    #[test]
12080    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
12081        let mut t = task();
12082        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12083        // The run's own instruction on disk predates the answer: it is the
12084        // plain original text `Runner::start` saved before the operator was
12085        // ever asked anything.
12086        let old = t.instruction.clone();
12087
12088        let refreshed = resumed_instruction(&old, &t);
12089        assert!(refreshed.starts_with(&old), "the original text is kept");
12090        assert!(refreshed.contains("Which backend?"));
12091        assert!(refreshed.contains("SQLite"));
12092    }
12093
12094    #[test]
12095    fn resumed_instruction_keeps_an_original_answers_heading() {
12096        let mut t = task();
12097        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
12098        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12099
12100        let refreshed = resumed_instruction(&t.instruction, &t);
12101
12102        assert!(
12103            refreshed.starts_with(&t.instruction),
12104            "an answers heading in the original instruction is not the appended block"
12105        );
12106        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
12107        assert!(refreshed.contains("Which backend?"));
12108        assert!(refreshed.contains("SQLite"));
12109
12110        let repeated = resumed_instruction(&refreshed, &t);
12111        assert_eq!(
12112            repeated, refreshed,
12113            "only the final appended block is refreshed"
12114        );
12115    }
12116
12117    #[test]
12118    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
12119        let mut t = task();
12120        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12121
12122        // A first resume appends the block; a second resume of the same run,
12123        // with no new answer in between, must reproduce exactly the same
12124        // text rather than appending the block a second time.
12125        let once = resumed_instruction(&t.instruction, &t);
12126        let twice = resumed_instruction(&once, &t);
12127        assert_eq!(once, twice);
12128        assert_eq!(once.matches("Which backend?").count(), 1);
12129
12130        // A later answer replaces the block wholesale rather than growing it.
12131        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
12132        let refreshed = resumed_instruction(&once, &t);
12133        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
12134        assert!(refreshed.contains("Which backend?"));
12135        assert!(refreshed.contains("Which cache?"));
12136    }
12137
12138    #[test]
12139    fn prepare_instruction_covers_all_three_starters() {
12140        let mut t = task();
12141        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12142
12143        // Start: a fresh run gets the task text plus every answer so far —
12144        // exactly `instruction_for`.
12145        assert_eq!(
12146            prepare_instruction(&Starter::Start, None, &t),
12147            Some(instruction_for(&t))
12148        );
12149
12150        // Resume: the run's prior instruction is refreshed with the answer,
12151        // not discarded and not left stale.
12152        let old = t.instruction.clone();
12153        assert_eq!(
12154            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
12155            Some(resumed_instruction(&old, &t))
12156        );
12157
12158        // Review: a review-only pass builds its own instruction from the
12159        // branch's history in `crate::graph`, with no task statement at all -
12160        // this boundary must leave it alone.
12161        assert_eq!(
12162            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
12163            None
12164        );
12165    }
12166
12167    #[test]
12168    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
12169        assert_eq!(
12170            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
12171            Starter::Review("magi/eba2/A".to_owned())
12172        );
12173    }
12174
12175    #[test]
12176    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
12177        assert_eq!(
12178            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
12179            Starter::Start,
12180            "a vanished review branch must not fall back to resuming the old run either"
12181        );
12182    }
12183
12184    #[test]
12185    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
12186        let mut t = task();
12187        t.start("old-run".to_owned());
12188        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
12189        t.release();
12190        let branch = t.review_branch.take();
12191        assert_eq!(
12192            choose_starter(branch.as_deref(), true, Some("old-run")),
12193            Starter::Review("magi/eba2/A".to_owned()),
12194            "a review wins over resuming the old run"
12195        );
12196    }
12197
12198    #[test]
12199    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
12200        assert_eq!(
12201            choose_starter(None, false, Some("some-run")),
12202            Starter::Resume("some-run".to_owned())
12203        );
12204        assert_eq!(choose_starter(None, false, None), Starter::Start);
12205    }
12206
12207    #[test]
12208    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
12209        let mut released = task();
12210        released.start("stalled-run".to_owned());
12211        released.requeue();
12212        let unfinished = (!released.fresh_start)
12213            .then(|| Some("stalled-run".to_owned()))
12214            .flatten();
12215        assert_eq!(
12216            choose_starter(None, false, unfinished.as_deref()),
12217            Starter::Start,
12218            "release keeps run history but must not resume it"
12219        );
12220        assert_eq!(released.runs, ["stalled-run"]);
12221    }
12222
12223    #[test]
12224    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
12225        let dir = tempfile::tempdir().unwrap();
12226        let queue = Queue::at(dir.path().join("queue"));
12227        let mut state = run_state(RunStatus::Blocked);
12228        state.merge_decision = Some(crate::merge_decision::Decision {
12229            question: "hold-inquiry".into(),
12230            target: crate::merge_decision::Target {
12231                pr: "https://example.test/pull/1".into(),
12232                head: "reviewed-head".into(),
12233                language: "en".into(),
12234            },
12235            choice: land::HOLD.into(),
12236            closed: false,
12237            replacement_run: None,
12238            replacement_pr: None,
12239        });
12240        let mut t = task();
12241        t.start(state.id.clone());
12242        settle_and_diagnose(
12243            &mut t,
12244            Verdict {
12245                status: RunStatus::Blocked,
12246                left_pr: true,
12247                quota_hit: false,
12248                parked: false,
12249                no_viable_candidates: false,
12250            },
12251            "held",
12252            2,
12253            &state,
12254        );
12255        queue.put(&mut t).unwrap();
12256        t.release_operator("chat", None);
12257        t.edit("revised".into(), "revised instruction".into())
12258            .unwrap();
12259        queue.put(&mut t).unwrap();
12260        drop(state);
12261        assert_eq!(
12262            queue
12263                .get(&t.id)
12264                .unwrap()
12265                .decision_effects
12266                .get("hold-inquiry"),
12267            Some(&format!("decision: {}", land::HOLD))
12268        );
12269    }
12270
12271    fn stopped_public_run(status: RunStatus) -> RunState {
12272        let mut state = run_state(status);
12273        state.driver_exited = true;
12274        state.config.graph.land = true;
12275        state.config.graph.review_rounds = 1;
12276        state.reviews = vec![review_round(1)];
12277        state.merge = Some(crate::run::MergeOutcome {
12278            mode: MergeMode::Pr,
12279            ok: false,
12280            detail: "landing stopped".into(),
12281            empty: false,
12282        });
12283        state.pr = Some(crate::run::PrRecord {
12284            url: "https://example.test/pull/1".into(),
12285            number: 1,
12286            state: "open".into(),
12287            checks: "red".into(),
12288            round: 1,
12289            rounds: 1,
12290            red_at_merge: Vec::new(),
12291        });
12292        state
12293    }
12294
12295    #[test]
12296    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
12297        for status in [RunStatus::Blocked, RunStatus::Gating] {
12298            let home = tempfile::tempdir().unwrap();
12299            let mut state = stopped_public_run(status);
12300            state.save_under(home.path()).unwrap();
12301            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
12302            assert!(!exhausted_review_budget(&state));
12303            let mut task = held_task_with(&state.id);
12304            task.release();
12305            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
12306            assert_eq!(
12307                choose_starter(None, false, unfinished.as_deref()),
12308                Starter::Resume(state.id.clone())
12309            );
12310            let question = action_question(&state.id, resume_action(&state.id));
12311            assert_eq!(
12312                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12313                    state.clone()
12314                )),
12315                ActionDecision::Resume(state.id.clone())
12316            );
12317            // The control-plane command uses this same preflight before pinning.
12318            assert_eq!(
12319                crate::resume::validate(home.path(), &state.id).unwrap().id,
12320                state.id
12321            );
12322            let queue = Queue::at(home.path().join("queue"));
12323            let mut controlled = Task::new(
12324                "resume land".into(),
12325                state.instruction.clone(),
12326                state.repo.clone(),
12327                Source::Agent {
12328                    run: "talk".into(),
12329                    node: crate::queue::CHAT_NODE.into(),
12330                },
12331            );
12332            controlled.runs.push(state.id.clone());
12333            controlled.hold_machine(Some("land stopped".into()));
12334            queue.put(&mut controlled).unwrap();
12335            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
12336            assert_eq!(resumed.status, TaskStatus::Queued);
12337            assert_eq!(
12338                resumed.resume_override.unwrap().pinned_run,
12339                Some(state.id.clone())
12340            );
12341            assert_eq!(resumed.attempts, 0);
12342        }
12343    }
12344
12345    #[test]
12346    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
12347        for review_rounds in [0, 1] {
12348            let home = tempfile::tempdir().unwrap();
12349            let mut state = run_state(RunStatus::Blocked);
12350            state.config.graph.review_rounds = review_rounds;
12351            if review_rounds > 0 {
12352                let mut review = review_round(1);
12353                review.clean = true;
12354                state.reviews = vec![review];
12355            }
12356            state.gate_ran = true;
12357            state.gate = vec![crate::run::CommandOutcome {
12358                command: "verify".into(),
12359                code: Some(1),
12360                output_tail: "gate failed after repair budget exhausted".into(),
12361                duration_ms: 0,
12362                resource_blocked: false,
12363            }];
12364            state.save_under(home.path()).unwrap();
12365            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
12366            assert!(exhausted_review_budget(&state));
12367            let mut task = held_task_with(&state.id);
12368            task.release();
12369            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
12370            let question = action_question(&state.id, resume_action(&state.id));
12371            assert_ne!(
12372                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12373                    state.clone()
12374                )),
12375                ActionDecision::Resume(state.id.clone())
12376            );
12377            let error = crate::resume::validate(home.path(), &state.id)
12378                .unwrap_err()
12379                .to_string();
12380            assert!(!error.contains("review budget exhausted"), "{error}");
12381            assert!(
12382                error.contains(if review_rounds == 0 {
12383                    "review is disabled"
12384                } else {
12385                    "gate already ran"
12386                }),
12387                "{error}"
12388            );
12389
12390            // An unexecuted gate still has work to do with or without reviews.
12391            state.gate_ran = false;
12392            state.gate.clear();
12393            assert!(!exhausted_review_budget(&state));
12394            assert_eq!(
12395                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
12396                Some(state.id)
12397            );
12398        }
12399    }
12400
12401    #[test]
12402    fn resource_blocked_verification_resumes_the_same_run() {
12403        for (kind, stage) in [
12404            ("cache", "clean"),
12405            ("coordination", "clean"),
12406            ("cache", "review-e2e"),
12407            ("coordination", "no-reviews"),
12408            ("coordination", "handoff"),
12409        ] {
12410            let home = tempfile::tempdir().unwrap();
12411            let mut state = run_state(RunStatus::Blocked);
12412            state.config.graph.review_rounds = 1;
12413            let mut review = review_round(1);
12414            review.clean = true;
12415            state.reviews = vec![review];
12416            if stage == "review-e2e" {
12417                let review = &mut state.reviews[0];
12418                review.clean = false;
12419                review.blocking = 1;
12420                review.e2e = vec![crate::run::CommandOutcome {
12421                    command: "verify".into(),
12422                    code: None,
12423                    output_tail: "resource wait expired".into(),
12424                    duration_ms: 0,
12425                    resource_blocked: true,
12426                }];
12427            } else if stage == "no-reviews" {
12428                state.config.graph.review_rounds = 0;
12429                state.reviews.clear();
12430            } else if stage == "handoff" {
12431                // A completed final verification can hand off to the gate
12432                // even when the review still carries contested findings.
12433                let review = &mut state.reviews[0];
12434                review.clean = false;
12435                review.blocking = 1;
12436                review.e2e = vec![crate::run::CommandOutcome {
12437                    command: "verify".into(),
12438                    code: Some(0),
12439                    output_tail: String::new(),
12440                    duration_ms: 0,
12441                    resource_blocked: false,
12442                }];
12443            }
12444            state.gate_ran = false;
12445            state.resource_block = Some(crate::run::ResourceBlock {
12446                cause: crate::run::ResourceBlockCause::Other,
12447                node: if stage == "review-e2e" {
12448                    "review"
12449                } else {
12450                    "gate"
12451                }
12452                .into(),
12453                kind: kind.into(),
12454                detail: "resource wait expired".into(),
12455                at: jiff::Timestamp::now(),
12456            });
12457            state.save_under(home.path()).unwrap();
12458            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
12459            assert!(!exhausted_review_budget(&state));
12460            let mut task = held_task_with(&state.id);
12461            task.release();
12462            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
12463            assert_eq!(
12464                choose_starter(None, false, unfinished.as_deref()),
12465                Starter::Resume(state.id.clone())
12466            );
12467            let question = action_question(&state.id, resume_action(&state.id));
12468            assert_eq!(
12469                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12470                    state.clone()
12471                )),
12472                ActionDecision::Resume(state.id.clone())
12473            );
12474            assert_eq!(
12475                crate::resume::validate(home.path(), &state.id).unwrap().id,
12476                state.id
12477            );
12478            let queue = Queue::at(home.path().join("queue"));
12479            let mut controlled = Task::new(
12480                "resume verification".into(),
12481                state.instruction.clone(),
12482                state.repo.clone(),
12483                Source::Agent {
12484                    run: "talk".into(),
12485                    node: crate::queue::CHAT_NODE.into(),
12486                },
12487            );
12488            controlled.runs.push(state.id.clone());
12489            controlled.hold_machine(Some("verification resource unavailable".into()));
12490            queue.put(&mut controlled).unwrap();
12491            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
12492            assert_eq!(resumed.status, TaskStatus::Queued);
12493            assert_eq!(
12494                resumed.resume_override.unwrap().pinned_run,
12495                Some(state.id.clone())
12496            );
12497            assert_eq!(resumed.attempts, 0);
12498
12499            // A genuinely unresolved final review still exhausts the budget.
12500            state.config.graph.review_rounds = 1;
12501            let mut unresolved = review_round(1);
12502            unresolved.blocking = 1;
12503            state.reviews = vec![unresolved];
12504            state.resource_block = None;
12505            state.save_under(home.path()).unwrap();
12506            assert!(exhausted_review_budget(&state));
12507            assert!(crate::resume::validate(home.path(), &state.id).is_err());
12508        }
12509    }
12510
12511    #[tokio::test]
12512    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
12513        if !crate::standalone_test(
12514            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
12515        ) {
12516            return;
12517        }
12518        let home = tempfile::tempdir().unwrap();
12519        let mut owner = stopped_public_run(RunStatus::Blocked);
12520        owner.save_under(home.path()).unwrap();
12521        let history = vec![owner.id.clone()];
12522        let repo = owner.repo.clone();
12523        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
12524        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
12525        let initial =
12526            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
12527        assert!(
12528            initial.is_pending(),
12529            "a busy record must not hold or resume the task"
12530        );
12531        owner.retired_to = Some("20260101-000001-bbbb".into());
12532        owner.save_under(home.path()).unwrap();
12533        drop(lock);
12534        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
12535            .await
12536            .expect("ownership lock released")
12537            .expect("read settled owner");
12538        assert!(
12539            result.is_none(),
12540            "the retired owner must not be resumed from a stale read"
12541        );
12542    }
12543
12544    #[tokio::test]
12545    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
12546        if !crate::standalone_test(
12547            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
12548        ) {
12549            return;
12550        }
12551        let home = tempfile::tempdir().unwrap();
12552        let mut owner = stopped_public_run(RunStatus::Blocked);
12553        let repo = tempfile::tempdir().unwrap();
12554        crate::git::git(repo.path(), &["init"]).await.unwrap();
12555        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
12556        owner.id = "20260101-000000-aaaa".into();
12557        owner.save_under(home.path()).unwrap();
12558        let mut successor = run_state(RunStatus::Blocked);
12559        successor.id = "20260101-000001-bbbb".into();
12560        successor.save_under(home.path()).unwrap();
12561        let runs = vec![owner.id.clone(), successor.id.clone()];
12562        assert_eq!(
12563            public_resume_owner(home.path(), &runs, &owner.repo)
12564                .await
12565                .unwrap()
12566                .unwrap()
12567                .id,
12568            owner.id
12569        );
12570        let subdir = owner.repo.join("nested");
12571        std::fs::create_dir(&subdir).unwrap();
12572        assert_eq!(
12573            public_resume_owner(home.path(), &runs, &subdir)
12574                .await
12575                .unwrap()
12576                .unwrap()
12577                .id,
12578            owner.id
12579        );
12580        #[cfg(unix)]
12581        {
12582            let alias = home.path().join("repo-alias");
12583            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
12584            assert_eq!(
12585                public_resume_owner(home.path(), &runs, &alias.join("nested"))
12586                    .await
12587                    .unwrap()
12588                    .unwrap()
12589                    .id,
12590                owner.id
12591            );
12592        }
12593        let different = tempfile::tempdir().unwrap();
12594        crate::git::git(different.path(), &["init"]).await.unwrap();
12595        assert!(
12596            public_resume_owner(home.path(), &runs, different.path())
12597                .await
12598                .is_err()
12599        );
12600        std::fs::remove_file(
12601            home.path()
12602                .join("runs")
12603                .join(&successor.id)
12604                .join("run.json"),
12605        )
12606        .unwrap();
12607        assert!(
12608            public_resume_owner(home.path(), &runs, &owner.repo)
12609                .await
12610                .is_err()
12611        );
12612    }
12613
12614    #[test]
12615    fn an_ordinary_release_keeps_a_resumable_run_available() {
12616        let mut released = task();
12617        released.start("stalled-run".to_owned());
12618        released.release();
12619        let unfinished = (!released.fresh_start)
12620            .then(|| Some("stalled-run".to_owned()))
12621            .flatten();
12622        assert_eq!(
12623            choose_starter(None, false, unfinished.as_deref()),
12624            Starter::Resume("stalled-run".to_owned()),
12625            "manual release must preserve the normal resume path"
12626        );
12627    }
12628
12629    #[test]
12630    fn resume_refusals_explain_admission_without_changing_task_or_run() {
12631        use crate::handover::{ResumeRefusal, resume_refusal_under};
12632        let home = tempfile::tempdir().unwrap();
12633        let mut exhausted = run_state(RunStatus::Blocked);
12634        exhausted.driver_exited = true;
12635        exhausted.config.graph.review_rounds = 3;
12636        exhausted.reviews = (1..=3).map(review_round).collect();
12637        for refusal in [
12638            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
12639            ResumeRefusal::Status(RunStatus::Ready),
12640            ResumeRefusal::Released("20261022-000000-aaaa".into()),
12641            ResumeRefusal::Retired("retirement-successor".into()),
12642            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
12643        ] {
12644            let mut state = exhausted.clone();
12645            let expected = match refusal {
12646                ResumeRefusal::Status(_) => {
12647                    state.status = RunStatus::Ready;
12648                    "status `ready`"
12649                }
12650                ResumeRefusal::Released(ref target) => {
12651                    state.released_to = Some(target.clone());
12652                    "execution was released"
12653                }
12654                ResumeRefusal::Retired(ref target) => {
12655                    state.retired_to = Some(target.clone());
12656                    "execution was retired"
12657                }
12658                ResumeRefusal::OwnershipTransferred(ref target) => {
12659                    state.pr_taken_over_by = Some(target.clone());
12660                    "PR ownership was transferred"
12661                }
12662                _ => "review budget exhausted (3/3 rounds used)",
12663            };
12664            assert_eq!(
12665                resume_refusal_under(&state, Some(home.path())),
12666                Some(refusal.clone())
12667            );
12668            assert_eq!(
12669                refusal.successor(),
12670                state
12671                    .released_to
12672                    .as_deref()
12673                    .or(state.retired_to.as_deref())
12674                    .or(state.pr_taken_over_by.as_deref())
12675            );
12676            state.save_under(home.path()).unwrap();
12677            let queue = Queue::at(home.path().join("queue"));
12678            let mut task = Task::new(
12679                "retained implementation".into(),
12680                state.instruction.clone(),
12681                state.repo.clone(),
12682                Source::Agent {
12683                    run: "talk".into(),
12684                    node: crate::queue::CHAT_NODE.into(),
12685                },
12686            );
12687            task.runs.push(state.id.clone());
12688            task.hold_machine(Some("stopped".into()));
12689            queue.put(&mut task).unwrap();
12690            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
12691            let before_run = serde_json::to_value(&state).unwrap();
12692            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
12693                .unwrap_err()
12694                .to_string();
12695            assert!(error.contains(expected), "{error}");
12696            assert!(!error.contains("only a stalled or blocked"), "{error}");
12697            if matches!(refusal, ResumeRefusal::Status(_)) {
12698                assert!(
12699                    error.contains("is final; there is nothing left to resume"),
12700                    "{error}"
12701                );
12702            }
12703            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
12704                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
12705                assert!(error.contains("review-only successor with a new review budget"));
12706                assert!(error.contains("does not resume this run"));
12707            }
12708            for target in [
12709                &state.released_to,
12710                &state.retired_to,
12711                &state.pr_taken_over_by,
12712            ]
12713            .into_iter()
12714            .flatten()
12715            {
12716                let short = if state.retired_to.as_ref() == Some(target) {
12717                    target.as_str()
12718                } else {
12719                    crate::run::short_of(target)
12720                };
12721                assert!(
12722                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
12723                    "{error}"
12724                );
12725                if short != target {
12726                    assert!(!error.contains(target), "full successor id leaked: {error}");
12727                }
12728            }
12729            assert_eq!(
12730                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
12731                before_task
12732            );
12733            assert_eq!(
12734                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
12735                    .unwrap(),
12736                before_run
12737            );
12738            let question = action_question(&state.id, resume_action(&state.id));
12739            for phrases in [&PHRASES_EN, &PHRASES_JA] {
12740                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
12741                    RunState::load_under(id, home.path())
12742                });
12743                let ActionDecision::Refuse(detail) = decision else {
12744                    panic!(
12745                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
12746                        state.id,
12747                        home.path().display()
12748                    );
12749                };
12750                assert!(detail.contains(expected), "{detail}");
12751            }
12752        }
12753        // Preserve predicate ordering, while keeping every recorded destination visible.
12754        exhausted.status = RunStatus::Ready;
12755        exhausted.released_to = Some("released".into());
12756        exhausted.retired_to = Some("retired".into());
12757        exhausted.pr_taken_over_by = Some("owner".into());
12758        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
12759        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
12760        let detail = reason.diagnostic(&exhausted);
12761        for target in ["released", "retired", "owner"] {
12762            assert!(detail.contains(&format!("magi show {target}")));
12763        }
12764    }
12765
12766    #[test]
12767    fn resume_action_ignores_question_checkpoints_in_another_home() {
12768        crate::run::pin_test_home();
12769        let home = tempfile::tempdir().unwrap();
12770        let mut state = run_state(RunStatus::Blocked);
12771        // The private directory reserves this fixture's identity even while
12772        // other tests write questions into the process-wide store.
12773        state.id = format!(
12774            "resume-context-{}",
12775            home.path().file_name().unwrap().to_str().unwrap()
12776        );
12777        state.driver_exited = true;
12778        state.config.graph.review_rounds = 1;
12779        state.reviews = vec![review_round(1)];
12780        state.save_under(home.path()).unwrap();
12781        let task = held_task_with(&state.id);
12782        let answer = action_question(&state.id, resume_action(&state.id));
12783        let mut checkpoint = approval_question(&state.id);
12784        let foreign = Questions::open();
12785        foreign.put(&mut checkpoint).unwrap();
12786        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
12787        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12788            RunState::load_under(id, home.path())
12789        });
12790        let matching: Vec<_> = foreign
12791            .list()
12792            .into_iter()
12793            .filter(|q| q.run == state.id && q.status.open())
12794            .collect();
12795        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
12796        assert!(
12797            matches!(decision, ActionDecision::Refuse(_)),
12798            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
12799            state.id,
12800            home.path().display(),
12801            crate::run::test_home().display()
12802        );
12803        assert_eq!(
12804            refusal,
12805            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
12806        );
12807        let local = Questions::at(home.path().join("questions"));
12808        for status in [
12809            ask::QuestionStatus::Open,
12810            ask::QuestionStatus::Answered,
12811            ask::QuestionStatus::Abandoned,
12812        ] {
12813            let mut question = checkpoint.clone();
12814            match status {
12815                ask::QuestionStatus::Open => {}
12816                ask::QuestionStatus::Answered => {
12817                    question
12818                        .answer(ask::Answer::Choice(question.choices[0].clone()))
12819                        .unwrap();
12820                }
12821                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
12822            }
12823            local.put(&mut question).unwrap();
12824            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
12825                RunState::load_under(id, home.path())
12826            });
12827            if status.open() {
12828                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
12829            } else {
12830                assert!(
12831                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
12832                    "status={status:?}, decision={decision:?}"
12833                );
12834            }
12835        }
12836    }
12837
12838    #[test]
12839    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
12840        let home = tempfile::tempdir().unwrap();
12841        let mut state = run_state(RunStatus::Stalled);
12842        state.id = format!(
12843            "resume-driver-{}",
12844            home.path().file_name().unwrap().to_str().unwrap()
12845        );
12846        state.driver_claimed = Some(false);
12847        state.save_under(home.path()).unwrap();
12848        let task = held_task_with(&state.id);
12849        let question = action_question(&state.id, resume_action(&state.id));
12850        let decide = || {
12851            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
12852                RunState::load_under(id, home.path())
12853            })
12854        };
12855        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
12856        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
12857        assert_eq!(
12858            decide(),
12859            ActionDecision::Refuse("run already has a live driver".into())
12860        );
12861        drop(lease);
12862        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
12863    }
12864
12865    #[test]
12866    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
12867        let home = tempfile::tempdir().unwrap();
12868        let mut state = run_state(RunStatus::Blocked);
12869        state.driver_exited = true;
12870        state.config.graph.review_rounds = 1;
12871        state.reviews = vec![review_round(1)];
12872        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
12873        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
12874            let mut saved = state.clone();
12875            match checkpoint {
12876                "publication" => saved.pr_publication_pending = true,
12877                "approval" => {
12878                    saved.land_approval = Some(crate::run::LandApproval {
12879                        question: "approval".into(),
12880                        head: "head".into(),
12881                    })
12882                }
12883                "armed" => saved.land_armed_head = Some("head".into()),
12884                "landing" => saved.status = RunStatus::Landing,
12885                _ => {
12886                    let mut question = ask::Question::new(
12887                        saved.id.clone(),
12888                        "review".into(),
12889                        "review-1".into(),
12890                        "continue?".into(),
12891                        String::new(),
12892                        vec!["continue".into()],
12893                    );
12894                    ask::Questions::at(home.path().join("questions"))
12895                        .put(&mut question)
12896                        .unwrap();
12897                }
12898            }
12899            saved.save_under(home.path()).unwrap();
12900            assert!(
12901                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
12902                "{checkpoint}"
12903            );
12904            assert!(
12905                crate::resume::validate(home.path(), &saved.id).is_ok(),
12906                "{checkpoint}"
12907            );
12908        }
12909    }
12910
12911    #[test]
12912    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
12913        let mut state = run_state(RunStatus::Blocked);
12914        state.config.graph.review_rounds = 3;
12915        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
12916        assert!(exhausted_review_budget(&state));
12917
12918        // One round still unused: resuming can still ask a reviewer something.
12919        state.reviews.pop();
12920        assert!(!exhausted_review_budget(&state));
12921
12922        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
12923        // count: only a `Blocked` run re-enters the review loop on resume.
12924        let mut stalled = run_state(RunStatus::Stalled);
12925        stalled.config.graph.review_rounds = 1;
12926        stalled.reviews = vec![review_round(1)];
12927        assert!(!exhausted_review_budget(&stalled));
12928    }
12929
12930    fn review_round(round: usize) -> crate::run::ReviewRound {
12931        crate::run::ReviewRound {
12932            round,
12933            head: "deadbeef".to_owned(),
12934            verified_head: None,
12935            verified_at: None,
12936            reviews: Vec::new(),
12937            e2e: Vec::new(),
12938            verify_retried: false,
12939            e2e_deferred: false,
12940            e2e_defer_reason: None,
12941            fix: None,
12942            blocking: 0,
12943            answered: 1,
12944            expected: 1,
12945            clean: false,
12946            progressed: true,
12947            vote_split: false,
12948            reconsideration: Vec::new(),
12949            verdict: None,
12950        }
12951    }
12952
12953    #[test]
12954    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
12955        let mut run = RunState::new(
12956            PathBuf::from("/repo"),
12957            "main".to_owned(),
12958            "abc1234def".to_owned(),
12959            "add retries".to_owned(),
12960            Config::default(),
12961        );
12962        run.status = RunStatus::Judging;
12963        run.parked = true;
12964        let mut task = Task::new(
12965            "add retries".to_owned(),
12966            "add retries".to_owned(),
12967            PathBuf::from("/repo"),
12968            crate::queue::Source::Human,
12969        );
12970        task.status = TaskStatus::Failed;
12971        task.runs = vec![run.id.clone()];
12972        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
12973        assert!(with(&task, &run), "parked after judging is the case");
12974        let mut parked_task = task.clone();
12975        parked_task.status = TaskStatus::Parked;
12976        assert!(with(&parked_task, &run), "the Parked status is the case");
12977
12978        let mut not_parked = run.clone();
12979        not_parked.parked = false;
12980        not_parked.status = RunStatus::Stalled;
12981        assert!(!with(&task, &not_parked), "a stall is the conductor's");
12982
12983        let mut fresh = task.clone();
12984        fresh.fresh_start = true;
12985        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
12986
12987        let mut review = task.clone();
12988        review.review_branch = Some("magi/x/A".to_owned());
12989        assert!(!with(&review, &run), "review is ranked before resume");
12990
12991        let mut held = task.clone();
12992        held.status = TaskStatus::Held;
12993        assert!(!with(&held, &run), "a hold stays visible to the conductor");
12994
12995        let mut released = run.clone();
12996        released.released_to = Some("20260901-000000-new1".to_owned());
12997        assert!(!with(&task, &released), "nothing left to resume into");
12998
12999        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
13000            "unreadable"
13001        )));
13002    }
13003
13004    #[test]
13005    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
13006        let mut released = RunState::new(
13007            PathBuf::from("/repo"),
13008            "main".to_owned(),
13009            "abc1234def".to_owned(),
13010            "add retries".to_owned(),
13011            Config::default(),
13012        );
13013        released.status = RunStatus::Blocked;
13014        assert_eq!(
13015            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13016            Some(released.id.clone())
13017        );
13018        released.released_to = Some("20260901-000000-new1".to_owned());
13019        assert_eq!(
13020            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13021            None,
13022            "there is nothing left to resume it into"
13023        );
13024    }
13025
13026    #[test]
13027    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
13028        // Mirrors the failure this exists to close: a task's last run ended
13029        // `Blocked` with the review budget spent, `crate::conduct` chose
13030        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
13031        // evidence), and without this check `attempt` would go on treating
13032        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
13033        // review loop iterates zero times over an already-spent budget, so
13034        // the resumed run settles right back to `Blocked` having asked nobody
13035        // anything, and `Requeue`'s promised fresh competition never happens.
13036        let mut exhausted = RunState::new(
13037            PathBuf::from("/repo"),
13038            "main".to_owned(),
13039            "abc1234def".to_owned(),
13040            "add retries".to_owned(),
13041            Config::default(),
13042        );
13043        exhausted.status = RunStatus::Blocked;
13044        exhausted.config.graph.review_rounds = 1;
13045        exhausted.reviews = vec![review_round(1)];
13046
13047        assert_eq!(
13048            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
13049            None,
13050            "an exhausted `Blocked` run must not be offered as resumable"
13051        );
13052
13053        // A `Blocked` run with rounds still unused is genuinely worth
13054        // resuming, and must still be found.
13055        let mut has_budget_left = RunState::new(
13056            PathBuf::from("/repo"),
13057            "main".to_owned(),
13058            "abc1234def".to_owned(),
13059            "add retries".to_owned(),
13060            Config::default(),
13061        );
13062        has_budget_left.status = RunStatus::Blocked;
13063        has_budget_left.config.graph.review_rounds = 3;
13064        has_budget_left.reviews = vec![review_round(1)];
13065
13066        assert_eq!(
13067            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
13068                Ok(has_budget_left.clone())
13069            }),
13070            Some(has_budget_left.id.clone())
13071        );
13072    }
13073
13074    #[test]
13075    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
13076        let mut run = RunState::new(
13077            PathBuf::from("/repo"),
13078            "main".to_owned(),
13079            "abc1234def".to_owned(),
13080            "add retries".to_owned(),
13081            Config::default(),
13082        );
13083        run.status = RunStatus::Blocked;
13084        run.config.graph.review_rounds = 1;
13085        run.reviews = vec![review_round(1)];
13086        run.pr_publication_pending = true;
13087        assert_eq!(
13088            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
13089            Some(run.id.clone()),
13090            "a spent review budget must not turn a failed publication into a re-competition"
13091        );
13092    }
13093
13094    #[test]
13095    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
13096        let mut task = Task::new(
13097            "recover work".into(),
13098            "recover work".into(),
13099            PathBuf::from("/repo"),
13100            crate::queue::Source::Human,
13101        );
13102        let mut history = std::collections::BTreeMap::new();
13103        for index in 0..8 {
13104            let mut run = run_state(RunStatus::Blocked);
13105            run.id = format!("20260101-000000-{index:04}");
13106            run.base_commit = format!("upstream-{index}");
13107            // Seven empty newer attempts must not erase the old recovery owner.
13108            if index > 0 {
13109                run.candidates.clear();
13110            }
13111            task.runs.extend([run.id.clone(), run.id.clone()]);
13112            history.insert(run.id.clone(), run);
13113            task.requeue();
13114        }
13115        let check = |task: &Task, starter: &Starter, limit| {
13116            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
13117        };
13118        assert!(
13119            check(&task, &Starter::Start, 8)
13120                .unwrap()
13121                .contains("8 unretired")
13122        );
13123        assert!(check(&task, &Starter::Start, 9).is_none());
13124        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
13125        task.release_operator("owner", None);
13126        assert_eq!(task.attempts, 0);
13127        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13128        assert!(check(&restored, &Starter::Start, 8).is_some());
13129        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
13130        assert!(check(&restored, &Starter::Start, 0).is_none());
13131    }
13132
13133    #[test]
13134    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
13135        let tmp = tempfile::tempdir().unwrap();
13136        let mut task = Task::new(
13137            "recover selected PR".into(),
13138            "preserve implementation".into(),
13139            tmp.path().join("repo"),
13140            crate::queue::Source::Human,
13141        );
13142        let mut failed = run_state(RunStatus::Failed);
13143        failed.id = "20260101-000000-fail".into();
13144        failed.candidates.clear();
13145        failed.prep_complete = Some(false);
13146        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
13147        failed.startup = Some(crate::run::Startup {
13148            kind: "pr-recovery".into(),
13149            branch: Some("selected-public-head".into()),
13150            stage: "worktree-setup".into(),
13151            complete: false,
13152            failure: Some("setup modified a tracked file and failed".into()),
13153        });
13154        // Setup may fail before a candidate is recorded; its dirty worktree
13155        // still needs protection and consumes the independent retained bound.
13156        let worktree = failed.worktree_root().join("under-review");
13157        std::fs::create_dir_all(&worktree).unwrap();
13158        let retained_edit = worktree.join("implementation");
13159        std::fs::write(&retained_edit, "retained setup edit").unwrap();
13160        task.record_startup_failure(crate::run::StartupFailure {
13161            run: failed.id.clone(),
13162            stage: "worktree-setup".into(),
13163        });
13164        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13165        assert!(task.runs.is_empty() && task.passes.is_empty());
13166        assert_eq!(task.attempts, 0);
13167        let starter = Starter::Review("selected-public-head".into());
13168        assert!(
13169            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
13170                .unwrap()
13171                .contains("1 unretired")
13172        );
13173        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
13174        assert!(
13175            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
13176                .unwrap()
13177                .contains("Cannot verify")
13178        );
13179        // Older or mixed writers can link the same reservation in both lists.
13180        let mut mixed = task.clone();
13181        mixed.runs.push(failed.id.clone());
13182        mixed
13183            .startup_failures
13184            .push(task.startup_failures[0].clone());
13185        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
13186        failed.retired_to = Some("verified-recovery-owner".into());
13187        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
13188        assert!(
13189            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
13190                panic!("resuming the existing owner must not allocate a new attempt")
13191            })
13192            .is_none()
13193        );
13194        assert_eq!(
13195            std::fs::read_to_string(retained_edit).unwrap(),
13196            "retained setup edit"
13197        );
13198        assert!(task.runs.is_empty() && task.passes.is_empty());
13199        assert_eq!(task.attempts, 0);
13200    }
13201
13202    #[test]
13203    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
13204        let mut task = Task::new(
13205            "recover work".into(),
13206            "recover work".into(),
13207            PathBuf::from("/repo"),
13208            crate::queue::Source::Human,
13209        );
13210        let mut run = run_state(RunStatus::Superseded);
13211        run.candidates.clear();
13212        task.runs.push(run.id.clone());
13213        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
13214        run.retired_to = Some("authority".into());
13215        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13216        run.retired_to = None;
13217        run.released_to = Some("authority".into());
13218        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13219        assert!(
13220            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
13221                .unwrap()
13222                .contains("Cannot verify")
13223        );
13224        // Resuming an existing owner needs no new inventory or worktree budget.
13225        assert!(
13226            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
13227                panic!("resume must not load historical attempts")
13228            })
13229            .is_none()
13230        );
13231    }
13232
13233    #[test]
13234    fn retired_resume_requires_a_valid_same_repository_authority() {
13235        let mut source = run_state(RunStatus::Blocked);
13236        let mut empty = run_state(RunStatus::Blocked);
13237        empty.retired_to = Some(source.id.clone());
13238        let runs = vec![source.id.clone(), empty.id.clone()];
13239        let resolve = |source: &RunState, empty: &RunState| {
13240            unfinished_run_with(&runs, "fixture", |id| {
13241                if id == source.id {
13242                    Ok(source.clone())
13243                } else if id == empty.id {
13244                    Ok(empty.clone())
13245                } else {
13246                    bail!("unreadable authority")
13247                }
13248            })
13249        };
13250        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
13251        assert_eq!(
13252            choose_starter(None, false, resolve(&source, &empty).as_deref()),
13253            Starter::Resume(source.id.clone())
13254        );
13255        source.retired_to = Some(empty.id.clone());
13256        assert!(
13257            resolve(&source, &empty).is_none(),
13258            "cycles do not revive obsolete runs"
13259        );
13260        source.retired_to = None;
13261        source.repo = PathBuf::from("/another-repository");
13262        assert!(resolve(&source, &empty).is_none());
13263        source.repo = empty.repo.clone();
13264        source.released_to = Some("later".into());
13265        assert!(resolve(&source, &empty).is_none());
13266        empty.retired_to = Some("unlisted-run".into());
13267        assert!(resolve(&source, &empty).is_none());
13268    }
13269
13270    #[test]
13271    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
13272        // A task whose history holds an *older* run that still looks
13273        // resumable (say, a competition `Runner::review` was started
13274        // alongside after that older run went `Stalled`) and a *newest* run
13275        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
13276        // on this task must mean a fresh competition — falling back to the
13277        // stale, superseded `Stalled` run instead would resurrect history
13278        // nothing asked to revisit and silently defeat the requeue.
13279        let mut older_stalled = RunState::new(
13280            PathBuf::from("/repo"),
13281            "main".to_owned(),
13282            "abc1234def".to_owned(),
13283            "add retries".to_owned(),
13284            Config::default(),
13285        );
13286        older_stalled.status = RunStatus::Stalled;
13287
13288        let mut newest_exhausted = RunState::new(
13289            PathBuf::from("/repo"),
13290            "main".to_owned(),
13291            "abc1234def".to_owned(),
13292            "add retries".to_owned(),
13293            Config::default(),
13294        );
13295        newest_exhausted.status = RunStatus::Blocked;
13296        newest_exhausted.config.graph.review_rounds = 1;
13297        newest_exhausted.reviews = vec![review_round(1)];
13298
13299        assert_eq!(
13300            unfinished_run_with(
13301                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
13302                "t",
13303                |_| Ok(newest_exhausted.clone())
13304            ),
13305            None,
13306            "the newest run is exhausted, so nothing here is worth resuming - \
13307             least of all the older, already-superseded run"
13308        );
13309    }
13310
13311    #[test]
13312    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
13313        assert_eq!(
13314            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
13315                Err(anyhow::anyhow!("fixture is absent"))
13316            }),
13317            None
13318        );
13319    }
13320
13321    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
13322        let mut q = ask::Question::new(
13323            run.to_owned(),
13324            "implement".to_owned(),
13325            "impl-A".to_owned(),
13326            "continue?".to_owned(),
13327            String::new(),
13328            vec!["resume で続行する".to_owned(), "other".to_owned()],
13329        );
13330        q.actions.insert("resume で続行する".to_owned(), action);
13331        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
13332            .unwrap();
13333        q
13334    }
13335
13336    fn held_task_with(run: &str) -> Task {
13337        let mut t = task();
13338        t.runs = vec![run.to_owned()];
13339        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
13340        t
13341    }
13342
13343    fn resume_action(run: &str) -> ask::ChoiceAction {
13344        ask::ChoiceAction::Resume { run: run.into() }
13345    }
13346
13347    #[test]
13348    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
13349        let home = crate::run::test_home();
13350        for parked in [false, true] {
13351            let mut t = task();
13352            t.start("A".into());
13353            t.start("B".into());
13354            assert_eq!(t.runs, vec!["A", "B"]);
13355            t.start("A".into());
13356            let mut resumed = run_state(RunStatus::Blocked);
13357            resumed.id = "A".into();
13358            resumed.parked = parked;
13359            resumed.driver_exited = true;
13360            t.hold_machine(Some("resumed run stopped".into()));
13361            let q = action_question("A", resume_action("A"));
13362            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13363            assert_eq!(
13364                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
13365                    assert_eq!(id, "A");
13366                    Ok(resumed.clone())
13367                }),
13368                ActionDecision::Resume("A".into())
13369            );
13370            assert_eq!(
13371                action_standing(&t, &action_question("B", resume_action("B"))),
13372                ActionStanding::Stale
13373            );
13374            t.release_operator("cli", None);
13375            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
13376                assert_eq!(id, "A");
13377                Ok(resumed.clone())
13378            });
13379            assert_eq!(
13380                choose_starter(None, false, unfinished.as_deref()),
13381                Starter::Resume("A".into())
13382            );
13383            assert_eq!(t.runs, vec!["B", "A"]);
13384        }
13385    }
13386
13387    #[test]
13388    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
13389        let home = crate::run::test_home();
13390        let mut state = crate::land::tests::repair_state(true, true);
13391        state.status = RunStatus::Landing;
13392        state.parked = true;
13393        state.driver_exited = true;
13394        let mut q = ask::Question::new(
13395            state.id.clone(),
13396            land::APPROVAL_NODE.into(),
13397            "land".into(),
13398            "Merge?".into(),
13399            String::new(),
13400            vec![land::APPROVE.into(), land::HOLD.into()],
13401        );
13402        q.id = state.id.clone();
13403        state.land_approval = Some(crate::run::LandApproval {
13404            question: q.id.clone(),
13405            head: "current-head".into(),
13406        });
13407        assert!(land::upgrade_repair_choice(&mut q, &state));
13408        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13409        let mut task = held_task_with(&state.id);
13410        task.status = TaskStatus::Parked;
13411        assert_eq!(
13412            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
13413            ActionDecision::Resume(state.id.clone())
13414        );
13415        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13416        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
13417        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
13418        assert_eq!(
13419            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
13420            ActionDecision::Resume(state.id.clone()),
13421            "a repair answer newer than the manual hold resumes the existing owner"
13422        );
13423        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
13424        for answered_at in [q.answered_at, None] {
13425            let mut older = q.clone();
13426            older.answered_at = answered_at;
13427            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
13428                panic!("a later manual hold must prevent dispatch")
13429            });
13430            let ActionDecision::Refuse(reason) = refused else {
13431                panic!("expected an actionable refusal, got {refused:?}");
13432            };
13433            assert!(reason.contains("later operator decision"));
13434            assert!(reason.contains(&format!("magi task release {}", task.id)));
13435        }
13436        task.operator_decided_at = None;
13437        let mut superseded = state.clone();
13438        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
13439        assert_eq!(
13440            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
13441            ActionDecision::Stale
13442        );
13443        for case in 1..4 {
13444            let mut changed = state.clone();
13445            match case {
13446                1 => changed.status = RunStatus::Blocked,
13447                2 => changed.released_to = Some("new-owner".into()),
13448                _ => changed.land_approval.as_mut().unwrap().head.clear(),
13449            }
13450            assert!(matches!(
13451                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
13452                ActionDecision::Refuse(_)
13453            ));
13454        }
13455        assert!(matches!(
13456            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
13457                "missing owner"
13458            )),
13459            ActionDecision::Refuse(_)
13460        ));
13461        task.runs.push("replacement".into());
13462        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
13463        assert_eq!(
13464            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
13465                "old owner must not load"
13466            )),
13467            ActionDecision::Stale
13468        );
13469    }
13470
13471    #[test]
13472    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
13473        let mut state = crate::land::tests::repair_state(true, true);
13474        state.status = RunStatus::Landing;
13475        state.parked = true;
13476        state.driver_exited = true;
13477        let mut q = ask::Question::new(
13478            state.id.clone(),
13479            land::APPROVAL_NODE.into(),
13480            "land".into(),
13481            "Merge?".into(),
13482            String::new(),
13483            vec![land::APPROVE.into(), land::HOLD.into()],
13484        );
13485        q.id = state.id.clone();
13486        state.land_approval = Some(crate::run::LandApproval {
13487            question: q.id.clone(),
13488            head: "current-head".into(),
13489        });
13490        state.save().unwrap();
13491        land::upgrade_repair_choice(&mut q, &state);
13492        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13493        Questions::open().put(&mut q).unwrap();
13494        let tmp = tempfile::tempdir().unwrap();
13495        let queue = Queue::at(tmp.path().join("queue"));
13496        let mut task = held_task_with(&state.id);
13497        task.status = TaskStatus::Parked;
13498        queue.put(&mut task).unwrap();
13499        let empty = Arc::new(tokio::sync::Semaphore::new(0));
13500        let free = Arc::new(tokio::sync::Semaphore::new(1));
13501        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
13502        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
13503        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
13504        assert!(claim.permit.is_some());
13505        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
13506        drop(claim);
13507        Questions::open()
13508            .update(&q.id, |q| {
13509                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
13510                Ok(())
13511            })
13512            .unwrap();
13513        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
13514        assert!(claim.permit.is_none());
13515        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
13516    }
13517
13518    #[test]
13519    fn decide_action_resumes_only_the_latest_resumable_run() {
13520        let home = crate::run::test_home();
13521        let t = held_task_with("r1");
13522        let q = action_question("r1", resume_action("r1"));
13523        let load = |s: RunState| move |_: &str| Ok(s);
13524        assert_eq!(
13525            decide_action(
13526                &home,
13527                &t,
13528                &q,
13529                &PHRASES_EN,
13530                load(run_state(RunStatus::Blocked))
13531            ),
13532            ActionDecision::Resume("r1".into())
13533        );
13534        // Not the latest run of the task.
13535        let q_other = action_question("r1", resume_action("r0"));
13536        assert!(matches!(
13537            decide_action(
13538                &home,
13539                &t,
13540                &q_other,
13541                &PHRASES_EN,
13542                load(run_state(RunStatus::Blocked))
13543            ),
13544            ActionDecision::Refuse(_)
13545        ));
13546        // A finished run cannot make progress.
13547        assert!(matches!(
13548            decide_action(
13549                &home,
13550                &t,
13551                &q,
13552                &PHRASES_EN,
13553                load(run_state(RunStatus::Ready))
13554            ),
13555            ActionDecision::Refuse(_)
13556        ));
13557        // A released one either.
13558        let mut released = run_state(RunStatus::Blocked);
13559        released.released_to = Some("elsewhere".into());
13560        assert!(matches!(
13561            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
13562            ActionDecision::Refuse(_)
13563        ));
13564        // Unreadable state is a refusal, never a fresh competition.
13565        assert!(matches!(
13566            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
13567            ActionDecision::Refuse(_)
13568        ));
13569    }
13570
13571    #[test]
13572    fn decide_action_ignores_a_question_about_an_earlier_run() {
13573        let home = crate::run::test_home();
13574        let mut t = held_task_with("r1");
13575        t.runs.push("r2".to_owned());
13576        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13577        assert_eq!(
13578            decide_action(
13579                &home,
13580                &t,
13581                &action_question("r1", ask::ChoiceAction::Done),
13582                &PHRASES_EN,
13583                never
13584            ),
13585            ActionDecision::Stale
13586        );
13587    }
13588
13589    #[test]
13590    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
13591        let home = crate::run::test_home();
13592        let mut t = held_task_with("r1");
13593        let never = |_: &str| -> Result<RunState> { bail!("not read") };
13594        assert_eq!(
13595            decide_action(
13596                &home,
13597                &t,
13598                &action_question("r1", ask::ChoiceAction::Requeue),
13599                &PHRASES_EN,
13600                never
13601            ),
13602            ActionDecision::Requeue
13603        );
13604        let done_q = action_question("r1", ask::ChoiceAction::Done);
13605        assert_eq!(
13606            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13607            ActionDecision::Done
13608        );
13609        t.mark_action_applied(&done_q.id);
13610        assert_eq!(
13611            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
13612            ActionDecision::Skip
13613        );
13614
13615        // A plain answer (no action for that label) does nothing.
13616        let mut plain = action_question("r1", ask::ChoiceAction::Done);
13617        plain.actions.clear();
13618        assert_eq!(
13619            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
13620            ActionDecision::Skip
13621        );
13622        // A running task is left alone.
13623        let mut running = held_task_with("r1");
13624        running.status = TaskStatus::Running;
13625        assert_eq!(
13626            decide_action(
13627                &home,
13628                &running,
13629                &action_question("r1", ask::ChoiceAction::Done),
13630                &PHRASES_EN,
13631                never
13632            ),
13633            ActionDecision::Skip
13634        );
13635    }
13636
13637    #[test]
13638    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
13639        crate::run::pin_test_home();
13640        for legacy in [false, true] {
13641            let dir = tempfile::tempdir().unwrap();
13642            let queue = Queue::at(dir.path().join("queue"));
13643            let questions = Questions::at(dir.path().join("questions"));
13644            let run = "20260101-000000-hold";
13645            let mut task = held_task_with(run);
13646            task.status = TaskStatus::Parked;
13647            let mut q = ask::Question::new(
13648                run.into(),
13649                land::APPROVAL_NODE.into(),
13650                "land".into(),
13651                "Repair?".into(),
13652                String::new(),
13653                vec![land::REPAIR.into()],
13654            );
13655            q.actions.insert(land::REPAIR.into(), resume_action(run));
13656            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13657            // Deterministically order the answer before the actual manual hold.
13658            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13659            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
13660            questions.put(&mut q).unwrap();
13661            task.hold_manual(Some("Keep this PR paused".into()));
13662            if legacy {
13663                task.hold_source = None;
13664            }
13665            queue.put(&mut task).unwrap();
13666
13667            apply_task_choice_actions(&queue, &questions, dir.path());
13668            let after = queue.get(&task.id).unwrap();
13669            assert!(after.operator_held());
13670            assert_eq!(after.hold_source, task.hold_source);
13671            assert_eq!(after.operator_decided_at, task.operator_decided_at);
13672            assert_eq!(after.runs, task.runs);
13673            assert_eq!(after.instruction, task.instruction);
13674            assert!(after.resume_override.is_none());
13675            assert!(after.action_applied(&q.id));
13676            let reason = after.hold_reason.as_deref().unwrap();
13677            assert!(reason.starts_with("Keep this PR paused"));
13678            assert!(reason.contains("later operator decision"));
13679            assert!(reason.contains(&format!("magi task release {}", task.id)));
13680
13681            for recovery in [
13682                crate::conduct::Recovery::Review,
13683                crate::conduct::Recovery::Requeue,
13684            ] {
13685                crate::conduct::apply(
13686                    &queue,
13687                    &questions,
13688                    &crate::conduct::Verdict {
13689                        decisions: vec![crate::conduct::Decision {
13690                            id: task.id.clone(),
13691                            recovery: Some(recovery),
13692                            ..Default::default()
13693                        }],
13694                    },
13695                )
13696                .unwrap();
13697            }
13698            // Reconciliation is idempotent, and automatic recovery cannot
13699            // reopen this owner after it observes the rejected repair answer.
13700            apply_task_choice_actions(&queue, &questions, dir.path());
13701            let still_held = queue.get(&task.id).unwrap();
13702            assert!(still_held.operator_held());
13703            assert_eq!(still_held.hold_reason, after.hold_reason);
13704            assert_eq!(still_held.runs, task.runs);
13705            assert!(still_held.review_branch.is_none());
13706            assert!(!still_held.fresh_start);
13707            assert!(queue.next_runnable().is_none());
13708        }
13709    }
13710
13711    #[test]
13712    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
13713        for held in [false, true] {
13714            for retry in [false, true] {
13715                let dir = tempfile::tempdir().unwrap();
13716                let queue = Queue::at(dir.path().join("queue"));
13717                let questions = Questions::at(dir.path().join("questions"));
13718                let home = dir.path().join("home");
13719                let mut t = task();
13720                if held {
13721                    t.hold_machine(Some("driver state unknown".into()));
13722                }
13723                queue.put(&mut t).unwrap();
13724                let verdict = serde_json::from_value(serde_json::json!({
13725                    "decisions": [{
13726                        "id": t.id,
13727                        "question": "Driver state unknown; retry the checks or hold?",
13728                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
13729                        "actions": {
13730                            "daemon: recheck and retry": {"do": "requeue"},
13731                            "daemon: hold the task": {"do": "hold"}
13732                        }
13733                    }]
13734                }))
13735                .unwrap();
13736                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
13737                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13738                let mut q = questions.list().pop().unwrap();
13739                let choice = if retry {
13740                    "daemon: recheck and retry"
13741                } else {
13742                    "daemon: hold the task"
13743                };
13744                assert_eq!(q.actions.len(), 2);
13745                q.answer(ask::Answer::Choice(choice.into())).unwrap();
13746                questions.put(&mut q).unwrap();
13747
13748                // A Web answer does not remove the deputy's fresh lease.
13749                questions.beat(&q.id, ask::WaiterKind::Deputy);
13750                for _ in 0..2 {
13751                    resolve_blockers(&queue, &questions);
13752                    apply_task_choice_actions(&queue, &questions, &home);
13753                    let waiting = queue.get(&t.id).unwrap();
13754                    assert_eq!(waiting.status, TaskStatus::Blocked);
13755                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
13756                    assert!(waiting.answers.is_empty());
13757                    assert!(!waiting.action_applied(&q.id));
13758                    assert!(runnable(&queue).is_empty());
13759                    let free = Arc::new(tokio::sync::Semaphore::new(1));
13760                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
13761                }
13762                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13763
13764                // Releasing the blocker and applying the operation share one save.
13765                resolve_blockers(&queue, &questions);
13766                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
13767                apply_task_choice_actions(&queue, &questions, &home);
13768                let after = queue.get(&t.id).unwrap();
13769                assert_eq!(
13770                    after.status,
13771                    if retry {
13772                        TaskStatus::Queued
13773                    } else {
13774                        TaskStatus::Held
13775                    }
13776                );
13777                assert!(after.action_applied(&q.id));
13778                assert_eq!(after.operator_held(), !retry);
13779                assert_eq!(after.answers.len(), 1);
13780
13781                // A later operator decision must not replay this answer.
13782                let mut changed = after;
13783                if retry {
13784                    changed.hold_manual(Some("later hold".into()));
13785                } else {
13786                    changed.release_operator("test", None);
13787                }
13788                let expected = changed.status;
13789                queue.put(&mut changed).unwrap();
13790                apply_task_choice_actions(&queue, &questions, &home);
13791                assert_eq!(queue.get(&t.id).unwrap().status, expected);
13792            }
13793        }
13794    }
13795
13796    #[test]
13797    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
13798        let dir = tempfile::tempdir().unwrap();
13799        let queue = Queue::at(dir.path().join("queue"));
13800        let questions = Questions::at(dir.path().join("questions"));
13801        let home = dir.path().join("home");
13802        let mut state = run_state(RunStatus::Blocked);
13803        state.id = "20260101-000000-act1".to_owned();
13804        state.save_under(&home).unwrap();
13805
13806        let mut t = held_task_with(&state.id);
13807        queue.put(&mut t).unwrap();
13808        let mut q = action_question(&state.id, resume_action(&state.id));
13809        questions.put(&mut q).unwrap();
13810
13811        apply_task_choice_actions(&queue, &questions, &home);
13812        let after = queue.get(&t.id).unwrap();
13813        assert_eq!(after.status, TaskStatus::Queued);
13814        assert!(!after.fresh_start);
13815        assert!(after.action_applied(&q.id));
13816        let pin = after.resume_override.clone().unwrap();
13817        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
13818        assert!(pin.forced);
13819
13820        // Held again later: the same answer does not release it a second time.
13821        let mut again = queue.get(&t.id).unwrap();
13822        again.hold_machine(Some("later".into()));
13823        queue.put(&mut again).unwrap();
13824        apply_task_choice_actions(&queue, &questions, &home);
13825        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13826    }
13827
13828    #[test]
13829    fn a_delivered_answer_is_still_acted_on_exactly_once() {
13830        let dir = tempfile::tempdir().unwrap();
13831        let queue = Queue::at(dir.path().join("queue"));
13832        let questions = Questions::at(dir.path().join("questions"));
13833        let home = dir.path().join("home");
13834        let mut state = run_state(RunStatus::Blocked);
13835        state.id = "20260101-000000-act2".to_owned();
13836        state.save_under(&home).unwrap();
13837
13838        let mut t = held_task_with(&state.id);
13839        queue.put(&mut t).unwrap();
13840        let mut q = action_question(&state.id, resume_action(&state.id));
13841        q.answer_delivered = true;
13842        questions.put(&mut q).unwrap();
13843
13844        // Delivered, and the agent then died: the task is still held, so the
13845        // chosen action applies.
13846        apply_task_choice_actions(&queue, &questions, &home);
13847        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13848        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
13849
13850        // Held again: the same answer does nothing a second time.
13851        let mut again = queue.get(&t.id).unwrap();
13852        again.hold_machine(Some("later".into()));
13853        queue.put(&mut again).unwrap();
13854        apply_task_choice_actions(&queue, &questions, &home);
13855        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13856    }
13857
13858    #[test]
13859    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
13860        let dir = tempfile::tempdir().unwrap();
13861        let queue = Queue::at(dir.path().join("queue"));
13862        let questions = Questions::at(dir.path().join("questions"));
13863        let home = dir.path().join("home");
13864        let mut state = run_state(RunStatus::Blocked);
13865        state.id = "20260101-000000-act3".to_owned();
13866        state.save_under(&home).unwrap();
13867        let mut t = held_task_with(&state.id);
13868        queue.put(&mut t).unwrap();
13869        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
13870        questions.put(&mut q).unwrap();
13871
13872        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
13873        apply_task_choice_actions(&queue, &questions, &home);
13874        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13875
13876        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
13877        apply_task_choice_actions(&queue, &questions, &home);
13878        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
13879    }
13880
13881    #[test]
13882    fn action_standing_tells_the_reasons_apart() {
13883        let mut t = held_task_with("r1");
13884        let q = action_question("r1", ask::ChoiceAction::Requeue);
13885        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13886        let mut plain = q.clone();
13887        plain.actions.clear();
13888        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
13889
13890        // Applied wins over everything, even a running task.
13891        t.mark_action_applied(&q.id);
13892        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
13893
13894        // A newer attempt running: the old question is Stale, not Busy.
13895        let mut t = held_task_with("r1");
13896        t.start("r2".to_owned());
13897        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
13898        // The same question about the latest run just waits.
13899        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
13900        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13901        t.status = TaskStatus::Blocked;
13902        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
13903
13904        // A conductor question is keyed by the task, never stale.
13905        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
13906        c.node = crate::conduct::NODE.to_owned();
13907        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
13908        assert!(!ActionStanding::Busy.daemon_owns());
13909    }
13910
13911    #[test]
13912    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
13913        let dir = tempfile::tempdir().unwrap();
13914        let queue = Queue::at(dir.path().join("queue"));
13915        let questions = Questions::at(dir.path().join("questions"));
13916        let home = dir.path().join("home");
13917        let mut state = run_state(RunStatus::Blocked);
13918        state.id = "20260101-000000-act4".to_owned();
13919        state.save_under(&home).unwrap();
13920        let mut t = held_task_with(&state.id);
13921        t.status = TaskStatus::Running;
13922        queue.put(&mut t).unwrap();
13923        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13924        q.cwd = Some(dir.path().display().to_string());
13925        questions.put(&mut q).unwrap();
13926
13927        // While the task runs the daemon will not act, so the waiter still
13928        // delivers the word to the dead asker's seat ...
13929        let running = queue.get(&t.id).unwrap();
13930        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
13931        assert!(matches!(
13932            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
13933            crate::waiter::Action::Deliver(_)
13934        ));
13935        // ... and the daemon waits while the task runs, then applies once.
13936        apply_task_choice_actions(&queue, &questions, &home);
13937        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
13938        let mut back = queue.get(&t.id).unwrap();
13939        back.hold_machine(Some("later".into()));
13940        queue.put(&mut back).unwrap();
13941        apply_task_choice_actions(&queue, &questions, &home);
13942        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
13943        let mut again = queue.get(&t.id).unwrap();
13944        again.hold_machine(Some("again".into()));
13945        queue.put(&mut again).unwrap();
13946        apply_task_choice_actions(&queue, &questions, &home);
13947        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
13948    }
13949}