Skip to main content

magi/
daemon.rs

1//! The unattended scheduler and independently leased task workers.
2//!
3//! The scheduler chooses tasks and execution lanes; a detached worker owns each
4//! queue claim, graph driver and outcome settlement. Replacing the scheduler
5//! reconstructs occupied slots from live worker jobs, without touching their
6//! attempts, passes or paid agent calls. Finite maintenance jobs follow the same
7//! lifetime rule. Explicit parking is durable control, never an upgrade step.
8//!
9//! # A crashed worker is legible
10//!
11//! A task is written `Running`, with its run id, before graph execution. The
12//! worker keeps its claim until the outcome is recorded. Recovery requires both
13//! no live worker reservation and an obtainable task claim, and settles the
14//! saved run through the same policy as a live finish. A scheduler's missing
15//! heartbeat alone is never evidence that a run died.
16//!
17//! # Retries are bounded
18//!
19//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
20//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
21//! exception is a run that ended `Stalled`: the panel collapsed because the
22//! agent CLIs hit their quota, which is a fact about the machine and not about
23//! the task, so it must not spend an attempt. Without that exception a quota
24//! outage would quietly hold the entire backlog, and the operator would come
25//! back to a reset quota and nothing left that the loop is willing to run.
26
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Mutex, MutexGuard};
31use std::time::Duration;
32
33use anyhow::{Context, Result, bail};
34use jiff::Timestamp;
35use serde::{Deserialize, Serialize};
36use tokio::sync::Notify;
37
38use crate::ask::{self, Questions};
39use crate::clean;
40use crate::conduct::Conductor;
41use crate::config::{Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{Queue, Task, TaskStatus};
46use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
47use crate::triage;
48
49/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
50pub const SCHEMA: u32 = 1;
51
52/// How often the status file is refreshed. A reader treats a status file older
53/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
54/// that a busy daemon is never mistaken for a dead one.
55pub const HEARTBEAT: Duration = Duration::from_secs(5);
56
57/// How old a heartbeat may be before a reader calls the daemon dead. Six
58/// missed beats: long enough to survive a slow filesystem, short enough that
59/// a crashed daemon is not still reported as running a task.
60///
61/// The single threshold every reader shares — the web UI's `/api/health` and
62/// `magi doctor` both call [`Reading::running`] rather than each comparing
63/// against their own copy of this number, so a crashed daemon cannot look
64/// alive on one screen and dead on another.
65pub const STALE_SECS: i64 = 30;
66
67/// Default queue poll interval.
68pub const POLL: Duration = Duration::from_secs(5);
69
70/// How old a claim has to be before startup sweeps it. Longer than any run
71/// this graph plausibly takes, so a sweep cannot pull a task out from under a
72/// daemon that is merely slow.
73pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
74
75/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
76/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
77///
78/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
79/// poll, by attempting the task's own claim: a dead pid is proof enough for
80/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
81/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
82/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
83/// age instead, since there is nothing else to check (see
84/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
85/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
86/// task `running` — see
87/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
88/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
89/// conductor well before the mechanical six-hour sweep would, and thirty
90/// minutes is comfortably below `STALE_CLAIM` while still being generous
91/// enough that a task merely late to publish its first [`HEARTBEAT`] is
92/// never mistaken for abandoned.
93pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
94
95/// What the loop is working on, for the status file.
96#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(default)]
98pub struct Current {
99    /// Worker reservation that produced this claim; absent on legacy drivers.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub worker: Option<String>,
102    /// Task id being run.
103    pub task: String,
104    /// Run id the task produced.
105    pub run: String,
106}
107
108/// The daemon's liveness, published to `<home>/daemon.json`.
109///
110/// This is the only interface between the loop and the web UI, which is why it
111/// carries `updated_at` as well as `started_at`: a reader cannot tell a
112/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
113/// can compare the heartbeat against the clock.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Status {
116    /// On-disk format version.
117    pub schema: u32,
118    /// Process id, so a human can find or kill the daemon.
119    pub pid: u32,
120    /// When this process started.
121    pub started_at: Timestamp,
122    /// Last heartbeat.
123    pub updated_at: Timestamp,
124    /// True when the queue has nothing runnable.
125    pub idle: bool,
126    /// Every task and run currently in flight. More than one entry means the
127    /// loop is driving more than one run at once — see
128    /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
129    /// nothing is running, so a reader never has to treat "no field" and "an
130    /// empty list" as two different kinds of idle.
131    pub current: Vec<Current>,
132    /// Tasks that reached a terminal status in this process.
133    pub completed: usize,
134    /// Queue polls since start, so a wedged loop shows up as a frozen count.
135    pub polls: u64,
136    /// Effective startup capabilities of the question recovery loops.
137    #[serde(default)]
138    pub question_recovery: Option<crate::question_delivery::Recovery>,
139    /// Independent-worker control protocol supported by this scheduler.
140    #[serde(default)]
141    pub worker_protocol: Option<u32>,
142}
143
144impl Status {
145    /// A fresh, idle status for this process.
146    #[must_use]
147    pub fn new() -> Self {
148        let now = Timestamp::now();
149        Self {
150            schema: SCHEMA,
151            pid: std::process::id(),
152            started_at: now,
153            updated_at: now,
154            idle: true,
155            current: Vec::new(),
156            completed: 0,
157            polls: 0,
158            question_recovery: None,
159            worker_protocol: Some(1),
160        }
161    }
162}
163
164impl Default for Status {
165    fn default() -> Self {
166        Self::new()
167    }
168}
169
170/// How the loop should behave.
171#[derive(Debug, Clone, Serialize, Deserialize)]
172#[serde(default)]
173pub struct Opts {
174    /// Repository used by tasks that name none.
175    pub repo: PathBuf,
176    /// Explicit `magi.toml`, instead of the discovered layer stack.
177    pub config: Option<PathBuf>,
178    /// Queue poll interval.
179    pub poll: Duration,
180    /// Attempts a task gets before it is held for a human.
181    pub max_attempts: usize,
182    /// Drain what is runnable now, then return, instead of waiting for more.
183    pub once: bool,
184    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
185    pub merge: Option<String>,
186    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
187    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
188    /// `None` resolves to [`crate::run::default_worktree_root`] - the
189    /// operator's real `~/wt/<repo>` - the same way a run with no
190    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
191    /// that does not own that directory (a test, an embedding that manages
192    /// worktrees itself) must set this, or every idle tick reclaims worktrees
193    /// out from under whoever actually does.
194    pub worktrees_root: Option<PathBuf>,
195}
196
197impl Default for Opts {
198    fn default() -> Self {
199        Self {
200            repo: PathBuf::from("."),
201            config: None,
202            poll: POLL,
203            max_attempts: 2,
204            once: false,
205            merge: None,
206            worktrees_root: None,
207        }
208    }
209}
210
211impl Opts {
212    fn absolute(&self) -> Result<Self> {
213        let mut opts = self.clone();
214        opts.repo = std::path::absolute(&opts.repo)?;
215        opts.config = opts
216            .config
217            .as_deref()
218            .map(std::path::absolute)
219            .transpose()?;
220        opts.worktrees_root = opts
221            .worktrees_root
222            .as_deref()
223            .map(std::path::absolute)
224            .transpose()?;
225        Ok(opts)
226    }
227}
228
229/// How many runs a plain `usize` from config may drive concurrently, floored
230/// at one. A `0` in a config file would otherwise stall the loop entirely -
231/// no runnable task could ever start - which is never what an operator who
232/// wrote `0` meant.
233fn max_concurrent(n: usize) -> usize {
234    n.max(1)
235}
236
237/// Where the status file lives.
238#[must_use]
239pub fn status_path() -> PathBuf {
240    crate::run::home().join("daemon.json")
241}
242
243/// Publish the status file for this process.
244pub fn write_status(status: &Status) -> Result<()> {
245    write_status_to(&status_path(), status)
246}
247
248/// Publish a status to an explicit path.
249///
250/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
251/// on every health poll and must never see a half-written one.
252pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
253    if let Some(parent) = path.parent() {
254        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
255    }
256    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
257    let tmp = path.with_extension("json.tmp");
258    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
259    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
260    Ok(())
261}
262
263/// Delete the status file. Called on the way out so a clean exit reads as
264/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
265pub fn clear_status() {
266    clear_status_at(&status_path());
267}
268
269/// Delete a status file at an explicit path, so the loop's teardown and
270/// [`clear_status`] cannot drift apart: the loop is handed the path it
271/// published to, and a test can watch a temp file disappear.
272fn clear_status_at(path: &Path) {
273    let _ = std::fs::remove_file(path);
274}
275
276/// A cooperative stop, shared with whoever asked the loop to run.
277///
278/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
279/// Ctrl-C listener and the web UI keep others, and every clone points at the
280/// same flag. There is no channel because there is nothing to send — the only
281/// message is "stop", it is idempotent, and a flag cannot be missed by a
282/// receiver that was not listening yet.
283///
284/// A stop ends scheduler dispatch promptly. Its busy snapshot is observational:
285/// detached task workers keep their own lifetimes and ownership after this
286/// handle's scheduler exits.
287#[derive(Debug, Clone, Default)]
288pub struct Stop {
289    /// Set once, never cleared: a stop is not something an operator takes back
290    /// half way through, and a clearable flag would let a start racing a stop
291    /// resurrect a loop that is already unwinding.
292    stopped: Arc<AtomicBool>,
293    /// Live task workers observed by the scheduler's latest dispatch snapshot.
294    busy: Arc<std::sync::atomic::AtomicUsize>,
295    /// Wakes the idle wait. Without this a stop would not be seen until the
296    /// poll interval elapsed, and an operator tapping stop on a phone would
297    /// watch a button do nothing for five seconds.
298    wake: Arc<Notify>,
299    /// Handed to the run in flight, so a stop can also mean "park at the next
300    /// node boundary" instead of "finish the whole competition first".
301    pause: crate::graph::Pause,
302}
303
304impl Stop {
305    /// A stop nobody has asked for yet.
306    #[must_use]
307    pub fn new() -> Self {
308        Self::default()
309    }
310
311    /// Ask the loop to stop. Idempotent, and safe to call before the loop
312    /// starts: the flag is checked before the first poll.
313    pub fn stop(&self) {
314        self.stopped.store(true, Ordering::SeqCst);
315        // `notify_one` rather than `notify_waiters` because the loop may not be
316        // parked yet: this stores a permit, so a wait that registers a moment
317        // later returns at once instead of sleeping out the whole interval.
318        self.wake.notify_one();
319    }
320
321    /// Has a stop been asked for?
322    #[must_use]
323    pub fn stopped(&self) -> bool {
324        self.stopped.load(Ordering::SeqCst)
325    }
326
327    /// Whether a requested scheduler retirement still has an active snapshot.
328    /// Workers continue independently after the scheduler has retired.
329    #[must_use]
330    pub fn finishing(&self) -> bool {
331        self.stopped() && self.busy_now()
332    }
333
334    /// Ask the loop to stop *and* the run in flight to park at its next node
335    /// boundary.
336    ///
337    /// Unlike plain stop, explicit park asks workers to checkpoint at their
338    /// existing safe boundaries. Binary replacement never needs a park.
339    pub fn park(&self, cause: crate::run::ParkCause) {
340        self.pause.park_for(cause);
341        self.stop();
342    }
343
344    /// Has a park been asked for?
345    #[must_use]
346    pub fn parking(&self) -> bool {
347        self.pause.parked()
348    }
349
350    /// The pause handle to give a runner.
351    #[must_use]
352    pub fn pause(&self) -> crate::graph::Pause {
353        self.pause.clone()
354    }
355
356    /// Whether the scheduler's latest snapshot contains active task workers.
357    #[must_use]
358    pub fn busy_now(&self) -> bool {
359        self.busy.load(Ordering::SeqCst) > 0
360    }
361
362    /// Wait out one poll interval, returning early once a stop is asked for.
363    async fn idle(&self, poll: Duration) {
364        tokio::select! {
365            () = tokio::time::sleep(poll) => {}
366            () = self.wake.notified() => {}
367        }
368    }
369}
370
371/// The daemon's published state, read permissively.
372///
373/// This mirrors [`Status`], but is a separate declaration on purpose: every
374/// field defaults, so a status file from an older or newer magi still yields
375/// a usable reading — one this build has never heard of — instead of a parse
376/// error that hides the daemon entirely.
377#[derive(Debug, Clone, Default, Deserialize)]
378#[serde(default)]
379pub struct Reading {
380    /// Format version the daemon claims.
381    pub schema: u32,
382    /// Daemon process id, for an operator who wants to stop it.
383    pub pid: Option<u32>,
384    /// When that process started.
385    pub started_at: Option<Timestamp>,
386    /// Last heartbeat. Absent means the file is unusable, hence not running.
387    pub updated_at: Option<Timestamp>,
388    /// True when the queue had nothing runnable at the last poll.
389    pub idle: bool,
390    /// What the daemon is working on. Empty means idle; more than one entry
391    /// means more than one run is in flight at once.
392    ///
393    /// `deserialize_with` rather than the plain derive: a daemon started
394    /// before this field became a list is still out there writing the old
395    /// shape — a single `{"task":...,"run":...}` object, or its absence —
396    /// on every heartbeat until it is restarted, and a live process reading
397    /// that file during the rollout must still see it as running rather than
398    /// as absent. A bare type change here would fail the whole struct's
399    /// deserialization on a type mismatch, defeating the permissiveness this
400    /// type exists for.
401    #[serde(deserialize_with = "de_current")]
402    pub current: Vec<Current>,
403    /// Tasks this daemon process has finished.
404    pub completed: u64,
405    /// Queue polls this daemon process has made.
406    pub polls: u64,
407    /// Effective startup capabilities of the question recovery loops.
408    #[serde(default)]
409    pub question_recovery: Option<crate::question_delivery::Recovery>,
410    /// Independent-worker control protocol, absent on legacy embedded loops.
411    pub worker_protocol: Option<u32>,
412}
413
414/// Accept the old single-`Current`-or-absent shape as well as the current
415/// list, so a reader never has to know which build wrote the file.
416fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
417where
418    D: serde::Deserializer<'de>,
419{
420    #[derive(Deserialize)]
421    #[serde(untagged)]
422    enum Shape {
423        Many(Vec<Current>),
424        One(Current),
425    }
426    Ok(
427        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
428            Shape::Many(v) => v,
429            Shape::One(c) => vec![c],
430        }),
431    )
432}
433
434impl Reading {
435    /// Seconds since the last heartbeat, or `None` when there has never been
436    /// one.
437    #[must_use]
438    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
439        self.updated_at
440            .map(|at| (now.as_second() - at.as_second()).max(0))
441    }
442
443    /// Whether the loop counts as running: a heartbeat no older than
444    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
445    /// progress hours after the daemon that owned it was killed.
446    #[must_use]
447    pub fn running(&self, now: Timestamp) -> bool {
448        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
449    }
450}
451
452/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
453/// usable there.
454///
455/// Missing, half-written and unparseable all collapse to `None`, because the
456/// only question a reader asks is whether a daemon is alive, and a file it
457/// cannot read is not evidence that one is.
458#[must_use]
459pub fn read_status(home: &Path) -> Option<Reading> {
460    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
461    serde_json::from_str(&body).ok()
462}
463
464/// Read-only evidence of runs owned by a live daemon or independent worker.
465///
466/// CLI, sandboxed conversation controls and Web cleanup share this observation.
467/// A stale daemon heartbeat does not invalidate a worker's OS-held lease.
468/// Starting reservations and unknown worker state remain protected; observing
469/// them never creates, reconciles or archives files in the worker store.
470/// Callers interested in one identity use [`is_working_on`] or
471/// [`is_working_on_task`].
472#[must_use]
473pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
474    let mut current = read_status(home)
475        .filter(|reading| reading.running(now))
476        .map(|reading| reading.current)
477        .unwrap_or_default();
478    let workers = crate::worker::observe_active(home).and_then(|jobs| {
479        jobs.into_iter()
480            .filter(|job| job.kind == "task")
481            .map(|job| {
482                let request: TaskWorker = serde_json::from_value(job.payload)?;
483                let run = Queue::at(request.queue)
484                    .get(&request.task)
485                    .ok()
486                    .and_then(|task| task.runs.last().cloned())
487                    .unwrap_or_default();
488                Ok(Current {
489                    worker: Some(job.id),
490                    task: request.task,
491                    run,
492                })
493            })
494            .collect::<Result<Vec<_>>>()
495    });
496    match workers {
497        Ok(workers) => {
498            for worker in workers {
499                if !current.iter().any(|claim| {
500                    claim.task == worker.task
501                        && claim.run == worker.run
502                        && claim.worker == worker.worker
503                }) {
504                    current.push(worker);
505                }
506            }
507        }
508        Err(error) => {
509            // This API gates destructive cleanup. Unknown worker ownership
510            // protects every known task/run instead of pretending it is idle.
511            tracing::error!("cannot determine active workers: {error:#}");
512            current.extend(
513                Queue::at(home.join("queue"))
514                    .list()
515                    .into_iter()
516                    .map(|task| Current {
517                        worker: None,
518                        task: task.id,
519                        run: task.runs.last().cloned().unwrap_or_default(),
520                    }),
521            );
522            current.extend(
523                crate::run::list_ids_in(&home.join("runs"))
524                    .into_iter()
525                    .map(|run| Current {
526                        worker: None,
527                        task: String::new(),
528                        run,
529                    }),
530            );
531        }
532    }
533    current
534}
535
536/// Whether a live daemon is working on this run at this moment.
537#[must_use]
538pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
539    current_work(home, now).iter().any(|c| c.run == run)
540}
541
542/// Admission may ignore only this process's confirmed worker reservation.
543/// Keep anonymous/legacy daemon claims and every other worker, even for the
544/// same task. The run's execution lease and process identity are checked by
545/// the caller under the owner lock as well.
546pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
547    // A helper or test may inherit an identity from a different run store.
548    // That identity grants no exception here; retain all ownership evidence.
549    let same_home = std::env::var_os("MAGI_WORKER_HOME")
550        .is_some_and(|worker_home| Path::new(&worker_home) == home);
551    let caller = if same_home {
552        crate::worker::current_job(home)?
553    } else {
554        None
555    }
556    .filter(|job| {
557        job.kind == "task"
558            && job.status == crate::worker::Status::Running
559            && job.pid == Some(std::process::id())
560    });
561    Ok(other_claims_run(
562        &current_work(home, now),
563        run,
564        caller.as_ref().map(|job| job.id.as_str()),
565    ))
566}
567
568fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
569    claims
570        .iter()
571        .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
572}
573
574/// Whether a live daemon is working on a run whose short id is this one.
575///
576/// For a worktree that has no run record to compare against at all -
577/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
578/// id is not available to hand to [`is_working_on`]. The short id is: a run's
579/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
580/// and it is exactly the gap between the daemon claiming a task and
581/// `RunState::new` saving the first `run.json` that this exists to protect -
582/// a run genuinely in flight but invisible to a scan of `runs/`.
583#[must_use]
584pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
585    current_work(home, now)
586        .iter()
587        .any(|c| crate::run::short_of(&c.run) == short)
588}
589
590/// Whether a live daemon is working on this task at this moment.
591#[must_use]
592pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
593    current_work(home, now).iter().any(|c| c.task == task)
594}
595
596/// Remove claim files whose owner is provably dead, or that have simply
597/// outlived `older_than`, and return the task ids swept.
598///
599/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
600/// destructor, and the orphaned `.lock` file would make its task permanently
601/// unclaimable — the backlog would stop for good at exactly the task that was
602/// in flight when the machine went down.
603///
604/// The pid recorded in the lock is the authority whenever it can be read at
605/// all; age is only a fallback for when it cannot be.
606///
607/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
608///   full stop — dead sweeps the lock immediately, regardless of age; alive
609///   protects it, regardless of age. This is what lets a lock be reclaimed in
610///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
611///   before this daemon even started, next to a `queued` task, no longer has
612///   to sit for six hours before anything notices its owner is gone.
613/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
614///   falls back to `older_than`, since there is nothing else to check.
615///
616/// Age must never override a *positive* liveness confirmation. `sweep`
617/// polls concurrently with independently running task workers. A worker may
618/// legitimately run longer than `older_than`; its live pid must still protect
619/// its claim. Age alone must never turn that claim into a second task attempt,
620/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
621/// to a second attempt — two `Runner`s writing the same `run.json` and the
622/// same worktree at once. `pid_alive` answering "alive" for anything it
623/// cannot determine (a live process, a pid this build cannot check, one
624/// under another account) is exactly what keeps that path from ever
625/// firing on a guess.
626///
627/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
628/// output unreadable must not be license to guess, and the risk of an
629/// unparseable lock outliving a genuinely dead owner is bounded by an order
630/// of magnitude above any plausible run rather than by a positive check.
631///
632/// Runs on every poll, not only at startup — a daemon up for days must keep
633/// noticing a lock some other, now-dead, daemon left behind just as readily
634/// as one it trips over on the way up.
635pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
636    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
637}
638
639/// [`sweep_stale_claims`] with its process-query boundary supplied by the
640/// caller. This keeps the lock policy testable where process listing is
641/// unavailable, while production still uses the platform query above.
642fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
643where
644    F: Fn(u32) -> bool,
645{
646    let this_process = std::process::id();
647    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
648        .into_iter()
649        .flatten()
650        .flatten()
651        .map(|e| e.path())
652        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
653        .filter(|p| {
654            match std::fs::read_to_string(p)
655                .ok()
656                .and_then(|body| body.trim().parse::<u32>().ok())
657            {
658                // This process wrote it and is asking the question right
659                // now, so it is definitionally still alive - settled without
660                // spawning a helper process at all.
661                Some(pid) if pid == this_process => false,
662                Some(pid) => !pid_alive(pid),
663                None => p
664                    .metadata()
665                    .and_then(|m| m.modified())
666                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
667                    .is_ok_and(|age| age >= older_than),
668            }
669        })
670        .filter(|p| std::fs::remove_file(p).is_ok())
671        .filter_map(|p| {
672            p.file_stem()
673                .and_then(|s| s.to_str())
674                .map(std::borrow::ToOwned::to_owned)
675        })
676        .collect();
677    swept.sort_unstable();
678    swept
679}
680
681/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
682/// no live daemon's heartbeat naming it? Deterministic — no model call, and
683/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
684/// shown.
685fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
686    task.status == TaskStatus::Running
687        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
688        && !is_working_on_task(home, &task.id, now)
689}
690
691/// Every task [`is_stalled`] right now — "止まったタスク" in
692/// `crate::conduct`'s vocabulary.
693fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
694    queue
695        .list()
696        .into_iter()
697        .filter(|t| is_stalled(t, home, now))
698        .collect()
699}
700
701/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
702/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
703/// `Failed`-and-so-also-runnable: a task that already attempted and lost
704/// belongs in [`finished_tasks`], where the question is a recovery, not a
705/// dependency.
706fn queued_tasks(queue: &Queue) -> Vec<Task> {
707    queue
708        .list()
709        .into_iter()
710        .filter(|t| t.status == TaskStatus::Queued)
711        .collect()
712}
713
714/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
715/// タスク" in `crate::conduct`'s vocabulary.
716fn finished_tasks(queue: &Queue) -> Vec<Task> {
717    queue
718        .list()
719        .into_iter()
720        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
721        .collect()
722}
723
724/// Deterministically resolve `Task::blocked_by`: a dependency task that
725/// reached `Done`, or a question that was answered, is removed — no model
726/// involved, on every poll. An answered question's content is copied onto
727/// the task ([`Task::record_answer`]) before its id is dropped, so it
728/// reaches the next `crate::conduct` prompt and the next run's instruction
729/// (see [`instruction_for`]) rather than only clearing the block.
730///
731/// A `blocked_by` id that names neither an existing task nor an existing
732/// question - `magi task rm` (or an operator by hand) deleted it while this
733/// task was still waiting - is caught before any of that: it can never
734/// become `Done` or `Answered`, so the ordinary loop below would otherwise
735/// leave the task `blocked` forever with nothing to notice. Such a task is
736/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
737/// which puts it in front of `crate::triage::run_once`'s own walk the next
738/// time it runs - see that module's doc for why the choice is "ask a human",
739/// never "assume the missing dependency was satisfied and unblock anyway".
740fn resolve_blockers(queue: &Queue, questions: &Questions) {
741    for listed in queue.list() {
742        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
743            continue;
744        }
745        let Ok(_claim) = queue.claim(&listed.id) else {
746            continue;
747        };
748        let Ok(mut task) = queue.get(&listed.id) else {
749            continue;
750        };
751        if task.status != TaskStatus::Blocked {
752            continue;
753        }
754        // A dependency deleted on purpose is released, not held - and before
755        // the missing check, so a pass that races the delete (or a claim that
756        // made `Queue::remove` skip this task) settles it quietly.
757        let deleted = queue.apply_deleted_blockers(&mut task, questions);
758        if !deleted.is_empty() {
759            record(queue, &mut task);
760            for id in &deleted {
761                queue.note_dependency_deleted(&task, id);
762            }
763            if task.status != TaskStatus::Blocked {
764                continue;
765            }
766        }
767        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
768        if !missing.is_empty() {
769            let language = language_of(&task, Path::new("."));
770            let mut cause = missing.clone();
771            cause.sort();
772            cause.dedup();
773            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
774            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
775                &task.blocked_by,
776                &missing,
777                &language,
778            )));
779            record(queue, &mut task);
780            continue;
781        }
782        // A conductor question nobody answered in time is retired by the
783        // waiter, and nothing else would ever move the task it blocks.
784        if let Some(q) = task.blocked_by.iter().find_map(|id| {
785            let crate::queue::Dependency::Question(full) =
786                crate::queue::dependency(queue, questions, id)
787            else {
788                return None;
789            };
790            questions.get(&full).ok().filter(|q| {
791                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
792            })
793        }) {
794            let language = language_of(&task, Path::new("."));
795            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
796            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
797            record(queue, &mut task);
798            continue;
799        }
800        let mut changed = false;
801        for id in task.blocked_by.clone() {
802            let resolved = crate::queue::dependency(queue, questions, &id);
803            if let crate::queue::Dependency::Task(full) = &resolved {
804                if queue
805                    .get(full)
806                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
807                {
808                    task.unblock(&id);
809                    changed = true;
810                }
811                continue;
812            }
813            if let crate::queue::Dependency::Question(full) = resolved
814                && let Ok(q) = questions.get(&full)
815                && q.status == ask::QuestionStatus::Answered
816            {
817                // The action sweep releases conductor blockers atomically
818                // with their selected operation. A fresh deputy lease must
819                // never leave an answered hold temporarily runnable.
820                if q.node == crate::conduct::NODE
821                    && q.chosen_action().is_some()
822                    && !task.action_applied(&q.id)
823                {
824                    continue;
825                }
826                let answer = match &q.answer {
827                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
828                    None => String::new(),
829                };
830                task.record_answer(q.summary.clone(), answer);
831                task.unblock(&id);
832                changed = true;
833            }
834        }
835        if changed {
836            record(queue, &mut task);
837        }
838    }
839}
840
841/// The `hold_reason` of a task whose conductor question went unanswered.
842fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
843    if crate::lang::is_japanese(language) {
844        format!(
845            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
846            q.short(),
847            q.summary
848        )
849    } else {
850        format!(
851            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
852            q.short(),
853            q.summary
854        )
855    }
856}
857
858/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
859/// for several unrelated reasons, and the waiter must not read them alike.
860#[derive(Debug, Clone, Copy, PartialEq, Eq)]
861pub(crate) enum ActionStanding {
862    /// The answer carries no action: the waiter delivers it as before.
863    NoAction,
864    /// The daemon will apply it (not applied, task idle, current attempt).
865    Pending,
866    /// Already applied (`Task::actions_applied`): the daemon has acted, so
867    /// delivering the word to the old seat would run it beside the new work.
868    Applied,
869    /// The question is about an earlier attempt than the task's latest.
870    Stale,
871    /// The task is running / blocked / done: the daemon defers for now.
872    Busy,
873}
874
875impl ActionStanding {
876    /// The daemon has acted or will act: the waiter must not deliver.
877    pub(crate) fn daemon_owns(self) -> bool {
878        matches!(self, Self::Pending | Self::Applied | Self::Stale)
879    }
880}
881
882/// Classify `q`'s chosen action against `task`. `Stale` is judged before
883/// `Busy`: a question about an earlier attempt must be stopped even while a
884/// newer competition is running.
885pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
886    if q.chosen_action().is_none() {
887        ActionStanding::NoAction
888    } else if task.action_applied(&q.id) {
889        ActionStanding::Applied
890    } else if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
891        ActionStanding::Stale
892    } else if matches!(
893        task.status,
894        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
895    ) {
896        ActionStanding::Busy
897    } else {
898        ActionStanding::Pending
899    }
900}
901
902/// What [`decide_action`] concluded about one answered question.
903#[derive(Debug, Clone, PartialEq, Eq)]
904enum ActionDecision {
905    /// Nothing to do now (no action, already applied, or the task is busy).
906    Skip,
907    /// Continue the named run instead of competing again.
908    Resume(String),
909    /// Requeue as a fresh competition.
910    Requeue,
911    /// Hold the task by explicit operator choice.
912    Hold,
913    /// Close the task as done.
914    Done,
915    /// The question is about an earlier attempt than the task's latest; it
916    /// is recorded as handled and changes nothing.
917    Stale,
918    /// The action cannot be carried out; hold the task and say why. Never
919    /// falls back to something else, because the operator chose this one.
920    Refuse(String),
921}
922
923/// Decide what the choice answered on `q` means for `task`. Pure: `load`
924/// reads a run's state, as with [`unfinished_run_with`].
925///
926/// `Resume` only fires on the task's *latest* run, and only while that run
927/// could actually make progress ([`RunStatus::resumable`], not released, review
928/// budget left); an answer naming anything else is refused rather than
929/// reinterpreted as a fresh competition.
930fn decide_action<F>(task: &Task, q: &ask::Question, p: &Phrases, load: F) -> ActionDecision
931where
932    F: FnOnce(&str) -> Result<RunState>,
933{
934    let Some(action) = q.chosen_action() else {
935        return ActionDecision::Skip;
936    };
937    if task.action_applied(&q.id)
938        || matches!(
939            task.status,
940            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
941        )
942    {
943        return ActionDecision::Skip;
944    }
945    // A question about an earlier attempt must not act on a newer one. A
946    // conductor question is keyed by the task id, not a run, so it is exempt.
947    if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
948        return ActionDecision::Stale;
949    }
950    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
951    let stopping = q.node == land::APPROVAL_NODE
952        && q.resolution()
953            .as_deref()
954            .is_some_and(crate::merge_decision::stops);
955    // Repair and stop actions are new decisions on an existing approval card. A
956    // manual hold before that answer must not discard it just because the
957    // card predates the hold. Keep the older policy for other choice actions.
958    let decision_at = if repair || stopping {
959        q.answered_at.unwrap_or(q.asked_at)
960    } else {
961        q.asked_at
962    };
963    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
964        return if repair || stopping {
965            ActionDecision::Refuse(format!(
966                "{} 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 {}`",
967                if repair { "repair" } else { "stop" },
968                q.id,
969                q.run,
970                task.id
971            ))
972        } else {
973            ActionDecision::Stale
974        };
975    }
976    match action {
977        a if a.maintenance() => ActionDecision::Skip,
978        ask::ChoiceAction::ResumeRun { .. }
979        | ask::ChoiceAction::ReleaseTask { .. }
980        | ask::ChoiceAction::RerunChecks { .. }
981        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
982        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
983        ask::ChoiceAction::Hold => ActionDecision::Hold,
984        ask::ChoiceAction::Done => ActionDecision::Done,
985        ask::ChoiceAction::Resume { run } => {
986            if task.runs.last() != Some(run) {
987                return ActionDecision::Refuse((p.resume_not_latest)(
988                    q.short(),
989                    ask::short_id(run),
990                ));
991            }
992            match load(run) {
993                Ok(s) if stopping => {
994                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
995                        || !s
996                            .land_approval
997                            .as_ref()
998                            .is_some_and(|binding| binding.question == q.id)
999                    {
1000                        ActionDecision::Stale
1001                    } else if s.liveness(false) == Liveness::Live {
1002                        ActionDecision::Skip
1003                    } else if s.status == RunStatus::Landing
1004                        && !s.released()
1005                        && s.retired_to.is_none()
1006                    {
1007                        ActionDecision::Resume(run.clone())
1008                    } else {
1009                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1010                    }
1011                }
1012                Ok(s)
1013                    if q.node == land::APPROVAL_NODE
1014                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1015                {
1016                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1017                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1018                    {
1019                        // A live/manual driver already consumed or superseded
1020                        // this answer. Do not hold its fresh approval wait.
1021                        ActionDecision::Stale
1022                    } else if s.liveness(false) == Liveness::Live {
1023                        ActionDecision::Skip
1024                    } else if s.status != RunStatus::Landing
1025                        || s.released()
1026                        || s.reviews.is_empty()
1027                        || !implementers_match(task, &s)
1028                        || !s
1029                            .land_approval
1030                            .as_ref()
1031                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1032                    {
1033                        ActionDecision::Refuse(format!(
1034                            "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",
1035                            q.id, run, run
1036                        ))
1037                    } else {
1038                        ActionDecision::Resume(run.clone())
1039                    }
1040                }
1041                Ok(s) if s.liveness(false) == Liveness::Live => {
1042                    ActionDecision::Refuse("run already has a live driver".into())
1043                }
1044                Ok(s) if crate::handover::can_resume(&s) => ActionDecision::Resume(run.clone()),
1045                Ok(_) => ActionDecision::Refuse((p.resume_cannot_progress)(
1046                    q.short(),
1047                    ask::short_id(run),
1048                )),
1049                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1050                    q.short(),
1051                    ask::short_id(run),
1052                    &format!("{e:#}"),
1053                )),
1054            }
1055        }
1056    }
1057}
1058
1059/// The fixed prose the daemon writes into [`Task::last_error`] and
1060/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1061/// `triage::Wording` and `land::Words`: only English and Japanese are
1062/// translated, anything else falls back to English.
1063///
1064/// Rendered when the reason is *generated*, so a reason keeps the language it
1065/// was written in if the setting changes later. The notification frame
1066/// (`Task <id> is held:`) is not here and stays English.
1067///
1068/// Deliberately **not** translated, because other code reads them back by
1069/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1070/// and `gate red`. IDs, node names, paths and external error text are embedded
1071/// as they are.
1072struct Phrases {
1073    /// `{}` = status label, then the detail.
1074    graph_stopped: fn(&str, &str) -> String,
1075    quorum_lost: &'static str,
1076    /// Followed by the seats' names.
1077    quota_took_out: &'static str,
1078    /// Followed by the status label.
1079    run_ended: &'static str,
1080    /// Followed by the question's short id.
1081    waiting_for_answer: &'static str,
1082    recovered_running: &'static str,
1083    no_run_to_recover: &'static str,
1084    could_not_start: &'static str,
1085    resume_not_latest: fn(&str, &str) -> String,
1086    resume_cannot_progress: fn(&str, &str) -> String,
1087    resume_unreadable: fn(&str, &str, &str) -> String,
1088    /// A takeover refusal: the operator-facing text. English is the error's own
1089    /// `Display`; a translation keeps the machine detail apart in parentheses.
1090    handover_refused: fn(&crate::handover::Refused) -> String,
1091    /// Appended to a refused handover's hold reason (leading space included).
1092    handover_hint: &'static str,
1093    /// (seats that never answered, review rounds) for the review loop's
1094    /// "refusing to call it clean" stop.
1095    reviewers_never_answered: fn(usize, usize) -> String,
1096}
1097
1098const PHRASES_EN: Phrases = Phrases {
1099    graph_stopped: |status, detail| {
1100        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1101    },
1102    quorum_lost: "the judging panel lost its quorum",
1103    quota_took_out: "; quota took out ",
1104    run_ended: "run ended ",
1105    waiting_for_answer: " - waiting for operator answer to question ",
1106    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1107    no_run_to_recover: "task was `running` with no live daemon and no readable \
1108                        run to recover; held for a human to check what happened",
1109    could_not_start: "could not start the run: ",
1110    resume_not_latest: |q, run| {
1111        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1112    },
1113    resume_cannot_progress: |q, run| {
1114        format!("question {q} asked to resume run {run}, which cannot make progress")
1115    },
1116    resume_unreadable: |q, run, e| {
1117        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1118    },
1119    handover_refused: |r| r.to_string(),
1120    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1121    reviewers_never_answered: |missing, rounds| {
1122        format!(
1123            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1124             refusing to call it clean"
1125        )
1126    },
1127};
1128
1129const PHRASES_JA: Phrases = Phrases {
1130    graph_stopped: |status, detail| {
1131        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1132    },
1133    quorum_lost: "審査パネルが定足数を失いました",
1134    quota_took_out: "。クォータで脱落: ",
1135    run_ended: "run 終了: ",
1136    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1137    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1138    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1139                        何が起きたか人が確認するため保留にしました",
1140    could_not_start: "run を開始できませんでした: ",
1141    resume_not_latest: |q, run| {
1142        format!(
1143            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1144        )
1145    },
1146    resume_cannot_progress: |q, run| {
1147        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません")
1148    },
1149    resume_unreadable: |q, run, e| {
1150        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1151    },
1152    handover_refused: |r| {
1153        use crate::handover::Refused;
1154        match r {
1155            Refused::Foreign { branch, path, why } => format!(
1156                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1157                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1158                 から、やり直してください(詳細: {why})"
1159            ),
1160            Refused::Unsafe { branch, path, why } => format!(
1161                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1162                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1163                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1164            ),
1165            Refused::ReleaseFailed { branch, path, run } => format!(
1166                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1167                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1168                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1169            ),
1170        }
1171    },
1172    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1173    reviewers_never_answered: |missing, rounds| {
1174        format!(
1175            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1176             クリーンとは認めません"
1177        )
1178    },
1179};
1180
1181fn phrases(language: &str) -> &'static Phrases {
1182    if crate::lang::is_japanese(language) {
1183        &PHRASES_JA
1184    } else {
1185        &PHRASES_EN
1186    }
1187}
1188
1189/// The language of the repository a task belongs to, read best-effort for the
1190/// paths that have no run (and so no config of their own) to ask. An unreadable
1191/// config is English, not an error: a hold reason must still get written.
1192fn language_of(task: &Task, fallback: &Path) -> String {
1193    crate::lang::of_repo(&repo_for(task, fallback))
1194}
1195
1196/// The task an answered question speaks for: the one whose runs include the
1197/// question's run, or - for a conductor question, filed under the task's own
1198/// id - the task with that id.
1199pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1200    if q.node == crate::conduct::NODE {
1201        return tasks.iter().find(|t| t.id == q.run);
1202    }
1203    tasks.iter().find(|t| t.runs.contains(&q.run))
1204}
1205
1206/// Legacy conductor prose never becomes a maintenance command by inference.
1207/// Replace unsupported open labels under the question lock before dispatch.
1208fn repair_choice_offers(questions: &Questions) {
1209    for q in questions.list().into_iter().filter(|q| {
1210        q.status.open()
1211            && q.node == crate::conduct::NODE
1212            && q.choices
1213                .iter()
1214                .any(|c| crate::choice_effect::describe(q, c).is_none())
1215    }) {
1216        let _ = questions.update(&q.id, |current| {
1217            if current.status.open() {
1218                crate::choice_effect::executable_conductor(current);
1219                if let Some(deputy) = &mut current.deputy {
1220                    deputy.brief = crate::deputy::brief(
1221                        &current.run,
1222                        &current.detail,
1223                        &current.choices,
1224                        &current.actions,
1225                    );
1226                }
1227            }
1228            Ok(())
1229        });
1230    }
1231}
1232
1233/// Apply answered typed choices. Only the daemon calls this in production;
1234/// deputies settle the question and never execute its actions.
1235pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1236    apply_maintenance_choices(queue, questions, home).await;
1237    apply_task_choice_actions(queue, questions, home);
1238}
1239
1240/// Apply bounded maintenance effects independently of question ownership: a
1241/// release watcher need not have a queue task, and a predecessor is another run.
1242async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1243    for q in questions.list() {
1244        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1245            continue;
1246        };
1247        // Receipt paths use question IDs, whose format is independent of run
1248        // IDs. Apply the question store's filename safety rule to both eras.
1249        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1250            continue;
1251        }
1252        let dir = home.join("choice-actions");
1253        if std::fs::create_dir_all(&dir).is_err() {
1254            continue;
1255        }
1256        let Ok(lock) = std::fs::OpenOptions::new()
1257            .create(true)
1258            .truncate(false)
1259            .write(true)
1260            .open(dir.join(format!("{}.lock", q.id)))
1261        else {
1262            continue;
1263        };
1264        if crate::pr_head::try_lock_file(&lock).is_err() {
1265            continue;
1266        }
1267        let fresh = !home
1268            .join("choice-actions")
1269            .join(format!("{}.json", q.id))
1270            .exists();
1271        let result = async {
1272            let receipt = dir.join(format!("{}.json", q.id));
1273            if receipt.exists() {
1274                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1275                anyhow::ensure!(
1276                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1277                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1278                );
1279                return Ok::<_, anyhow::Error>(());
1280            }
1281            // Never retry an uncertain external effect. The receipt is written
1282            // before calling gh, exactly like release_watch's rerun record.
1283            let record = |status: &str| -> anyhow::Result<()> {
1284                let tmp = receipt.with_extension("tmp");
1285                std::fs::write(
1286                    &tmp,
1287                    serde_json::to_vec(&serde_json::json!({
1288                        "action": action, "status": status,
1289                    }))?,
1290                )?;
1291                std::fs::rename(tmp, &receipt)?;
1292                Ok(())
1293            };
1294            let applied = async {
1295                match action {
1296                    ask::ChoiceAction::ResumeRun { run } => {
1297                        crate::resume::validate(home, run)?;
1298                        record("started")?;
1299                        if !crate::resume::pin_queued(queue, run, Some(q.asked_at), Some(&q.id))? {
1300                            crate::resume::validate_unqueued(home, run)?;
1301                            crate::resume::start(home, run.clone()).await?;
1302                        }
1303                    }
1304                    ask::ChoiceAction::ReleaseTask {
1305                        task,
1306                        held_at,
1307                        reason,
1308                    } => {
1309                        anyhow::ensure!(
1310                            queue.resolve_id(task)? == *task,
1311                            "task action requires an exact task ID"
1312                        );
1313                        let _claim = queue.claim(task)?;
1314                        let mut task = queue.get(task)?;
1315                        if task.action_applied(&q.id) {
1316                            return Ok(());
1317                        }
1318                        // Filing this conductor question temporarily wraps the
1319                        // original hold in a Blocked state. Restore only that
1320                        // exact blocker on the local copy before checking the
1321                        // hold binding; unrelated waits never authorize release.
1322                        if q.node == crate::conduct::NODE
1323                            && q.run == task.id
1324                            && task.status == TaskStatus::Blocked
1325                            && task.blocked_from == Some(TaskStatus::Held)
1326                            && task.blocked_by.as_slice() == [q.id.as_str()]
1327                        {
1328                            task.unblock(&q.id);
1329                        }
1330                        anyhow::ensure!(
1331                            task.status == TaskStatus::Held
1332                                && task.held_at == Some(*held_at)
1333                                && task.hold_reason.as_deref() == reason.as_deref()
1334                                && task.operator_decided_at.is_none_or(|at| at <= q.asked_at),
1335                            "task no longer has the hold this question names"
1336                        );
1337                        task.release_operator("choice", Some(&q.id));
1338                        task.mark_action_applied(&q.id);
1339                        queue.put(&mut task)?;
1340                    }
1341                    ask::ChoiceAction::AbandonRun { run } => {
1342                        record("started")?;
1343                        crate::driver::abandon_proven_dead(home, run)?;
1344                    }
1345                    ask::ChoiceAction::RerunChecks {
1346                        repo,
1347                        pr,
1348                        head,
1349                        runs,
1350                    } => {
1351                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1352                            .await?;
1353                    }
1354                    _ => unreachable!(),
1355                }
1356                Ok::<_, anyhow::Error>(())
1357            }
1358            .await;
1359            match applied {
1360                Ok(()) => record("applied"),
1361                Err(e) => {
1362                    record(&format!("refused or failed: {e:#}"))?;
1363                    Err(e)
1364                }
1365            }
1366        }
1367        .await;
1368        // Retire the originating blocker as well as the target operation.
1369        // A foreign resume leaves its issuer held instead of competing beside
1370        // the execution just started. Other successful maintenance lets the
1371        // original task retry its normal, guarded path.
1372        if home
1373            .join("choice-actions")
1374            .join(format!("{}.json", q.id))
1375            .exists()
1376            && let Some(listed) = task_of_question(&queue.list(), &q)
1377            && !listed.action_applied(&q.id)
1378            && let Ok(_claim) = queue.claim(&listed.id)
1379            && let Ok(mut origin) = queue.get(&listed.id)
1380        {
1381            if !origin.operator_held()
1382                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1383                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1384            {
1385                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1386                    origin.hold_machine(Some(format!(
1387                        "Maintenance choice {} settled; inspect its target before releasing this task",
1388                        q.id
1389                    )));
1390                } else {
1391                    origin.unblock(&q.id);
1392                }
1393            }
1394            origin.mark_action_applied(&q.id);
1395            let _ = queue.put(&mut origin);
1396        }
1397        if let Err(e) = result
1398            && fresh
1399        {
1400            notices::raise_in(
1401                home,
1402                Notice::warn(
1403                    &format!("action:{}", q.id),
1404                    format!("Choice action {} was not completed: {e:#}", q.id),
1405                )
1406                .link(if q.run_names_task() {
1407                    Link::Task { id: q.run.clone() }
1408                } else {
1409                    Link::Run { id: q.run.clone() }
1410                }),
1411            );
1412        }
1413    }
1414}
1415
1416/// Rerun the named failed workflow runs of a pull request, each at most once
1417/// per `request` (a question id, or a chat operation identity). The head,
1418/// lifecycle and failed state are re-read from the forge first; `started` is
1419/// called once those checks pass and before the first external call, and the
1420/// ledger entry is written before every `gh` call, so an uncertain result is
1421/// never repeated automatically.
1422pub(crate) async fn rerun_checks_once(
1423    home: &Path,
1424    request: &str,
1425    repo: &Path,
1426    pr: &str,
1427    head: &str,
1428    runs: &[String],
1429    started: impl FnOnce() -> anyhow::Result<()>,
1430) -> anyhow::Result<()> {
1431    use crate::release_watch::{GhForge, ReleaseForge};
1432    anyhow::ensure!(
1433        !runs.is_empty()
1434            && runs.len() <= 20
1435            && runs
1436                .iter()
1437                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1438            && !pr.starts_with('-'),
1439        "invalid rerun targets"
1440    );
1441    let snap = GhForge.snapshot(repo, pr).await?;
1442    anyhow::ensure!(
1443        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1444        "pull request head or lifecycle changed"
1445    );
1446    anyhow::ensure!(
1447        runs.iter().all(|r| snap
1448            .checks
1449            .iter()
1450            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1451        "named workflow is no longer failed on this pull request"
1452    );
1453    started()?;
1454    let dir = home.join("choice-actions");
1455    std::fs::create_dir_all(&dir)?;
1456    let rerun_lock = std::fs::OpenOptions::new()
1457        .create(true)
1458        .truncate(false)
1459        .write(true)
1460        .open(dir.join("reruns.lock"))?;
1461    crate::pr_head::try_lock_file(&rerun_lock)?;
1462    let ledger = dir.join("reruns.json");
1463    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1464        serde_json::from_slice(&std::fs::read(&ledger)?)?
1465    } else {
1466        Default::default()
1467    };
1468    for run in runs {
1469        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1470        if !recorded.insert(key) {
1471            continue;
1472        }
1473        let tmp = ledger.with_extension("tmp");
1474        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1475        std::fs::rename(tmp, &ledger)?;
1476        GhForge.rerun(repo, run).await?;
1477    }
1478    Ok(())
1479}
1480
1481/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1482///
1483/// Runs on every poll before the conductor looks at the queue. The task is
1484/// re-read under its claim, so a task somebody completed or held by hand in
1485/// the meantime is judged on what it is now. `Resume` releases the task and
1486/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1487/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1488/// ordinary `unfinished_run` logic resumes that same run.
1489pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1490    let tasks = queue.list();
1491    for q in questions.list() {
1492        // Dismissal is committed by the question writer, never a resume.
1493        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1494            continue;
1495        }
1496        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1497            continue;
1498        }
1499        let Some(listed) = task_of_question(&tasks, &q) else {
1500            if q.node == land::APPROVAL_NODE
1501                && q.resolution().as_deref().is_some_and(|choice| {
1502                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1503                })
1504            {
1505                notices::raise_in(
1506                    home,
1507                    Notice::warn(
1508                        &format!("repair-owner:{}", q.id),
1509                        format!(
1510                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1511                            q.run, q.run
1512                        ),
1513                    ).link(Link::Run { id: q.run.clone() }),
1514                );
1515            }
1516            continue;
1517        };
1518        if listed.action_applied(&q.id) {
1519            continue;
1520        }
1521        let Ok(_claim) = queue.claim(&listed.id) else {
1522            continue;
1523        };
1524        let Ok(mut task) = queue.get(&listed.id) else {
1525            continue;
1526        };
1527        // Work only on this local copy until the action can be committed.
1528        // In particular, a fresh lease below leaves the persisted task blocked.
1529        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1530            let blockers: Vec<_> = task
1531                .blocked_by
1532                .iter()
1533                .filter(|id| {
1534                    crate::queue::dependency(queue, questions, id)
1535                        == crate::queue::Dependency::Question(q.id.clone())
1536                })
1537                .cloned()
1538                .collect();
1539            if !blockers.is_empty() {
1540                for id in blockers {
1541                    task.unblock(&id);
1542                }
1543                let answer = match &q.answer {
1544                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1545                    None => String::new(),
1546                };
1547                task.record_answer(q.summary.clone(), answer);
1548            }
1549        }
1550        let language = language_of(&task, Path::new("."));
1551        let decision = decide_action(&task, &q, phrases(&language), |id| {
1552            RunState::load_under(id, home)
1553        });
1554        let ran = matches!(
1555            decision,
1556            ActionDecision::Resume(_)
1557                | ActionDecision::Requeue
1558                | ActionDecision::Hold
1559                | ActionDecision::Done
1560        );
1561        if ran && asker_may_still_read(questions, &q, home) {
1562            // The asking process or its seat can still take the word; act
1563            // once it has gone quiet. Bound on the remaining window: the
1564            // check is not atomic with the write below, so an asker that
1565            // takes the word in between (at most one poll, never more than
1566            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1567            // and `Task::actions_applied` under the claim keeps the action to
1568            // one application. The waiter does not deliver an answer that
1569            // carries an action (`waiter::decide_owned`), so it cannot race.
1570            continue;
1571        }
1572        let done = matches!(decision, ActionDecision::Done);
1573        match decision {
1574            ActionDecision::Skip => continue,
1575            ActionDecision::Resume(run) => {
1576                task.release_operator("choice", Some(&q.id));
1577                task.resume_override = Some(crate::queue::OperatorResume {
1578                    question_id: q.id.clone(),
1579                    at: Timestamp::now(),
1580                    conductor_rehold: None,
1581                    forced: true,
1582                    pinned_run: Some(run),
1583                });
1584            }
1585            ActionDecision::Stale => {}
1586            ActionDecision::Requeue => {
1587                task.release_operator("choice-requeue", Some(&q.id));
1588                task.requeue();
1589            }
1590            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1591            ActionDecision::Done => task.succeed(),
1592            ActionDecision::Refuse(why) => {
1593                if task.operator_held() {
1594                    // A rejected answer does not release the operator's hold
1595                    // or reclassify it as recoverable by the conductor.
1596                    task.hold_reason = Some(match task.hold_reason.take() {
1597                        Some(reason) => format!("{reason}\n\n{why}"),
1598                        None => why,
1599                    });
1600                } else {
1601                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1602                    task.hold_machine(Some(why));
1603                }
1604                notices::raise(
1605                    Notice::warn(
1606                        &format!("action:{}", q.id),
1607                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1608                    )
1609                    .link(Link::Task {
1610                        id: task.id.clone(),
1611                    }),
1612                );
1613            }
1614        }
1615        task.mark_action_applied(&q.id);
1616        // The applied id travels with the transition, so a failed save loses
1617        // neither and the answer is acted on at the next poll.
1618        record(queue, &mut task);
1619        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1620            supersede_prior_runs(&task, home);
1621        }
1622        // Delivery is only a note of who has read the answer; the task's own
1623        // mark above is the authority. Best effort.
1624        let _ = questions.update(&q.id, |r| {
1625            r.answer_delivered = true;
1626            Ok(())
1627        });
1628    }
1629}
1630
1631/// Whether something may still read the answer to `q`: a fresh lease, or the
1632/// asking seat still listed as active in its run (its CLI can outlive the
1633/// `magi ask` that was killed).
1634fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1635    let now = Timestamp::now();
1636    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1637        return true;
1638    }
1639    q.node != crate::conduct::NODE
1640        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1641            s.seats_active()
1642                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1643        })
1644}
1645
1646/// Retire an unanswered conductor question after its task no longer refers to
1647/// it. Conductor questions use the task id in `Question::run`, so run-based
1648/// cleanup cannot observe a manual release or completion.
1649///
1650/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1651/// own question also carries a `run`, and a run id that happens to collide
1652/// with some task's id is not this loop's business — only a conductor
1653/// question actually uses the task id that way. One `Questions::list()` scan
1654/// is taken up front and matched against the in-memory task set, rather than
1655/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1656fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1657    let tasks = queue.list();
1658    let by_id: std::collections::BTreeMap<&str, &Task> =
1659        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1660    let referenced: Vec<&str> = tasks
1661        .iter()
1662        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1663        .collect();
1664
1665    for mut question in questions.list() {
1666        if !question.status.open() || question.node != crate::conduct::NODE {
1667            continue;
1668        }
1669        // Keep questions a task still names, including when the reference
1670        // moved to a dependent task.
1671        // Preserve even ambiguous references: retiring a possibly referenced
1672        // question is unsafe until the operator disambiguates it.
1673        if referenced
1674            .iter()
1675            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1676        {
1677            continue;
1678        }
1679        let Some(task) = by_id.get(question.run.as_str()) else {
1680            continue;
1681        };
1682        question.abandon(format!(
1683            "task {} no longer waits for this answer",
1684            task.short()
1685        ));
1686        if let Err(e) = questions.put(&mut question) {
1687            tracing::warn!(
1688                "could not retire question {} for task {}: {e:#}",
1689                question.short(),
1690                task.short()
1691            );
1692        }
1693    }
1694}
1695
1696/// What a finished run tells the queue about the task it came from.
1697///
1698/// A struct rather than a fourth and fifth boolean argument: the two flags
1699/// answer different questions about the same run, and a call site passing
1700/// `(…, true, false)` is one transposition away from refunding attempts
1701/// forever.
1702#[derive(Debug, Clone, Copy)]
1703pub struct Verdict {
1704    /// Where the graph stopped.
1705    pub status: RunStatus,
1706    /// The run opened a pull request.
1707    pub left_pr: bool,
1708    /// At least one seat was lost to a rate limit.
1709    pub quota_hit: bool,
1710    /// The run parked at a node boundary because it was asked to.
1711    pub parked: bool,
1712    /// The run never produced a single candidate a judge could look at.
1713    ///
1714    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1715    /// still have another candidate worth judging, in which case the loss was
1716    /// not the reason nothing came of the run. This is `true` only when the
1717    /// implement wave ended with nothing viable at all.
1718    pub no_viable_candidates: bool,
1719}
1720
1721/// Record a finished run against the task it came from.
1722///
1723/// Kept pure and separate from the loop because this mapping *is* the retry
1724/// policy, and a policy that can only be exercised by spawning a graph is a
1725/// policy nobody checks. The table:
1726///
1727/// | run status                           | task becomes        | attempt spent |
1728/// |---------------------------------------|---------------------|---------------|
1729/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1730/// | `Merged`, `Ready`                      | `Done`               | yes          |
1731/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1732/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1733/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1734/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1735/// | `Blocked` with a PR                    | `Held`               | yes          |
1736/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1737/// | `VerifiedNoop`                          | `Held`               | yes          |
1738/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1739///
1740/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1741/// deliberately: every candidate agreeing there is nothing to write is not a
1742/// machine fact about a rate limit, it is an unverified claim about the
1743/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1744/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1745/// claim could be wrong (a misread instruction, a stale check), and closing
1746/// the task automatically on an implementer's say-so would be the exact
1747/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1748/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1749/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1750/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1751/// claim regardless of whether the one already-spent attempt is refunded, and
1752/// [`Task::release`] resets the count to zero anyway the moment a human looks
1753/// at the evidence and lets it run again.
1754///
1755/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1756/// twice, together. A quorum lost to rate limits is a property of the machine
1757/// and not of the task, so the attempt is refunded and a reset quota picks
1758/// the work up where it stopped — and that is just as true when every
1759/// implement seat lost the same race and `after_implement` bails with nothing
1760/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1761/// machine fact. The `no_viable_candidates` guard is what keeps that row
1762/// narrow: a `Failed` run that produced a real candidate which then lost for
1763/// some other reason still spends the attempt, exactly like the quorum lost
1764/// to judges that answered with the wrong shape is ordinary flakiness, and
1765/// refunding *that* takes the bound off the retry loop entirely: run e633
1766/// stalled with `quota: []` after two judges wrote unusable JSON, was
1767/// refunded, and the next attempt paid for a fresh hour-long implement wave
1768/// before it could fail the same way. `max_attempts` exists precisely so
1769/// that cannot repeat forever.
1770///
1771/// A non-terminal status means `execute` returned while the graph was still
1772/// mid-flight, which is a bug rather than a verdict; it is treated as a
1773/// failure so that a task cannot loop on it either.
1774///
1775/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1776/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1777pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1778    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1779}
1780
1781/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1782fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1783    // A parked run is the operator's own doing, and its work is intact on
1784    // disk. The task goes back in line with its attempt refunded so the next
1785    // loop resumes the same run - which `one_task` prefers over competing
1786    // again - and so that swapping the binary a few times cannot exhaust a
1787    // budget meant for agents that actually misbehaved.
1788    if verdict.parked {
1789        task.park(detail);
1790        return;
1791    }
1792    match verdict.status {
1793        RunStatus::Merged | RunStatus::Ready
1794            if task.pr_recovery.as_ref().is_some_and(|s| {
1795                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1796            }) =>
1797        {
1798            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()));
1799        }
1800        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1801        RunStatus::AlreadyInBase => task.already_landed(detail),
1802        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1803        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1804            task.stall(detail)
1805        }
1806        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1807        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1808        RunStatus::Blocked => task.fail(detail, max_attempts),
1809        RunStatus::VerifiedNoop => task.handed_off(detail),
1810        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1811    }
1812}
1813
1814/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1815/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1816/// itself has actually finished *and* its own last attempt is provably why:
1817/// this loads that run and requires `Merged`/`Ready` before touching
1818/// anything earlier in `runs`, since `Task::succeed` can also be called
1819/// directly on a task whose last attempt never landed at all.
1820///
1821/// Called right after whatever call set `task.status` to
1822/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1823/// `reclaim`'s, but also every other place a task can be closed by hand
1824/// without the loop ever settling it itself: `magi task done`
1825/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1826/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1827/// GitHub merge, say, exactly the workflow this repository's own
1828/// "Landing a run's winner by hand" documents — is just as much "this task's
1829/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1830/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1831/// forever, which is the exact backlog this status exists to clear. `pub`
1832/// for those two out-of-module callers; everything else about this stays
1833/// internal bookkeeping.
1834///
1835/// A run something is still actually driving is left alone: a
1836/// task cannot be `Done` while one of its *own* attempts is still in flight,
1837/// so a live one at this point can only be an unrelated process — a manual
1838/// `--resume` of this old, now-moot run — and rewriting under it would just
1839/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1840/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1841/// pair `run_report`/`run_detail` use for the same question elsewhere:
1842/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1843/// --resume` invoked by hand outside it, which `liveness` also checks via
1844/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1845/// (already terminal in some other way, or itself mid-run) is left untouched
1846/// too.
1847///
1848/// Best-effort, like the rest of this module's bookkeeping: a load or save
1849/// failure here is a `tracing::warn`, not a failed settle, and the next time
1850/// this same task's completion is recorded — or a daemon restart replays
1851/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1852/// separate reconciliation pass; if that gap ever matters in practice, one
1853/// can be added then.
1854///
1855/// `home` is a parameter, not the process-global [`crate::run::home`], for
1856/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1857/// calls this with `ui.home`, which is `crate::run::home()` in a real
1858/// process but a fixture's own directory under test — falling through to
1859/// the global there would read and write through whichever home some other
1860/// test in the same binary happened to pin into that `OnceLock` first, not
1861/// the run this call actually means.
1862pub fn supersede_prior_runs(task: &Task, home: &Path) {
1863    let now = Timestamp::now();
1864    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1865    // right behind a `Merged`/`Ready` verdict) from one set directly by
1866    // `magi task done`/its web equivalent/the conductor on a task whose last
1867    // recorded attempt never actually landed - that requires reading the
1868    // run itself, which is exactly what this does before trusting anything
1869    // in `runs` is safe to relabel.
1870    let last_run_succeeded = task
1871        .runs
1872        .last()
1873        .and_then(|id| RunState::load_under(id, home).ok())
1874        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1875    for id in task.superseded_attempts(last_run_succeeded) {
1876        let mut state = match RunState::load_under(id, home) {
1877            Ok(s) => s,
1878            Err(e) => {
1879                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1880                continue;
1881            }
1882        };
1883        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1884            continue;
1885        }
1886        let daemon_claims = is_working_on(home, id, now);
1887        if state.liveness(daemon_claims) == Liveness::Live {
1888            continue;
1889        }
1890        state.status = RunStatus::Superseded;
1891        if let Err(e) = state.save_under(home) {
1892            tracing::warn!("could not mark run {id} superseded: {e:#}");
1893        }
1894    }
1895}
1896
1897/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1898/// finish the moment it was called, because one of its earlier attempts was
1899/// still live then - a `magi run --resume` invoked by hand on an old run,
1900/// most likely.
1901///
1902/// That skip is correct at the time (rewriting under a run something is
1903/// still actively saving would just be undone), but a task only ever
1904/// reaches `Done` once, so without this nothing would ever look at it
1905/// again: if that manual process later ends anywhere other than
1906/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1907/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1908/// backlog this status exists to clear. Called on the same idle-only
1909/// cadence as [`janitor`], next to it rather than folded into it: this
1910/// walks `queue` and `janitor` never otherwise needs one.
1911///
1912/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1913/// more than one attempt, every pass: each call is a handful of local file
1914/// reads bounded by that task's own attempt count, the same order of cost
1915/// [`clean::fold_due`] already pays scanning every run on disk on the same
1916/// cadence, and a task already fully resolved costs one failed liveness
1917/// check turned no-op the moment its lingering attempt is no longer live.
1918fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1919    for task in queue.list() {
1920        if task.status != TaskStatus::Done || task.runs.len() < 2 {
1921            continue;
1922        }
1923        supersede_prior_runs(&task, home);
1924    }
1925}
1926
1927/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1928/// task ends up held.
1929///
1930/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1931/// dead daemon never got back to) share this, so the two cannot drift into
1932/// disagreeing about which held tasks get a diagnostic.
1933fn settle_and_diagnose(
1934    task: &mut Task,
1935    verdict: Verdict,
1936    detail: &str,
1937    max_attempts: usize,
1938    state: &RunState,
1939) {
1940    let p = phrases(&state.config.graph.language);
1941    // Shared by normal completion and crash recovery, under the task claim.
1942    // No new attempt can own the task until the old driver has exited.
1943    if let Some(d) = &state.merge_decision {
1944        use crate::merge_decision as md;
1945        if task.runs.last().is_some_and(|id| id != &state.id) {
1946            return;
1947        }
1948        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
1949            task.succeed();
1950        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
1951            if state.liveness(false) != Liveness::Dead {
1952                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
1953                return;
1954            }
1955            let replacement = md::Replacement {
1956                question: d.question.clone(),
1957                run: state.id.clone(),
1958                pr: d.target.pr.clone(),
1959                agent: agent.to_owned(),
1960                context: format!(
1961                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
1962                    d.target.pr,
1963                    state.id,
1964                    serde_json::to_string(&state.reviews).unwrap_or_default()
1965                ),
1966            };
1967            task.requeue();
1968            task.pr_recovery = None;
1969            task.review_of = None;
1970            task.replacement = Some(replacement);
1971        } else {
1972            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
1973                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
1974            } 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())) }));
1975        }
1976        task.mark_action_applied(&d.question);
1977        if let Some(pass) = state.passes.last() {
1978            task.record_pass_at(
1979                &state.id,
1980                pass.index,
1981                Some(pass.started_at),
1982                task.attempts,
1983                None,
1984            );
1985        }
1986        return;
1987    }
1988    if let Some(replacement) = &task.replacement
1989        && !state.parked
1990        && state.resource_block.is_none()
1991        && (state.viable().is_empty()
1992            || (state.status == RunStatus::Blocked && state.tally.is_none()))
1993    {
1994        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)));
1995        return;
1996    }
1997    let attempts_before = task.attempts;
1998    // A run that stopped because a shared resource stayed busy was never a
1999    // failure of the task or of an agent. Earlier nodes may have run; only
2000    // the blocked operation lacks a result. The attempt is
2001    // refunded and the task is held by the machine, under a reason `triage`
2002    // can re-check, so the same run resumes with the same agents once the
2003    // resource is free. A park request still wins (it is the operator's).
2004    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2005        task.notice_cause(
2006            &format!("resource:{}:{}", block.kind, block.node),
2007            None,
2008            None,
2009        );
2010        task.last_error = Some(detail.to_owned());
2011        task.diagnostic = None;
2012        task.attempts = task.attempts.saturating_sub(1);
2013        if block.kind == "disk pressure" {
2014            task.hold_machine(Some(format!(
2015                "{}{}",
2016                crate::disk::RUNNING_PRESSURE,
2017                block.detail
2018            )));
2019        } else {
2020            task.hold_machine(Some(format!(
2021                "{}{}; no attempt was spent; resume to retry the affected operation",
2022                crate::cache::RESOURCE_HOLD,
2023                block.description()
2024            )));
2025        }
2026        if let Some(pass) = state.passes.last() {
2027            task.record_pass_at(
2028                &state.id,
2029                pass.index,
2030                Some(pass.started_at),
2031                attempts_before,
2032                None,
2033            );
2034        }
2035        return;
2036    }
2037    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2038        state.parked
2039            && state.status == RunStatus::Landing
2040            && state
2041                .pr_pushed_head
2042                .as_ref()
2043                .is_none_or(|h| h == &hold.head)
2044            && task.runs.last() == Some(&state.id)
2045    }) {
2046        // Settlement and crash recovery share this idempotency key. A later
2047        // explicit resume is a new pass and may refund its own attempt once.
2048        let pass = state.passes.last().map_or(0, |p| p.index);
2049        if !task
2050            .passes
2051            .iter()
2052            .any(|p| p.run == state.id && p.pass_index == pass)
2053        {
2054            task.attempts = task.attempts.saturating_sub(1);
2055        }
2056        task.hold_machine(Some(format!(
2057            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2058            hold.question
2059        )));
2060        task.last_error = Some(detail.to_owned());
2061        task.diagnostic = None;
2062        task.record_pass_at(
2063            &state.id,
2064            pass,
2065            state.passes.last().map(|p| p.started_at),
2066            attempts_before,
2067            Some(crate::run::ParkCause::Question),
2068        );
2069        return;
2070    }
2071    let unresolved = task.hold_notice_cause.clone();
2072    if !verdict.parked
2073        && task
2074            .pr_recovery
2075            .as_ref()
2076            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2077        && matches!(
2078            verdict.status,
2079            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2080        )
2081    {
2082        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2083            task.succeed();
2084        } else {
2085            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()));
2086        }
2087    } else if !verdict.parked
2088        && task.pr_recovery.is_some()
2089        && matches!(
2090            verdict.status,
2091            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2092        )
2093        && !verdict.quota_hit
2094    {
2095        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.")));
2096    } else {
2097        settle_in(task, verdict, detail, max_attempts, p);
2098    }
2099    if !verdict.parked
2100        && !verdict.quota_hit
2101        && matches!(
2102            verdict.status,
2103            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2104        )
2105    {
2106        task.recovery_failed(state);
2107    }
2108    if state.prep_failure.is_some() {
2109        // Minting a run whose candidates could not be prepared is not work
2110        // on a newly approved attempt. Keep the unresolved outcome anchor.
2111        task.hold_notice_cause = unresolved;
2112        task.startup_notice_cause("startup-candidates");
2113    }
2114    // Written here, where the refund (or not) is decided, so the history is a
2115    // fact and not a later guess from the run's status.
2116    if let Some(pass) = state.passes.last() {
2117        let parked = match &pass.end {
2118            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2119            _ => None,
2120        };
2121        task.record_pass_at(
2122            &state.id,
2123            pass.index,
2124            Some(pass.started_at),
2125            attempts_before,
2126            parked,
2127        );
2128    }
2129    if task.status == TaskStatus::Held {
2130        if state.prep_failure.is_none() {
2131            task.notice_cause(
2132                label(verdict.status),
2133                Some(&state.id),
2134                state.passes.last().map(|p| p.index),
2135            );
2136        }
2137        task.diagnostic = diagnostic(state);
2138        note_open_question(task, &state.id, p);
2139    }
2140}
2141
2142/// If `task` is held with a `magi ask` question still open on `run`, name the
2143/// question in [`Task::hold_reason`] rather than leaving the hold reading
2144/// only [`describe`]'s run summary.
2145///
2146/// This is the shape task 20260928-191407-05fd left underspecified: an
2147/// implementer settled a verified no-op and filed a question for the
2148/// operator, and the hold that followed said nothing about the question
2149/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2150/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2151/// marker) and must keep seeing it unchanged.
2152///
2153/// Best-effort: an unreadable question store must not stop a run from
2154/// settling, so this is a no-op rather than a propagated error when
2155/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2156fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2157    let Some(home) = crate::run::try_home() else {
2158        return;
2159    };
2160    let open = Questions::at(home.join("questions")).open_for(run);
2161    let Some(q) = open.first() else {
2162        return;
2163    };
2164    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2165    decisions.sort_unstable();
2166    task.notice_cause(
2167        &format!("questions:{}", decisions.join(",")),
2168        Some(run),
2169        None,
2170    );
2171    let base = task.hold_reason.clone().unwrap_or_default();
2172    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2173}
2174
2175/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2176/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2177/// by some other means entirely, like a manual `magi run` resume that
2178/// finishes the graph outside the queue's bookkeeping.
2179///
2180/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2181/// `settle` is separate from `attempt`: a task recovered this way must land
2182/// exactly where a live daemon would have put it — the same policy table,
2183/// not a second one that quietly drifts from it — and that is only checkable
2184/// without spawning a real run.
2185fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2186    match last_run {
2187        Some(state) => {
2188            let verdict = Verdict {
2189                status: state.status,
2190                left_pr: state.pr.is_some(),
2191                quota_hit: !state.quota.is_empty(),
2192                parked: state.parked,
2193                no_viable_candidates: state.viable().is_empty(),
2194            };
2195            let detail = format!(
2196                "{}{}",
2197                phrases(&state.config.graph.language).recovered_running,
2198                describe(&state)
2199            );
2200            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2201        }
2202        None => {
2203            // No run, so no config of its own: `language` is the task's
2204            // repository's setting, read by the caller.
2205            let why = phrases(language).no_run_to_recover;
2206            task.last_error = Some(why.to_owned());
2207            // The phone shows `hold_reason`, so a task held by the machine
2208            // says why there too and not only in `last_error`.
2209            task.notice_cause("missing-run", None, None);
2210            task.hold_machine(Some(why.to_owned()));
2211        }
2212    }
2213}
2214
2215/// Find every task left at `running` that no live process is actually
2216/// driving, and settle each one against whatever its last run became.
2217///
2218/// # Why a claim is proof, not a guess
2219///
2220/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2221/// `running`, and the guard is held for the task's whole time in that status:
2222/// `attempt` does not return, and the loop does not move past the scope
2223/// holding the claim, until the run has settled. So a `running` task whose
2224/// lock is gone cannot have a live owner — this process or any other —
2225/// without needing a staleness threshold or a pid check the way
2226/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2227/// task that never got as far as `running` at all. Taking the claim here is
2228/// the whole test: it either fails, because something really does hold it
2229/// and the task is left alone, or it succeeds, which is the proof — and it is
2230/// kept for the rest of the decision so nothing else can start a competing
2231/// run while this one is being written.
2232///
2233/// Called on every poll, not only at startup, for the reason
2234/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2235/// keep noticing this, not only on the one morning it happened to restart.
2236fn reclaim_orphaned_running(
2237    queue: &Queue,
2238    max_attempts: usize,
2239    live_workers: &std::collections::BTreeSet<String>,
2240) -> Vec<String> {
2241    let mut reclaimed = Vec::new();
2242    for listed in queue.list() {
2243        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2244            continue;
2245        }
2246        let Ok(_claim) = queue.claim(&listed.id) else {
2247            continue;
2248        };
2249        // Re-read under the claim: a release or an edit landed by a human
2250        // between the listing above and the claim just taken must not be
2251        // clobbered by a decision based on the stale copy.
2252        let Ok(mut task) = queue.get(&listed.id) else {
2253            continue;
2254        };
2255        if task.status != TaskStatus::Running {
2256            continue;
2257        }
2258        let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
2259        // `execute` normally abandons a run's own open questions the moment
2260        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2261        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2262        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2263        // with the question still `open`, because the process died before
2264        // reaching that call. `reclaim` itself stays pure on purpose (see its
2265        // own doc), so the same cleanup runs here instead, against the run
2266        // this reclaim is already reading. `settle_run` costs nothing when
2267        // `execute` already got there first.
2268        if let Some(state) = &last_run
2269            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2270        {
2271            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2272        }
2273        let language = if last_run.is_none() {
2274            language_of(&task, Path::new("."))
2275        } else {
2276            String::new()
2277        };
2278        reclaim(&mut task, last_run, max_attempts, &language);
2279        if task.status == TaskStatus::Done {
2280            supersede_prior_runs(&task, &crate::run::home());
2281        }
2282        record(queue, &mut task);
2283        reclaimed.push(task.id.clone());
2284    }
2285    reclaimed
2286}
2287
2288/// Find every run whose `run.json` is provably dead — every seat it still
2289/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2290/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2291/// not merely "no daemon claims it" — and fail it, clearing the leftover
2292/// active seats so the run stops reading as `implementing` (or whichever
2293/// node) forever.
2294///
2295/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2296/// `running`, using whatever `run.json` already says — but nothing in that
2297/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2298/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2299/// never got back to sits exactly where it was left: `active` full of seats
2300/// nobody will ever answer for, `status` stuck on whatever node was in
2301/// flight. `magi show` already tells an operator this in prose (`no live
2302/// daemon claims this run right now`); this is what makes that fact durable
2303/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2304/// stay stuck once nothing is driving it.
2305///
2306/// Runs on every poll, not only at startup, for the reason
2307/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2308/// daemon up for days must keep noticing a run some other, now-dead, daemon
2309/// left behind just as readily as one it trips over on the way up.
2310///
2311/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2312/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2313/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2314/// `runs` directory instead: `home` here is a parameter precisely so a test
2315/// can point it away from the operator's real history (see [`drive`]'s own
2316/// doc), and a scan that fell through to the global home anyway would walk
2317/// whichever directory some *other* process or test pinned into that
2318/// `OnceLock` first — mutating runs this call was never handed.
2319fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2320    reclaim_abandoned_runs_with(
2321        home,
2322        now,
2323        crate::proc::pid_status,
2324        crate::proc::process_started_at,
2325    )
2326}
2327
2328/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2329/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2330/// for the identical reason: this sweep's real damage (wiping a run's active
2331/// seats and failing it) has to be provable against an injected answer in a
2332/// test, not just the real process table.
2333fn reclaim_abandoned_runs_with<F, G>(
2334    home: &Path,
2335    now: Timestamp,
2336    query: F,
2337    identity: G,
2338) -> Vec<String>
2339where
2340    F: Fn(u32) -> Option<bool>,
2341    G: Fn(u32) -> Option<String>,
2342{
2343    let mut abandoned = Vec::new();
2344    for entry in std::fs::read_dir(home.join("runs"))
2345        .into_iter()
2346        .flatten()
2347        .flatten()
2348    {
2349        let id = entry.file_name().to_string_lossy().into_owned();
2350        if !crate::run::is_run_id(&id) {
2351            continue;
2352        }
2353        // Serialize the proof and save with claims and takeover: a new
2354        // execution must not be overwritten after the liveness observation.
2355        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2356            continue;
2357        };
2358        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2359        // that module's docs for why a run this cannot parse is left alone
2360        // rather than guessed at. A different schema number is not that: this
2361        // touches only `status` and `active`, never a field whose meaning a
2362        // schema bump changed, so an old record's values serve this exactly
2363        // as well as a current one's (see `clean::read_state`'s own doc for
2364        // the same reasoning applied to folding).
2365        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2366            continue;
2367        };
2368        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2369            continue;
2370        };
2371        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2372            continue;
2373        }
2374        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2375        // it", which is also the normal, healthy shape of a manual `magi
2376        // run` / `magi review` sharing this same home — this scan walks
2377        // every run on disk, not only ones this daemon itself started. Such
2378        // a run's active seats can legitimately sit past their own timeout
2379        // for a little while (the CLI finishing up, its result still being
2380        // collected) without the process driving it having died. `liveness`
2381        // is what actually tells the two apart, by corroborating
2382        // `driver_pid` against the process it names — see its own doc. Only
2383        // its strongest, provable answer licenses wiping this run's active
2384        // seats and failing it out from under whatever is still running it.
2385        let daemon_claims = is_working_on(home, &id, now);
2386        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2387            != crate::run::Liveness::Dead
2388        {
2389            continue;
2390        }
2391        state.abandon("daemon");
2392        if let Err(e) = state.save_under(home) {
2393            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2394            continue;
2395        }
2396        // This run never passes through `Runner::execute` again, so its end
2397        // is announced here.
2398        if let Some(notice) = notices::run_ended(&state) {
2399            notices::raise_in(home, notice);
2400        }
2401        // The seat that asked is gone for good now, exactly like any other
2402        // door `graph::Runner::settle_questions` closes the moment `status`
2403        // lands somewhere non-resumable - see that method's own doc. Nothing
2404        // else reaches this one before the next `janitor()` startup pass
2405        // (`clean::abandon_settled_questions`), and a daemon that stays up
2406        // for days must not leave an open question badging the operator
2407        // until it happens to restart.
2408        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2409            tracing::warn!("abandon questions for {id}: {e:#}");
2410        }
2411        abandoned.push(id);
2412    }
2413    abandoned
2414}
2415
2416#[derive(Debug, Clone, Serialize, Deserialize)]
2417struct TaskWorker {
2418    opts: Opts,
2419    queue: PathBuf,
2420    task: String,
2421    #[serde(default)]
2422    lane: PermitKind,
2423    #[serde(default)]
2424    standalone: bool,
2425}
2426
2427fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2428    Ok(crate::worker::active(home)?
2429        .into_iter()
2430        .filter(|job| job.kind == "task")
2431        .collect())
2432}
2433
2434fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2435    task_jobs(home)?
2436        .into_iter()
2437        .filter_map(
2438            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2439                Ok(request) if !request.standalone => Some(Ok(job)),
2440                Ok(_) => None,
2441                Err(error) => Some(Err(error.into())),
2442            },
2443        )
2444        .collect()
2445}
2446
2447/// Whether an independent scheduler can be controlled without its web parent.
2448#[must_use]
2449pub fn managed(home: &Path) -> bool {
2450    match crate::worker::active(home) {
2451        Err(error) => {
2452            tracing::error!("cannot determine scheduler ownership: {error:#}");
2453            true
2454        }
2455        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2456        Ok(_) => {
2457            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2458                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2459        }
2460    }
2461}
2462
2463/// Start a detached, singleton scheduler using this executable generation.
2464pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2465    anyhow::ensure!(
2466        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2467        "the scheduler is stopping; wait for retirement before starting it again"
2468    );
2469    crate::worker::spawn(
2470        home,
2471        "scheduler",
2472        "scheduler",
2473        serde_json::to_value(opts.absolute()?)?,
2474    )
2475    .await
2476}
2477
2478fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2479    home.join("worker-parks").join(format!("{}.json", job.id))
2480}
2481
2482fn request_task_park(
2483    home: &Path,
2484    job: &crate::worker::Job,
2485    cause: crate::run::ParkCause,
2486) -> Result<()> {
2487    let path = park_request_path(home, job);
2488    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2489    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2490    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2491}
2492
2493/// Stop dispatch immediately; only an explicit park reaches existing workers.
2494pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2495    if control == crate::worker::Control::Park {
2496        for job in owned_task_jobs(home)? {
2497            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2498        }
2499    }
2500    crate::worker::request(home, "scheduler", control)
2501}
2502
2503/// Replace the scheduler, leaving all active task and conversation jobs alone.
2504pub async fn restart_detached(home: &Path) -> Result<()> {
2505    let active = crate::worker::active(home)?;
2506    let prior = active.into_iter().find(|job| job.kind == "scheduler");
2507    if prior.is_none() && !managed(home) {
2508        return Ok(());
2509    }
2510    let opts: Opts = match prior {
2511        Some(job) => serde_json::from_value(job.payload)?,
2512        None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2513    };
2514    request_control(home, crate::worker::Control::Stop)?;
2515    loop {
2516        let reserved = crate::worker::active(home)?
2517            .iter()
2518            .any(|job| job.kind == "scheduler");
2519        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2520            break;
2521        }
2522        tokio::time::sleep(Duration::from_millis(100)).await;
2523    }
2524    spawn_detached(home, &opts).await?;
2525    Ok(())
2526}
2527
2528/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2529pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2530    let opts: Opts = serde_json::from_value(payload)?;
2531    let _ = home;
2532    serve_until(opts, Stop::new()).await
2533}
2534
2535/// Execute and settle one task with the queue claim owned by this process.
2536pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2537    let request: TaskWorker = serde_json::from_value(payload)?;
2538    let queue = Queue::at(request.queue);
2539    let key = format!("task:{}", request.task);
2540    let job = task_jobs(home)?
2541        .into_iter()
2542        .find(|job| job.key == key)
2543        .context("task worker reservation is missing")?;
2544    let park_path = park_request_path(home, &job);
2545    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2546    // our durable reservation. Never execute before that ownership hand-off.
2547    let _claim = loop {
2548        match queue.claim(&request.task) {
2549            Ok(claim) => break claim,
2550            // Only contention (the claim file exists) is worth waiting out; an
2551            // I/O failure must end this worker instead of pinning its lane.
2552            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2553                return Err(e.context("claim the task for its worker"));
2554            }
2555            Err(_) => {
2556                sweep_stale_claims(&queue, STALE_CLAIM);
2557                tokio::time::sleep(Duration::from_millis(50)).await;
2558            }
2559        }
2560    };
2561    let mut task = queue.get(&request.task)?;
2562    if !task.status.runnable()
2563        || (!request.standalone
2564            && request.lane
2565                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2566    {
2567        return Ok(());
2568    }
2569    let stop = Stop::new();
2570    let watcher = {
2571        let home = home.to_path_buf();
2572        let stop = stop.clone();
2573        let park_path = park_path.clone();
2574        tokio::spawn(async move {
2575            loop {
2576                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2577                    let cause = std::fs::read(&park_path)
2578                        .ok()
2579                        .and_then(|body| serde_json::from_slice(&body).ok())
2580                        .unwrap_or(crate::run::ParkCause::Operator);
2581                    stop.park(cause);
2582                    return;
2583                }
2584                tokio::time::sleep(Duration::from_millis(200)).await;
2585            }
2586        })
2587    };
2588    let quota = if request.standalone {
2589        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2590    } else {
2591        let status = Arc::new(Mutex::new(Status::new()));
2592        Box::pin(attempt(
2593            &request.opts,
2594            &queue,
2595            &status,
2596            &stop,
2597            crate::graph::Pause::new(),
2598            &mut task,
2599        ))
2600        .await
2601    };
2602    watcher.abort();
2603    let _ = std::fs::remove_file(park_path);
2604    persist_cooldown(home, &quota).await?;
2605    Ok(())
2606}
2607
2608/// Launch the standalone task worker with a claim-to-reservation handoff.
2609/// Returns only after the worker owns a durable execution reservation.
2610pub async fn spawn_claimed(
2611    home: &Path,
2612    opts: &Opts,
2613    queue: &Queue,
2614    task: &Task,
2615    claim: crate::queue::Claim,
2616) -> Result<crate::worker::Job> {
2617    let request = TaskWorker {
2618        opts: opts.absolute()?,
2619        queue: std::path::absolute(queue.root())?,
2620        task: task.id.clone(),
2621        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2622        standalone: true,
2623    };
2624    let job = crate::worker::spawn(
2625        home,
2626        "task",
2627        &format!("task:{}", task.id),
2628        serde_json::to_value(request)?,
2629    )
2630    .await?;
2631    drop(claim);
2632    Ok(job)
2633}
2634
2635/// Transfer a standalone caller's claim only after the detached worker is live,
2636/// then follow that worker to its final (non-automatically-retrying) outcome.
2637pub async fn run_detached_claimed(
2638    opts: &Opts,
2639    queue: &Queue,
2640    task: &mut Task,
2641    claim: crate::queue::Claim,
2642) -> Result<()> {
2643    let home = crate::run::home();
2644    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2645    loop {
2646        // Reconcile execution leases even without a scheduler. A dead worker
2647        // must become a reported failure, never an infinite persisted wait.
2648        crate::worker::active(&home)?;
2649        let current = crate::worker::get(&home, &job.id)?;
2650        if matches!(
2651            current.status,
2652            crate::worker::Status::Finished | crate::worker::Status::Failed
2653        ) {
2654            *task = queue.get(&task.id)?;
2655            anyhow::ensure!(
2656                current.status != crate::worker::Status::Failed,
2657                "task worker failed: {}",
2658                current.result.as_deref().unwrap_or("unknown failure")
2659            );
2660            return Ok(());
2661        }
2662        tokio::time::sleep(Duration::from_millis(200)).await;
2663    }
2664}
2665
2666async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2667    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2668        let _lease = loop {
2669            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2670                break lease;
2671            }
2672            tokio::time::sleep(Duration::from_millis(10)).await;
2673        };
2674        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2675            let path = home.join("task-quota-cooldown.json");
2676            let temporary = path.with_extension("json.tmp");
2677            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2678            std::fs::rename(temporary, path)?;
2679        }
2680    }
2681    Ok(())
2682}
2683
2684fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2685    match std::fs::read(home.join("task-quota-cooldown.json")) {
2686        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2687        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2688        Err(error) => Err(error.into()),
2689    }
2690}
2691
2692/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2693///
2694/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2695/// sets, so there is one loop body rather than two that drift apart the first
2696/// time the retry policy changes on only one of them.
2697pub async fn serve(opts: Opts) -> Result<()> {
2698    tracing::info!(
2699        "automatic update and restart requires magi web; standalone serve does not restart"
2700    );
2701    serve_until(opts, Stop::new()).await
2702}
2703
2704/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2705///
2706/// A stop retires dispatch promptly, including while a worker launch is being
2707/// acknowledged. Already reserved workers own their attempts independently and
2708/// finish with their started executable. Explicit park additionally forwards
2709/// durable park requests; neither scheduler retirement nor update does so.
2710///
2711/// While the queue is empty the stop is honoured within one wakeup rather than
2712/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2713/// caller that taps stop does not sit through the remainder of a sleep.
2714pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2715    let opts = opts.absolute()?;
2716    let home = crate::run::home();
2717    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2718        .context("another scheduler already owns this home")?;
2719    if let Some(reading) = read_status(&home)
2720        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2721    {
2722        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2723    }
2724    if !crate::worker::active(&home)?
2725        .iter()
2726        .any(|job| job.kind == "scheduler")
2727    {
2728        crate::worker::clear_control(&home, "scheduler")?;
2729    }
2730    std::fs::write(
2731        home.join("scheduler-options.json"),
2732        serde_json::to_vec(&opts)?,
2733    )?;
2734    let control = {
2735        let home = home.clone();
2736        let stop = stop.clone();
2737        tokio::spawn(async move {
2738            loop {
2739                match crate::worker::control(&home, "scheduler").ok().flatten() {
2740                    Some(crate::worker::Control::Park) => {
2741                        let _ = request_control(&home, crate::worker::Control::Park);
2742                        stop.park(crate::run::ParkCause::Operator);
2743                        break;
2744                    }
2745                    Some(crate::worker::Control::Stop) => {
2746                        stop.stop();
2747                        break;
2748                    }
2749                    None => {}
2750                }
2751                tokio::time::sleep(Duration::from_millis(100)).await;
2752            }
2753        })
2754    };
2755    let signal = {
2756        let stop = stop.clone();
2757        tokio::spawn(async move {
2758            if tokio::signal::ctrl_c().await.is_ok() {
2759                stop.stop();
2760                tracing::info!("scheduler shutdown requested; independent workers continue");
2761            }
2762        })
2763    };
2764
2765    let worktrees_root = opts
2766        .worktrees_root
2767        .clone()
2768        .unwrap_or_else(crate::run::default_worktree_root);
2769    let outcome = drive(
2770        &opts,
2771        &Queue::open(),
2772        &status_path(),
2773        &crate::run::home(),
2774        &worktrees_root,
2775        &stop,
2776    )
2777    .await;
2778
2779    signal.abort();
2780    control.abort();
2781    outcome
2782}
2783
2784/// The loop proper: setup, poll, teardown, with the queue and the status file
2785/// supplied rather than discovered.
2786///
2787/// All three of `home`, `worktrees_root` and the queue/status paths are
2788/// parameters rather than resolved here, for the same reason:
2789/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2790/// so a unit test that pinned it would fight every other test in the binary,
2791/// and a loop that resolved its own worktree bay could only be exercised
2792/// against the operator's real `~/wt/<repo>` - publishing over a live
2793/// daemon's status file, claiming tasks out of a live backlog, and, since
2794/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2795/// whatever the operator actually has on disk.
2796async fn drive(
2797    opts: &Opts,
2798    queue: &Queue,
2799    status_file: &Path,
2800    home: &Path,
2801    worktrees_root: &Path,
2802    stop: &Stop,
2803) -> Result<()> {
2804    // The status file is a *snapshot*, not a stream of events: a reader only
2805    // ever wants the latest values, and every tick rewrites the whole file
2806    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2807    // while an mpsc channel would force the loop to re-send unchanged fields on
2808    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2809    // for no gain. The lock is only ever held across a field assignment, never
2810    // across an await.
2811    let recovery_cfg = prepare(&opts.repo, opts).ok();
2812    let daemon_cfg = recovery_cfg
2813        .as_ref()
2814        .map(|c| c.daemon.clone())
2815        .unwrap_or_default();
2816    let reconciled = crate::driver::reconcile(home);
2817    if !reconciled.is_empty() {
2818        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2819    }
2820    let mut initial_status = Status::new();
2821    let owned = owned_task_jobs(home)?;
2822    initial_status.current = current_work(home, Timestamp::now())
2823        .into_iter()
2824        .filter(|current| {
2825            owned
2826                .iter()
2827                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2828        })
2829        .collect();
2830    initial_status.idle = initial_status.current.is_empty();
2831    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2832        recovery_cfg.as_ref(),
2833        daemon_cfg.max_deputies,
2834    ));
2835    let status = Arc::new(Mutex::new(initial_status));
2836    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
2837    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
2838
2839    // Read once at startup, not per task: how many runs this loop drives at
2840    // once is a property of the machine running it, not of whichever
2841    // repository a given task happens to name - see
2842    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
2843    // fact in the same sense the agent roster is.
2844    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
2845
2846    tracing::info!(
2847        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
2848        queue.root().display(),
2849        opts.poll.as_secs(),
2850        opts.max_attempts,
2851        concurrency,
2852        if daemon_cfg.pause_for_interrupts {
2853            ", interrupts enabled"
2854        } else {
2855            ""
2856        }
2857    );
2858
2859    let outcome = tokio::select! {
2860        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
2861            max_concurrent: concurrency,
2862            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
2863            recovery_cfg,
2864        }) => outcome,
2865        () = async {
2866            while !stop.stopped() {
2867                tokio::time::sleep(Duration::from_millis(25)).await;
2868            }
2869        } => {
2870            if stop.parking() {
2871                request_control(home, crate::worker::Control::Park)?;
2872            }
2873            Ok(())
2874        }
2875    };
2876
2877    stop.busy.store(0, Ordering::SeqCst);
2878    beat.abort();
2879    clear_status_at(status_file);
2880    outcome
2881}
2882
2883/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
2884/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
2885pub(crate) fn release_watch_settings_from_config(
2886    home: &Path,
2887    repo: &Path,
2888    cfg: &Config,
2889) -> (Vec<PathBuf>, u64) {
2890    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
2891        .into_iter()
2892        .map(|r| r.path)
2893        .collect();
2894    // Repositories the daemon has worked in, wherever they live: a task may
2895    // name one outside `[repos] roots`, and its release PR must be watched too.
2896    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
2897        .list()
2898        .into_iter()
2899        .map(|t| t.repo)
2900        .collect();
2901    let runs = home.join("runs");
2902    for id in crate::run::list_ids_in(&runs) {
2903        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
2904            .ok()
2905            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
2906            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
2907        known.extend(repo);
2908    }
2909    for k in known {
2910        let k = k.canonicalize().unwrap_or(k);
2911        if k.join(".git").exists() && !paths.contains(&k) {
2912            paths.push(k);
2913        }
2914    }
2915    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
2916    if !paths.contains(&own) {
2917        paths.push(own);
2918    }
2919    (paths, cfg.daemon.release_stall_minutes)
2920}
2921
2922/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
2923const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
2924
2925/// Refresh the status file on a fixed tick.
2926///
2927/// Separate from the loop because a run takes tens of minutes: a status file
2928/// written only between tasks would look stale for the whole of every run, and
2929/// a reader would report the daemon dead exactly while it was busiest.
2930async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
2931    loop {
2932        tokio::time::sleep(HEARTBEAT).await;
2933        let snapshot = {
2934            let mut guard = lock(&status);
2935            guard.updated_at = Timestamp::now();
2936            guard.clone()
2937        };
2938        if let Err(e) = write_status_to(&path, &snapshot) {
2939            // A failed heartbeat must not take the daemon down: the loop is the
2940            // product, the status file is only the window onto it.
2941            tracing::warn!("could not refresh the daemon status file: {e:#}");
2942        }
2943    }
2944}
2945
2946/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
2947/// if so, whether that wait is over.
2948#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2949enum LandResume {
2950    /// The task's last run is not parked on a land approval; schedule it
2951    /// like any other candidate.
2952    NotLanding,
2953    /// Parked in `land`, waiting on a question nobody has answered yet.
2954    /// Left alone: attempting it now would only re-observe the same pull
2955    /// request and park again, spending a `gh` call on a decision that has
2956    /// not changed since the last time this was checked.
2957    StillWaiting,
2958    /// Parked in `land`, and the question is settled - answered or
2959    /// abandoned. Resuming this is the one kind of candidate that must not
2960    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
2961    Ready,
2962}
2963
2964/// Classify a runnable candidate by whether it is parked on a land-merge
2965/// approval. Read-only - no claim taken, nothing written - so it is cheap
2966/// enough to call on every candidate, every poll.
2967fn land_resume_state(task: &Task) -> LandResume {
2968    let Some(run_id) = task.runs.last() else {
2969        return LandResume::NotLanding;
2970    };
2971    let Ok(state) = RunState::load(run_id) else {
2972        return LandResume::NotLanding;
2973    };
2974    if !state.parked {
2975        return LandResume::NotLanding;
2976    }
2977    if state.status == RunStatus::Landing
2978        && state.land_approval.as_ref().is_some_and(|binding| {
2979            ask::Questions::open()
2980                .get(&binding.question)
2981                .is_ok_and(|q| {
2982                    q.run == state.id
2983                        && q.resolution()
2984                            .as_deref()
2985                            .is_some_and(crate::merge_decision::stops)
2986                })
2987        })
2988    {
2989        return LandResume::Ready;
2990    }
2991    if !implementers_match(task, &state) {
2992        return LandResume::NotLanding;
2993    }
2994    // Parked in `land` on the merge approval, or at `merge` on the owner's
2995    // word about a title/body the posting gate withheld. Told apart by the
2996    // run's own record, not by a status both can share.
2997    let node = if state.status == RunStatus::Landing {
2998        land::APPROVAL_NODE
2999    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3000        crate::github_text::ASK_NODE
3001    } else {
3002        return LandResume::NotLanding;
3003    };
3004    let store = ask::Questions::open();
3005    let waiting = store
3006        .list()
3007        .into_iter()
3008        .filter(|q| &q.run == run_id && q.node == node)
3009        .max_by(|a, b| a.id.cmp(&b.id));
3010    let Some(mut q) = waiting else {
3011        return LandResume::Ready;
3012    };
3013    if !q.status.open() {
3014        // Repair spends agent resources and must obey concurrency and quota
3015        // waits; only a merge/hold decision may use the decision-only lane.
3016        if q.resolution().as_deref() == Some(land::REPAIR) {
3017            return if state.liveness(false) == Liveness::Live {
3018                LandResume::StillWaiting
3019            } else {
3020                LandResume::NotLanding
3021            };
3022        }
3023        return LandResume::Ready;
3024    }
3025    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3026    // nobody ever answered; land's approval bypasses that wait entirely (see
3027    // `land::approval_gate`), so the same deadline has to be enforced here
3028    // instead, or `graph.answer_timeout` silently stops meaning anything for
3029    // a land approval and a run can sit `StillWaiting` forever with nobody
3030    // told to look at it.
3031    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3032    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3033    if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3034        q.abandon(format!(
3035            "no answer within {}s of asking",
3036            timeout.as_secs().max(1)
3037        ));
3038        // If this can't be persisted, do not treat the wait as settled on a
3039        // guess: fall through and try again next poll.
3040        if store.put(&mut q).is_ok() {
3041            return LandResume::Ready;
3042        }
3043    }
3044    LandResume::StillWaiting
3045}
3046
3047/// How often the loop rechecks for new work while something it already
3048/// started is still running, rather than sleeping out the whole
3049/// [`Opts::poll`] interval.
3050///
3051/// Short on purpose: this is what lets a land-merge approval that comes back
3052/// while another task is mid-competition be noticed and resumed within a
3053/// fraction of a second, not within the next multi-second poll.
3054const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3055
3056/// How often [`poll`] rechecks the shared build cache against its cap at a
3057/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3058/// waiting for the queue to run dry.
3059///
3060/// A queue that never empties means the `janitor` call at the bottom of this
3061/// loop's fully-idle branch can go unreached for as long as the backlog
3062/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3063/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3064/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3065/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3066/// backlog of short tasks does not pay for that walk on every poll.
3067const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3068
3069/// State of [`poll`]'s own interrupt-scheduling sequence - see
3070/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3071/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3072/// both kept free of `Task`'s non-identity fields on purpose: every decision
3073/// here turns only on task ids and which ones are in flight, so the "never
3074/// more than one run at once" and "exactly one resume" invariants can be
3075/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3076/// queue - which is exactly the coverage this feature's first two attempts
3077/// were missing.
3078///
3079/// Persisted after every transition, so scheduler replacement preserves the
3080/// interrupt's exclusive turn and the interrupted task's priority resume.
3081#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3082enum Interrupt {
3083    /// No interrupt sequence in progress. Ordinary dispatch applies.
3084    Idle,
3085    /// `interrupt_task` is runnable and exactly one other run is in flight;
3086    /// `parked` names that one task's id. Dispatch is withheld from
3087    /// everyone, including `interrupt_task` itself, until it has left
3088    /// flight - only then is `interrupt_task` let through.
3089    ///
3090    /// `parked` is a `Vec` rather than a bare id for symmetry with
3091    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3092    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3093    /// when exactly one run is in flight, so it is guaranteed to hold
3094    /// exactly one entry in practice - see that branch's own doc for why
3095    /// more than one is deliberately never attempted.
3096    Parking {
3097        parked: Vec<String>,
3098        interrupt_task: String,
3099    },
3100    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3101    /// withheld from everyone until it leaves flight - merged, failed, held,
3102    /// it makes no difference - at which point the sequence moves to
3103    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3104    /// going straight to `Idle` would hand `parked` back to ordinary
3105    /// priority-order dispatch, where a higher-priority task filed in the
3106    /// meantime could start ahead of it.
3107    Running {
3108        parked: Vec<String>,
3109        interrupt_task: String,
3110    },
3111    /// `interrupt_task` left flight; `parked` still names the one run this
3112    /// sequence owes a resume. Dispatch is withheld from everyone except
3113    /// that task - see [`interrupt_gate`] - so the resume this feature
3114    /// promises is never raced by, or run alongside, an unrelated candidate.
3115    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3116    /// own doc on abandonment - the moment it is no longer runnable at all.
3117    Resuming { parked: Vec<String> },
3118}
3119
3120/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3121/// and `runnable` are read-only snapshots of this tick's reality, and the
3122/// only side effect the caller still owes the world is asking whichever
3123/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3124/// site.
3125///
3126/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3127/// accepted rather than a narrower type because that is what [`poll`] already
3128/// has on hand from [`runnable`], and building a second, smaller list on
3129/// every tick just to satisfy this signature would cost more than it proves.
3130///
3131/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3132/// back to a task they are waiting on no longer being [`runnable`] - held,
3133/// blocked, deleted, or finished by some other means entirely, all of which
3134/// an operator can do to a task sitting in the queue with no claim on it at
3135/// all, at any moment, interrupt sequence or not. Without this check the
3136/// sequence would wait forever for a dispatch that can never come, and
3137/// `interrupt_gate` would withhold every other task in the queue right along
3138/// with it - a single `magi task hold` on the wrong id turning into a
3139/// daemon that never dispatches anything again.
3140fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3141    match state {
3142        Interrupt::Idle => {
3143            // Not just "something to interrupt": exactly one thing. More
3144            // than one run in flight only happens above the default
3145            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3146            // one resume, never run alongside anything else" only because
3147            // it is only ever seeded with exactly one id - see
3148            // `Interrupt::Resuming`'s own doc on why releasing more than one
3149            // parked id back to ordinary dispatch cannot be made safe
3150            // against that same setting's own extra concurrency slots.
3151            // Waiting here for the herd to settle to one is the
3152            // simplification this feature's own constraints ask for rather
3153            // than a second concurrency model to reconcile with the first.
3154            if in_flight.len() != 1 {
3155                return Interrupt::Idle;
3156            }
3157            match runnable.iter().find(|t| t.interrupt) {
3158                Some(t) => Interrupt::Parking {
3159                    parked: in_flight.to_vec(),
3160                    interrupt_task: t.id.clone(),
3161                },
3162                None => Interrupt::Idle,
3163            }
3164        }
3165        Interrupt::Parking {
3166            parked,
3167            interrupt_task,
3168        } => {
3169            if in_flight.iter().any(|id| parked.contains(id)) {
3170                // Still waiting for what was in flight to actually stop.
3171                Interrupt::Parking {
3172                    parked,
3173                    interrupt_task,
3174                }
3175            } else if in_flight.contains(&interrupt_task) {
3176                Interrupt::Running {
3177                    parked,
3178                    interrupt_task,
3179                }
3180            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3181                // The parked run(s) are gone, but the interrupt task has not
3182                // been dispatched yet on this tick - `interrupt_gate` is
3183                // what lets it through next.
3184                Interrupt::Parking {
3185                    parked,
3186                    interrupt_task,
3187                }
3188            } else {
3189                // The interrupt task itself is no longer runnable - see this
3190                // function's own doc on abandonment. The parked run(s) still
3191                // get their guaranteed resume; there is simply no interrupt
3192                // to run ahead of them any longer.
3193                Interrupt::Resuming { parked }
3194            }
3195        }
3196        Interrupt::Running {
3197            parked,
3198            interrupt_task,
3199        } => {
3200            if in_flight.contains(&interrupt_task) {
3201                Interrupt::Running {
3202                    parked,
3203                    interrupt_task,
3204                }
3205            } else {
3206                // The interrupt task's own run reached a terminal status,
3207                // whichever one - this is the *only* trigger that moves the
3208                // sequence on, driven straight off the same in-flight
3209                // bookkeeping `poll` already reaps every tick, not a second,
3210                // independent poll of anything.
3211                Interrupt::Resuming { parked }
3212            }
3213        }
3214        Interrupt::Resuming { parked } => {
3215            if in_flight.iter().any(|id| parked.contains(id)) {
3216                // One of the parked runs has been dispatched - the resume
3217                // this sequence owed is fulfilled. Whatever else is left in
3218                // `parked` (ordinarily nothing, at the default concurrency
3219                // of one) rejoins ordinary priority-order dispatch, same as
3220                // any other runnable task.
3221                Interrupt::Idle
3222            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3223                Interrupt::Resuming { parked }
3224            } else {
3225                // Abandonment (see this function's own doc): nothing left in
3226                // `parked` is even runnable any longer.
3227                Interrupt::Idle
3228            }
3229        }
3230    }
3231}
3232
3233/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3234/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3235/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3236/// indistinguishable from any other runnable task - exactly the "off does
3237/// nothing" this feature promises.
3238fn advance_interrupt_tick(
3239    enabled: bool,
3240    state: Interrupt,
3241    in_flight: &[String],
3242    runnable: &[Task],
3243) -> Interrupt {
3244    if !enabled {
3245        return Interrupt::Idle;
3246    }
3247    advance_interrupt(state, in_flight, runnable)
3248}
3249
3250/// Which of this tick's runnable candidates the interrupt sequence actually
3251/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3252/// each half is assertable on its own: this is the half that keeps a
3253/// competition and an interrupt from ever running at the same moment.
3254fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3255    match state {
3256        Interrupt::Idle => candidates,
3257        Interrupt::Parking {
3258            parked,
3259            interrupt_task,
3260        } => {
3261            if in_flight.iter().any(|id| parked.contains(id)) {
3262                Vec::new()
3263            } else {
3264                candidates
3265                    .into_iter()
3266                    .filter(|t| &t.id == interrupt_task)
3267                    .collect()
3268            }
3269        }
3270        Interrupt::Running { .. } => Vec::new(),
3271        // At most one: even if `parked` names more than one id (more than
3272        // one run was in flight when the sequence began, only possible
3273        // above the default `max_concurrent_runs = 1`), only the first match
3274        // is offered. Capping this to a single candidate - not merely to
3275        // `parked`'s own ids - is what makes "exactly one resume, never two
3276        // dispatched together" true regardless of how many ordinary slots
3277        // happen to be free this tick.
3278        Interrupt::Resuming { parked } => candidates
3279            .into_iter()
3280            .find(|t| parked.contains(&t.id))
3281            .into_iter()
3282            .collect(),
3283    }
3284}
3285
3286/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3287/// bundled into one parameter so `poll`'s own signature stays readable -
3288/// see [`drive`]'s call site for where these are actually read.
3289struct DispatchLimits {
3290    /// How many *ordinary* candidates run at once. See
3291    /// [`crate::config::Daemon::max_concurrent_runs`].
3292    max_concurrent: usize,
3293    /// See [`crate::config::Daemon::pause_for_interrupts`].
3294    pause_for_interrupts: bool,
3295    recovery_cfg: Option<Config>,
3296}
3297
3298/// Which semaphore, if any, dispatching a candidate should draw its permit
3299/// from.
3300///
3301/// Pure and separate from [`poll`]'s loop body for the same reason
3302/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3303/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3304/// exactly the policy this feature adds, and a policy only exercisable by
3305/// running the whole loop is a policy nobody checks.
3306#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3307enum PermitKind {
3308    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3309    /// Checked first - a task can be both a land resume and marked
3310    /// [`Task::urgent`], and the resume's own "must not queue behind
3311    /// anything" guarantee takes precedence.
3312    None,
3313    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3314    /// (never in addition to trying) the ordinary pool. This is what lets
3315    /// an urgent task dispatch while every ordinary slot is already checked
3316    /// out, and what stops a second urgent task from opening a third run: it
3317    /// waits on this same one-slot semaphore rather than falling through to
3318    /// the ordinary one.
3319    Urgent,
3320    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3321    /// above.
3322    #[default]
3323    Ordinary,
3324}
3325
3326/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3327/// own boolean, already computed by the caller from [`land_resume_state`].
3328fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3329    if priority {
3330        PermitKind::None
3331    } else if urgent {
3332        PermitKind::Urgent
3333    } else {
3334        PermitKind::Ordinary
3335    }
3336}
3337
3338fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3339    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3340        (0usize, 0usize),
3341        |(ordinary, urgent), request| match request.lane {
3342            PermitKind::Ordinary => (ordinary + 1, urgent),
3343            PermitKind::Urgent => (ordinary, urgent + 1),
3344            PermitKind::None => (ordinary, urgent),
3345        },
3346    );
3347    (
3348        limit.saturating_sub(ordinary),
3349        1usize.saturating_sub(urgent),
3350    )
3351}
3352
3353struct DispatchClaim {
3354    task: Task,
3355    claim: crate::queue::Claim,
3356    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3357}
3358
3359/// Claim and re-read before choosing a lane: a queue listing may predate an
3360/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3361fn claim_dispatch(
3362    queue: &Queue,
3363    candidate: &Task,
3364    cooling_down: bool,
3365    ordinary: &Arc<tokio::sync::Semaphore>,
3366    urgent: &Arc<tokio::sync::Semaphore>,
3367) -> Option<DispatchClaim> {
3368    let Ok(claim) = queue.claim(&candidate.id) else {
3369        tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
3370        return None;
3371    };
3372    let task = match queue.get(&candidate.id) {
3373        Ok(t) if t.status.runnable() => t,
3374        Ok(_) => return None,
3375        Err(e) => {
3376            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3377            return None;
3378        }
3379    };
3380    let resume = land_resume_state(&task);
3381    if resume == LandResume::StillWaiting {
3382        return None;
3383    }
3384    let priority = resume == LandResume::Ready;
3385    if !priority && cooling_down {
3386        return None;
3387    }
3388    // Never borrow an ordinary slot when the single urgent slot is busy.
3389    // Keep scanning other candidates when either pool has no free slot.
3390    let permit = match permit_kind(priority, task.urgent) {
3391        PermitKind::None => None,
3392        PermitKind::Urgent => Some(Arc::clone(urgent).try_acquire_owned().ok()?),
3393        PermitKind::Ordinary => Some(Arc::clone(ordinary).try_acquire_owned().ok()?),
3394    };
3395    // Persist the dispatch order under the claim, before config discovery or
3396    // coordination waits can reorder concurrent starts.
3397    let stamp = Timestamp::now();
3398    let mut task = task;
3399    task.dispatched_at = Some(stamp);
3400    if let Err(e) = queue.modify(&task.id, |t| {
3401        t.dispatched_at = Some(stamp);
3402        true
3403    }) {
3404        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3405    }
3406    Some(DispatchClaim {
3407        task,
3408        claim,
3409        permit,
3410    })
3411}
3412
3413/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3414/// teardown and cannot skip the teardown on an early return.
3415///
3416/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3417/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3418/// land approval that has since been answered is dispatched outside that
3419/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3420/// the whole point of parking there is that it must not queue behind
3421/// whatever else the loop happens to be running, even at the default of one.
3422/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3423/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3424/// these exemptions is still subject to the interrupt gate below, urgent
3425/// included: a land-resume or urgent candidate is exactly as much "something
3426/// else running" as an ordinary one from the interrupt sequence's point of
3427/// view, and letting either slip through while a run is being parked, or
3428/// while the interrupt task itself has the floor, is precisely the second
3429/// run 75dd's own "at most one run, ever, at once" guarantee must never
3430/// allow - see [`Interrupt`]'s own doc.
3431#[derive(Serialize, Deserialize)]
3432struct ServiceWorker {
3433    opts: Opts,
3434    queue: PathBuf,
3435    worktrees_root: PathBuf,
3436    operation: String,
3437}
3438
3439fn load_conductor(home: &Path) -> Result<Conductor> {
3440    match std::fs::read(home.join("conductor-state.json")) {
3441        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3442        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3443        Err(error) => Err(error.into()),
3444    }
3445}
3446
3447fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3448    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3449        .into_iter()
3450        .map(|c| c.task)
3451        .collect();
3452    let stalled = stalled_tasks(queue, home, Timestamp::now());
3453    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3454    let finished = finished_tasks(queue)
3455        .into_iter()
3456        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3457        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3458        .collect();
3459    let queued = queued_tasks(queue)
3460        .into_iter()
3461        .filter(|t| !live.contains(&t.id))
3462        .collect();
3463    (queued, stalled, finished)
3464}
3465
3466async fn start_service(
3467    home: &Path,
3468    opts: &Opts,
3469    queue: &Queue,
3470    worktrees_root: &Path,
3471    operation: &str,
3472    cfg: Option<&Config>,
3473    busy: bool,
3474) -> Result<()> {
3475    // Fetch policy is live configuration, unlike question recovery capacity.
3476    // Reload before both cadence and eligibility, including disabled -> enabled.
3477    let fetch_cfg = if operation == "fetch" {
3478        match prepare(&opts.repo, opts) {
3479            Ok(cfg) => Some(cfg),
3480            Err(error) => {
3481                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3482                return Ok(());
3483            }
3484        }
3485    } else {
3486        None
3487    };
3488    let cfg = fetch_cfg.as_ref().or(cfg);
3489    let ticks = home.join("service-ticks");
3490    std::fs::create_dir_all(&ticks)?;
3491    let receipt = ticks.join(format!("daemon-{operation}"));
3492    let last = std::fs::read(&receipt)
3493        .ok()
3494        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3495    let interval = match operation {
3496        "disk-pressure" => 30,
3497        "cache" => CACHE_CHECK_INTERVAL_SECS,
3498        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3499        _ => opts.poll.as_secs().max(1),
3500    };
3501    let now = Timestamp::now();
3502    if !cache_check_due(last, now, interval) {
3503        return Ok(());
3504    }
3505    let key = format!("service:daemon-{operation}");
3506    if crate::worker::active(home)?
3507        .iter()
3508        .any(|job| job.key == key)
3509    {
3510        return Ok(());
3511    }
3512    let eligible = match operation {
3513        "conductor" => {
3514            let (queued, stalled, finished) = conductor_work(queue, home);
3515            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3516                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3517        }
3518        "maintenance" => Questions::at(home.join("questions"))
3519            .list()
3520            .iter()
3521            .any(|q| {
3522                q.chosen_action().is_some_and(|action| action.maintenance())
3523                    && !home
3524                        .join("choice-actions")
3525                        .join(format!("{}.json", q.id))
3526                        .exists()
3527            }),
3528        "housekeeping" => !busy && runnable(queue).is_empty(),
3529        "cache" => {
3530            !busy
3531                && !runnable(queue).is_empty()
3532                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3533        }
3534        "disk-pressure" => busy,
3535        "fetch" => {
3536            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3537        }
3538        _ => false,
3539    };
3540    if !eligible {
3541        return Ok(());
3542    }
3543    let request = ServiceWorker {
3544        opts: opts.absolute()?,
3545        queue: std::path::absolute(queue.root())?,
3546        worktrees_root: std::path::absolute(worktrees_root)?,
3547        operation: operation.to_owned(),
3548    };
3549    if let Err(error) =
3550        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3551    {
3552        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3553    }
3554    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3555    Ok(())
3556}
3557
3558/// Finite maintenance jobs survive scheduler replacement without duplicating
3559/// agent calls or cancelling an operation between its effect and receipt.
3560pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3561    let request: ServiceWorker = serde_json::from_value(payload)?;
3562    let opts = &request.opts;
3563    let queue = Queue::at(request.queue);
3564    let questions = Questions::at(home.join("questions"));
3565    match request.operation.as_str() {
3566        "maintenance" => apply_maintenance_choices(&queue, &questions, home).await,
3567        "conductor" => {
3568            let path = home.join("conductor-state.json");
3569            let mut conductor = load_conductor(home)?;
3570            let (queued, stalled, finished) = conductor_work(&queue, home);
3571            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3572                && conductor.worth_a_look(&queue, &stalled, &finished)
3573            {
3574                let cfg = prepare(&opts.repo, opts)?;
3575                conductor
3576                    .maybe_run(
3577                        &cfg,
3578                        &opts.repo,
3579                        &queue,
3580                        &questions,
3581                        home,
3582                        &queued,
3583                        &stalled,
3584                        &finished,
3585                        opts.max_attempts,
3586                    )
3587                    .await;
3588                let temporary = path.with_extension("json.tmp");
3589                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3590                std::fs::rename(temporary, path)?;
3591            }
3592        }
3593        "fetch" => {
3594            let cfg = prepare(&opts.repo, opts)?;
3595            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3596                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3597                tracing::debug!("fetch origins: {outcome:?}");
3598            }
3599        }
3600        "cache" => {
3601            if task_jobs(home)?.is_empty() {
3602                let mut checked = None;
3603                maybe_prune_cache_between_runs(
3604                    &opts.repo,
3605                    opts,
3606                    home,
3607                    &Stop::new(),
3608                    &mut checked,
3609                    Timestamp::now(),
3610                )
3611                .await;
3612            }
3613        }
3614        "disk-pressure" => {
3615            if let Ok(cfg) = prepare(&opts.repo, opts) {
3616                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3617                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3618                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3619                }
3620                for current in current_work(home, Timestamp::now()) {
3621                    if let Ok(state) = RunState::load_under(&current.run, home)
3622                        && let Some(reason) = disk_gate(&state.repo, &state.config)
3623                    {
3624                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
3625                            job.key.strip_prefix("task:") == Some(current.task.as_str())
3626                        }) {
3627                            request_task_park(
3628                                home,
3629                                &job,
3630                                crate::run::ParkCause::Interrupt {
3631                                    reason: reason.clone(),
3632                                },
3633                            )?;
3634                        }
3635                        notices::raise_in(
3636                            home,
3637                            Notice::warn(
3638                                "disk:pressure",
3639                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
3640                            ),
3641                        );
3642                    }
3643                }
3644            }
3645        }
3646        "housekeeping" => {
3647            if task_jobs(home)?.is_empty() {
3648                if let Ok(cfg) = prepare(&opts.repo, opts) {
3649                    crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3650                }
3651                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
3652                resweep_superseded_attempts(&queue, home);
3653                triage_held(&queue, home, opts).await;
3654            }
3655        }
3656        operation => bail!("unknown daemon service {operation}"),
3657    }
3658    Ok(())
3659}
3660
3661/// Only a different request under the same key is a dispatch handoff race.
3662/// Our own unacknowledged reservation is a startup failure, not competing work:
3663/// stop dispatch without fencing it, so an already detached child may still run.
3664fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
3665    let key = format!("task:{}", request.task);
3666    let payload = serde_json::to_value(request)?;
3667    if crate::worker::active(home)?
3668        .iter()
3669        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
3670    {
3671        tracing::warn!(
3672            "task {} acquired a competing worker reservation: {error:#}",
3673            crate::run::short_of(&request.task)
3674        );
3675        return Ok(());
3676    }
3677    tracing::error!("task worker startup stopped dispatch: {error:#}");
3678    notices::raise_in(
3679        home,
3680        Notice::error(
3681            "loop:worker-startup",
3682            // Startup diagnostics may contain private child-process details;
3683            // keep them in the local error/log rather than the chat or notifier.
3684            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),
3685        ).link(Link::Task { id: request.task.clone() }),
3686    );
3687    Err(error).with_context(|| {
3688        format!(
3689            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
3690            crate::run::short_of(&request.task)
3691        )
3692    })
3693}
3694
3695async fn poll(
3696    opts: &Opts,
3697    queue: &Queue,
3698    status: &Arc<Mutex<Status>>,
3699    home: &Path,
3700    worktrees_root: &Path,
3701    stop: &Stop,
3702    limits: DispatchLimits,
3703) -> Result<()> {
3704    let mut attempted = Vec::new();
3705    let mut settling_once_services = false;
3706    let interrupt_path = home.join("scheduler-interrupt.json");
3707    let mut interrupt = match std::fs::read(&interrupt_path) {
3708        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
3709        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
3710        Err(error) => return Err(error.into()),
3711    };
3712    let mut previous = std::collections::BTreeSet::<String>::new();
3713    while !stop.stopped() {
3714        let jobs: Vec<_> = crate::worker::active(home)?
3715            .into_iter()
3716            .filter(|job| job.kind == "task")
3717            .collect();
3718        let requests: Vec<_> = jobs
3719            .iter()
3720            .map(|job| {
3721                serde_json::from_value::<TaskWorker>(job.payload.clone())
3722                    .with_context(|| format!("read live task worker {}", job.id))
3723            })
3724            .collect::<Result<_>>()?;
3725        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
3726        let owned: std::collections::BTreeSet<_> = requests
3727            .iter()
3728            .filter(|r| !r.standalone)
3729            .map(|r| r.task.clone())
3730            .collect();
3731        let current: Vec<_> = requests
3732            .iter()
3733            .zip(&jobs)
3734            .filter(|(request, _)| !request.standalone)
3735            .map(|(request, job)| Current {
3736                worker: Some(job.id.clone()),
3737                task: request.task.clone(),
3738                run: queue
3739                    .get(&request.task)
3740                    .ok()
3741                    .and_then(|task| task.runs.last().cloned())
3742                    .unwrap_or_default(),
3743            })
3744            .collect();
3745        {
3746            let mut snapshot = lock(status);
3747            snapshot.polls += 1;
3748            snapshot.completed += previous.difference(&owned).count();
3749            snapshot.current = current;
3750            snapshot.idle = owned.is_empty();
3751        }
3752        previous = owned.clone();
3753        stop.busy.store(owned.len(), Ordering::SeqCst);
3754
3755        // Slots are reconstructed from durable reservations and OS-held worker
3756        // leases, not this scheduler's lifetime or mutable task urgency.
3757        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
3758        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
3759        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
3760        let mut permits = Vec::new();
3761        sweep_stale_claims(queue, STALE_CLAIM);
3762        reclaim_orphaned_running(queue, opts.max_attempts, &live);
3763        reclaim_abandoned_runs(home, Timestamp::now());
3764        let questions = Questions::at(home.join("questions"));
3765
3766        // Deterministic: no model, run before the conductor sees anything so
3767        // its input reflects the queue's current, already-resolved state.
3768        crate::task_chat::sweep(
3769            queue,
3770            &crate::talk::Talks::at(home.join("talks")),
3771            &questions,
3772            home,
3773        );
3774        repair_choice_offers(&questions);
3775        resolve_blockers(queue, &questions);
3776        apply_task_choice_actions(queue, &questions, home);
3777        triage::apply_answers(queue, &questions);
3778        reconcile_task_questions(queue, &questions);
3779        let talks = crate::talk::Talks::at(home.join("talks"));
3780        crate::chat_notify::sweep(queue, &talks, home);
3781        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
3782        crate::chat_watch::sweep(home, &talks);
3783        let mut turns = tokio::task::JoinSet::new();
3784        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
3785        // start_turns dispatches detached turns; no paid work lives in this set.
3786        while turns.join_next().await.is_some() {}
3787
3788        crate::consult::start_services(
3789            home,
3790            &opts.repo,
3791            limits.recovery_cfg.as_ref(),
3792            opts.config.as_deref(),
3793        )
3794        .await?;
3795        for operation in [
3796            "conductor",
3797            "maintenance",
3798            "housekeeping",
3799            "disk-pressure",
3800            "cache",
3801            "fetch",
3802        ] {
3803            // Once an idle --once drain starts settling services, subsequent
3804            // scans only consume their effects. An expired cadence receipt
3805            // must not start another service and keep the drain alive.
3806            if settling_once_services {
3807                break;
3808            }
3809            start_service(
3810                home,
3811                opts,
3812                queue,
3813                worktrees_root,
3814                operation,
3815                limits.recovery_cfg.as_ref(),
3816                !live.is_empty(),
3817            )
3818            .await?;
3819        }
3820        let latest = crate::worker::active(home)?;
3821        if latest.iter().any(|job| job.key == "service:daemon-cache")
3822            || latest
3823                .iter()
3824                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3825        {
3826            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3827            continue;
3828        }
3829        let candidates: Vec<Task> = runnable(queue)
3830            .into_iter()
3831            .filter(|task| !live.contains(&task.id))
3832            .filter(|task| !opts.once || !attempted.contains(&task.id))
3833            .collect();
3834        let in_flight: Vec<_> = owned.iter().cloned().collect();
3835        let prior_interrupt = std::mem::discriminant(&interrupt);
3836        interrupt = advance_interrupt_tick(
3837            limits.pause_for_interrupts,
3838            interrupt,
3839            &in_flight,
3840            &candidates,
3841        );
3842        // Same-variant transitions preserve their identities. Only an actual
3843        // transition needs a durable write, atomically before sending controls.
3844        if prior_interrupt != std::mem::discriminant(&interrupt) {
3845            let temporary = interrupt_path.with_extension("json.tmp");
3846            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
3847            std::fs::rename(temporary, &interrupt_path)?;
3848        }
3849        if let Interrupt::Parking {
3850            parked,
3851            interrupt_task,
3852        } = &interrupt
3853        {
3854            for job in jobs.iter().filter(|job| {
3855                parked
3856                    .iter()
3857                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
3858            }) {
3859                if crate::worker::control(home, &job.key)?.is_none() {
3860                    request_task_park(
3861                        home,
3862                        job,
3863                        crate::run::ParkCause::Interrupt {
3864                            reason: format!(
3865                                "task {} asked to run first",
3866                                crate::run::short_of(interrupt_task)
3867                            ),
3868                        },
3869                    )?;
3870                }
3871            }
3872        }
3873        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
3874        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
3875        let mut started = false;
3876        let mut resync = false;
3877        for candidate in candidates {
3878            if stop.stopped() {
3879                break;
3880            }
3881            let Some(DispatchClaim {
3882                task,
3883                claim,
3884                permit,
3885            }) = claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem)
3886            else {
3887                continue;
3888            };
3889            if crate::worker::active(home)?
3890                .iter()
3891                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
3892            {
3893                drop(claim);
3894                resync = true;
3895                break;
3896            }
3897            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
3898            let request = TaskWorker {
3899                opts: opts.absolute()?,
3900                queue: std::path::absolute(queue.root())?,
3901                task: task.id.clone(),
3902                lane,
3903                standalone: false,
3904            };
3905            // Keep the claim until spawn acknowledges the worker's durable
3906            // reservation. The worker then claims and re-reads before attempt.
3907            if let Err(error) = crate::worker::spawn(
3908                home,
3909                "task",
3910                &format!("task:{}", task.id),
3911                serde_json::to_value(&request)?,
3912            )
3913            .await
3914            {
3915                task_worker_spawn_error(home, &request, error)?;
3916                drop(claim);
3917                resync = true;
3918                break;
3919            }
3920            drop(claim);
3921            permits.extend(permit);
3922            attempted.push(task.id);
3923            started = true;
3924        }
3925        if started || resync {
3926            continue;
3927        }
3928        if owned.is_empty() && opts.once {
3929            settling_once_services = true;
3930            // These finite services can own queue claims or publish answers.
3931            // A skipped claim is not an idle queue until they have finished;
3932            // scan again afterwards so their changes are actually scheduled.
3933            if crate::worker::active(home)?.iter().any(|job| {
3934                job.kind == "daemon-service"
3935                    && matches!(
3936                        job.key.as_str(),
3937                        "service:daemon-housekeeping"
3938                            | "service:daemon-conductor"
3939                            | "service:daemon-maintenance"
3940                    )
3941            }) {
3942                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
3943                continue;
3944            }
3945            break;
3946        }
3947        stop.idle(if live.is_empty() {
3948            opts.poll
3949        } else {
3950            RECHECK_WHILE_BUSY.min(opts.poll)
3951        })
3952        .await;
3953    }
3954    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
3955    // every queue claim and Runner driver lease through outcome settlement.
3956    stop.busy.store(0, Ordering::SeqCst);
3957    Ok(())
3958}
3959
3960/// A maintenance pass may briefly own the same record while a worker starts.
3961/// Wait without blocking the executor or charging an agent attempt, then read
3962/// ownership again under the acquired lock. Other I/O failures still fail closed.
3963async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
3964    let busy = |error: &anyhow::Error| {
3965        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
3966            error.kind() == std::io::ErrorKind::WouldBlock
3967                || cfg!(windows) && error.raw_os_error() == Some(33)
3968        })
3969    };
3970    match crate::pr_head::owner_lock(home, id) {
3971        Ok(lock) => return Ok(lock),
3972        Err(error) if busy(&error) => {}
3973        Err(error) => return Err(error),
3974    }
3975    let wait = RunState::load_under(id, home)?
3976        .config
3977        .graph
3978        .timeout_resource_wait;
3979    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
3980}
3981
3982/// Historical successors do not revoke a still-resumable public owner. Scan
3983/// under the same lock as publication/driver claims, and fail closed on unknown
3984/// history before spending another attempt.
3985async fn public_resume_owner(
3986    home: &Path,
3987    runs: &[String],
3988    repo: &Path,
3989) -> Result<Option<RunState>> {
3990    let mut owner = None;
3991    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
3992        let _lock = resume_owner_lock(home, id).await?;
3993        let state = RunState::load_under(id, home)?;
3994        if state.released()
3995            || state.retired_to.is_some()
3996            || state.pr_taken_over_by.is_some()
3997            || !crate::handover::landing_checkpoint(&state)
3998        {
3999            continue;
4000        }
4001        anyhow::ensure!(
4002            crate::git::toplevel(&state.repo).await?.canonicalize()?
4003                == crate::git::toplevel(repo).await?.canonicalize()?,
4004            "public owner repository differs; inspect run lineage"
4005        );
4006        anyhow::ensure!(
4007            owner.is_none(),
4008            "multiple retained public owners; inspect run lineage"
4009        );
4010        anyhow::ensure!(
4011            crate::handover::can_resume(&state),
4012            "public owner cannot resume"
4013        );
4014        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4015        anyhow::ensure!(
4016            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4017            "public owner's driver is live or unknown; wait before retrying"
4018        );
4019        owner = Some(state);
4020    }
4021    Ok(owner)
4022}
4023
4024/// Run one claimed task to a terminal status and record the outcome.
4025///
4026/// Every transition is flushed to the queue as it happens, so the state on disk
4027/// is what actually occurred rather than what this process still intends to
4028/// write.
4029async fn attempt(
4030    opts: &Opts,
4031    queue: &Queue,
4032    status: &Arc<Mutex<Status>>,
4033    stop: &Stop,
4034    interrupt_pause: crate::graph::Pause,
4035    task: &mut Task,
4036) -> Vec<QuotaLoss> {
4037    let repo = repo_for(task, &opts.repo);
4038    tracing::info!(
4039        "task {} — {} (repo {})",
4040        task.short(),
4041        task.title,
4042        repo.display()
4043    );
4044
4045    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4046        Ok(owner) => owner,
4047        Err(e) => {
4048            task.hold_machine(Some(format!(
4049                "Cannot verify existing public owner: {e:#}; no attempt started."
4050            )));
4051            record(queue, task);
4052            return Vec::new();
4053        }
4054    };
4055    let resume_runs = public_owner
4056        .as_ref()
4057        .map(|s| vec![s.id.clone()])
4058        .unwrap_or_else(|| task.runs.clone());
4059
4060    // A stop spends no agent resources and uses the saved landing owner.
4061    // Current roster edits, missing attachments or a failed config fetch must
4062    // never turn it into a new implementation, or prevent a PR from closing.
4063    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4064        && previous
4065            .merge_decision
4066            .as_ref()
4067            .is_some_and(|decision| !decision.closed)
4068        && previous.status != RunStatus::Landing
4069        && !crate::merge_decision::resumable_hold(&previous)
4070    {
4071        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)));
4072        record(queue, task);
4073        return Vec::new();
4074    }
4075    let stop_owner = resume_runs
4076        .last()
4077        .and_then(|id| RunState::load(id).ok())
4078        .filter(|state| {
4079            crate::merge_decision::resumable_hold(state)
4080                || state.status == RunStatus::Landing
4081                    && state.land_approval.as_ref().is_some_and(|binding| {
4082                        Questions::open().get(&binding.question).is_ok_and(|q| {
4083                            q.run == state.id
4084                                && q.resolution()
4085                                    .as_deref()
4086                                    .is_some_and(crate::merge_decision::stops)
4087                        })
4088                    })
4089        });
4090    if let Some(owner) = stop_owner {
4091        let mut runner = match Runner::resume(&owner.id) {
4092            Ok(runner) => runner,
4093            Err(e) => {
4094                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4095                record(queue, task);
4096                return Vec::new();
4097            }
4098        };
4099        runner.on_pause(stop.pause());
4100        runner.watch_interrupt(interrupt_pause);
4101        let quota_before = runner.state.quota.clone();
4102        task.start(owner.id.clone());
4103        record(queue, task);
4104        lock(status).current.push(Current {
4105            worker: None,
4106            task: task.id.clone(),
4107            run: owner.id,
4108        });
4109        runner.state.next_pass_task_entry = true;
4110        let result = runner.execute().await;
4111        return finish_attempt(
4112            opts.max_attempts,
4113            queue,
4114            task,
4115            &runner.state,
4116            &quota_before,
4117            result,
4118        );
4119    }
4120
4121    if let Some(owner) = &public_owner
4122        && (task.fresh_start || !may_resume_run(owner, task))
4123    {
4124        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)));
4125        record(queue, task);
4126        return Vec::new();
4127    }
4128
4129    let unfinished = (!task.fresh_start)
4130        .then(|| unfinished_run(&resume_runs, task.short()))
4131        .flatten()
4132        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4133    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4134    if !task.fresh_start
4135        && task.pr_recovery.is_none()
4136        && task.review_branch.is_none()
4137        && task.resume_override.is_none()
4138        && previous
4139            .as_ref()
4140            .is_some_and(|run| run.retired_to.is_some())
4141        && unfinished.is_none()
4142    {
4143        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()));
4144        record(queue, task);
4145        return Vec::new();
4146    }
4147
4148    let saved_recovery = previous.as_ref().filter(|run| {
4149        task.replacement.is_none()
4150            && task.pr_recovery.as_ref().is_some_and(|selected| {
4151                selected.check_task(&task.id, &task.instruction).is_ok()
4152                    && selected_starter(selected, Some(run), unfinished.as_deref())
4153                        == Starter::Resume(run.id.clone())
4154            })
4155    });
4156
4157    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4158    // failure here is the network's or the operator's, not the task's: hold
4159    // without spending an attempt, never fall back to a possibly stale copy.
4160    let explicit = match &task.overrides {
4161        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4162        Some(_) => opts.config.as_deref(),
4163        None => opts.config.as_deref(),
4164    };
4165    let (mut config, layers) = if let Some(run) = saved_recovery {
4166        // A matching resume owns its resolved configuration and evidence;
4167        // current layers and inherited overrides only configure new work.
4168        let mut saved = run.clone();
4169        if let Err(e) = saved.configure_recovery_resume() {
4170            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4171            record(queue, task);
4172            return Vec::new();
4173        }
4174        (saved.config, Vec::new())
4175    } else {
4176        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4177            Ok(loaded) => loaded,
4178            Err(e) => {
4179                let reason = format!("[config] {e:#}");
4180                record_config_failure(task, &e);
4181                task.last_error = Some(reason.clone());
4182                task.hold_machine(Some(reason));
4183                record(queue, task);
4184                return Vec::new();
4185            }
4186        };
4187        if let Err(e) = apply_options(&mut config, opts, task) {
4188            task.hold_manual(Some(format!(
4189                "[config] {e:#}; correct the merge override before releasing the task"
4190            )));
4191            record(queue, task);
4192            return Vec::new();
4193        }
4194        if let Some(selected) = &task.pr_recovery
4195            && let Err(e) = selected.configure(&mut config)
4196        {
4197            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4198            record(queue, task);
4199            return Vec::new();
4200        }
4201        (config, layers)
4202    };
4203    let config_evidence = crate::pr_recovery::ConfigEvidence {
4204        layers,
4205        overrides: task.overrides.clone(),
4206        daemon_merge: task
4207            .overrides
4208            .as_ref()
4209            .is_none_or(|o| o.inherit_daemon_options)
4210            .then(|| opts.merge.clone())
4211            .flatten(),
4212    };
4213    apply_task_implementers(&mut config, task);
4214    if let Some(replacement) = &task.replacement {
4215        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4216            old.liveness(false) == Liveness::Dead
4217                && old.merge_decision.as_ref().is_some_and(|d| {
4218                    d.closed
4219                        && d.question == replacement.question
4220                        && d.replacement_run.as_ref().is_none_or(|run| {
4221                            task.runs.last() == Some(run)
4222                                && RunState::load(run).is_ok_and(|current| {
4223                                    current.replaces.as_ref().is_some_and(|pin| {
4224                                        pin.question == replacement.question
4225                                            && pin.agent == replacement.agent
4226                                    })
4227                                })
4228                        })
4229                })
4230        });
4231        if !safe {
4232            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()));
4233            record(queue, task);
4234            return Vec::new();
4235        }
4236        match config.agent(&replacement.agent) {
4237            Ok(agent) if crate::agent::installed(agent) => {}
4238            _ => {
4239                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)));
4240                record(queue, task);
4241                return Vec::new();
4242            }
4243        }
4244        config.graph.implementers = 1;
4245        config.graph.land_approval = true;
4246        config.merge.mode = MergeMode::Pr;
4247        config.graph.selected_implementer = Some(replacement.agent.clone());
4248    }
4249    let p = phrases(&config.graph.language);
4250    let start_failed = p.could_not_start;
4251    // Resolve once for both admission and settlement. The inputs are the
4252    // task's explicit sources (never prose), plus an explicit review source's
4253    // current head; review-only runs may rebase later, and neither fact can
4254    // refund a failed automatic generation.
4255    if let Ok(base) =
4256        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4257            .await
4258        && let Ok(head) =
4259            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4260    {
4261        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4262        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4263            let source = crate::git::rev_parse(&repo, branch)
4264                .await
4265                .unwrap_or_default();
4266            inputs.push_str(&format!(";review:{branch}:{source}"));
4267        }
4268        if let Some(reason) = task.recovery_exhausted(
4269            &head,
4270            &inputs,
4271            task.attempt_limit
4272                .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4273        ) {
4274            task.hold_unrequested_retry(Some(reason));
4275            record(queue, task);
4276            return Vec::new();
4277        }
4278        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4279    }
4280
4281    // The free-space gate, checked *before* anything is minted: a task that
4282    // waits out a full disk costs nothing yet, and must not spend an attempt
4283    // or start a run the machine cannot finish. Held tasks stay in the list
4284    // for the human to see, and `magi task release` re-queues them when space
4285    // comes back - the same recovery as any other hold. A volume whose free
4286    // space cannot be measured closes the gate too: starting a run blind on a
4287    // disk that may be full is how the machine ends up with 6.7 GB free.
4288    if let Some(reason) = disk_gate(&repo, &config) {
4289        task.notice_cause("disk-space", None, None);
4290        task.last_error = Some(reason.clone());
4291        task.hold_machine(Some(reason.clone()));
4292        record(queue, task);
4293        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4294        // Stable wording - the free-space figures live in the task's hold
4295        // reason, and changing numbers would relight the bell every poll.
4296        notices::raise(
4297            Notice::warn(
4298                &format!("disk:{}", repo.display()),
4299                format!("Task {} held for want of free disk space: {reason}. Free some, then release it from the queue.", task.id),
4300            )
4301            .link(Link::Task {
4302                id: task.id.clone(),
4303            }),
4304        );
4305        return Vec::new();
4306    }
4307
4308    // A resumable run of this task is carried on, never re-competed. The
4309    // candidates are built and paid for, and a fresh competition races a
4310    // second implementation against them.
4311    //
4312    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4313    // started 3cbf on the same task a moment later, duplicating two and a
4314    // half hours of agent work. Then b25f stalled on a judge that timed out
4315    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4316    // was to blame for - and 4043 started **one second** later, buying three
4317    // fresh implementations to reach the same panel. `RunStatus::resumable`
4318    // rather than `!done()` is what catches the second case: a stall is
4319    // terminal, and its cheap recovery re-asks only the absent seats.
4320    //
4321    // A load failure is warned about rather than silently read as "not
4322    // resumable": the alternative is exactly what let a schema mismatch on
4323    // run `eba2` fall through to a full re-competition with nobody told why.
4324    // `crate::conduct` is what actually offers a better answer than
4325    // `Runner::start` here (see `Recovery::Review`), once this task's next
4326    // failure shows it up as `held`/`failed` with the run state unreadable.
4327    // `crate::conduct` chose `Review` for this task on an earlier cycle: its
4328    // branch survived, and this reopens exactly that branch as a
4329    // review-only pass rather than resuming or competing again. Consumed
4330    // (cleared) here whichever way this goes, so it never outlives this one
4331    // attempt - see `queue::Task::review_branch`.
4332    let review_branch = take_review_branch(task, previous.as_ref());
4333    let branch_exists = match &review_branch {
4334        Some(branch) => crate::git::branch_exists(&repo, branch)
4335            .await
4336            .unwrap_or(false),
4337        None => false,
4338    };
4339    // An explicit `magi review <branch>` is reviewed whatever happens to the
4340    // branch unless an explicit implementer change requires fresh work. An
4341    // unfinished run of the same task still wins, so a retry resumes.
4342    let proposed = review_retry_starter(
4343        task,
4344        previous.as_ref(),
4345        review_branch.as_deref(),
4346        branch_exists,
4347        unfinished.as_deref(),
4348    );
4349    let retry_selected = task.replacement.is_some()
4350        && task.resumption.is_some()
4351        && !task.fresh_start
4352        && previous.as_ref().is_some_and(|run| {
4353            run.replaces.is_some()
4354                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4355                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4356        });
4357    let stop_pin = task
4358        .resume_override
4359        .as_ref()
4360        .filter(|pin| {
4361            Questions::open().get(&pin.question_id).is_ok_and(|q| {
4362                q.node == land::APPROVAL_NODE
4363                    && q.resolution()
4364                        .as_deref()
4365                        .is_some_and(crate::merge_decision::stops)
4366            })
4367        })
4368        .and_then(|pin| pin.pinned_run.clone());
4369    let starter = if let Some(owner) = &public_owner {
4370        Starter::Resume(owner.id.clone())
4371    } else if let Some(run) = stop_pin {
4372        // Stop actions resume their exact owner even after seat-count edits;
4373        // they must never fall through to implementation or a takeover.
4374        Starter::Resume(run)
4375    } else if retry_selected {
4376        Starter::Resume(previous.as_ref().unwrap().id.clone())
4377    } else if let Some(selected) = &task.pr_recovery {
4378        if selected.check_task(&task.id, &task.instruction).is_ok() {
4379            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4380        } else {
4381            Starter::Review(selected.branch.clone())
4382        }
4383    } else {
4384        starter_with_implementers(task, previous.as_ref(), proposed)
4385    };
4386    // An explicit resume pin must never degrade into a new competition or
4387    // takeover, including when its run stops being eligible after the answer.
4388    if let Some(pin) = &task.resume_override
4389        && let Some(run) = &pin.pinned_run
4390        && starter != Starter::Resume(run.clone())
4391    {
4392        let run = run.clone();
4393        task.notice_cause("resume-owner", Some(&run), None);
4394        task.hold_machine(Some(format!(
4395            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4396            task.id
4397        )));
4398        record(queue, task);
4399        return Vec::new();
4400    }
4401    if task.replacement.is_some()
4402        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4403        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4404    {
4405        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()));
4406        record(queue, task);
4407        return Vec::new();
4408    }
4409    if let Some(reason) = retained_attempt_hold(
4410        task,
4411        &starter,
4412        config.disk.retained_attempt_limit,
4413        RunState::load,
4414    ) {
4415        // The review choice was consumed above. Preserve it across this hold
4416        // so a later release cannot silently become a fresh implementation.
4417        if let Starter::Review(branch) = &starter {
4418            task.review_branch = Some(branch.clone());
4419        }
4420        task.hold_unrequested_retry(Some(reason));
4421        record(queue, task);
4422        return Vec::new();
4423    }
4424    // Absolute paths of the files the task was filed with, re-read from the
4425    // task now so a file attached while it was held reaches a resumed run
4426    // too. A stored name whose file has gone is an error before any agent is
4427    // paid for, never a silent omission the implementer cannot notice.
4428    let attachments = match task_attachments(queue, task) {
4429        Ok(a) => a,
4430        Err(e) => {
4431            task.attempts += 1;
4432            task.fail_startup_target(
4433                "startup-attachments",
4434                e.name.clone(),
4435                format!("{start_failed}{e:#}"),
4436                opts.max_attempts,
4437            );
4438            record(queue, task);
4439            return Vec::new();
4440        }
4441    };
4442    let startup_pause = stop.pause();
4443    let startup_interrupt = interrupt_pause.clone();
4444    let wait = crate::repo_lock::WaitPolicy::new(
4445        Duration::from_secs(config.graph.timeout_resource_wait),
4446        move || startup_pause.parked() || startup_interrupt.parked(),
4447    );
4448    // Startup includes review takeover and recovery. Do not embed its large
4449    // future in both the wait scope and the surrounding attempt stack frame.
4450    let started = wait.scope(Box::pin(async { match &starter {
4451        Starter::Review(_) if task.pr_recovery.is_some() => {
4452            let selected = task.pr_recovery.clone().expect("selected recovery");
4453            match selected.check_task(&task.id, &task.instruction) {
4454                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
4455                    .await
4456                    .map(|mut r| {
4457                        r.state.attachments = attachments.clone();
4458                        r
4459                    }),
4460                Err(e) => Err(e),
4461            }
4462        }
4463        Starter::Review(branch) => {
4464            tracing::info!(
4465                "task {} reopens `{branch}` as a review-only pass",
4466                task.short()
4467            );
4468            // Every earlier attempt is superseded by the one being minted
4469            // now, so a branch one of them still holds may be taken over.
4470            let takeover = crate::handover::Takeover {
4471                earlier: task.earlier_attempts().to_vec(),
4472                home: crate::run::home(),
4473                choice: take_divergence_answer(branch, &config.merge.remote, task),
4474                task_instruction: Some(instruction_for(task)),
4475            };
4476            Runner::review_taking_over(
4477                &repo,
4478                branch,
4479                config,
4480                Some(takeover),
4481                crate::run::Origin::queue(&task.id),
4482            )
4483            .await
4484        }
4485        Starter::Resume(id) => {
4486            tracing::info!("resuming run {id} rather than competing again");
4487            Runner::resume(id).and_then(|mut r| {
4488                if retry_selected {
4489                    // The explicit queue release retries this same pinned
4490                    // implementation, preserving the attempt and worktrees.
4491                    for candidate in &mut r.state.candidates {
4492                        candidate.failed = None;
4493                        candidate.empty = false;
4494                        candidate.commits = 0;
4495                    }
4496                    r.state.status = RunStatus::Implementing;
4497                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
4498                }
4499                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
4500                    r.state.sources = task.sources.clone();
4501                }
4502                if r.state.prep_failure.is_some() {
4503                    let approval = task
4504                        .resumption
4505                        .as_ref()
4506                        .context("preparation retry requires an explicit task release")?;
4507                    r.retry_preparation(approval.at)?;
4508                }
4509                if let Some(instruction) =
4510                    prepare_instruction(&starter, Some(&r.state.instruction), task)
4511                {
4512                    r.state.instruction = instruction;
4513                }
4514                r.state.attachments = attachments.clone();
4515                if task.replacement.is_some() {
4516                    r.state.config.merge.mode = MergeMode::Pr;
4517                    r.state.config.graph.land_approval = true;
4518                }
4519                // Replacements publish a new PR and ask again. Selected PR
4520                // recoveries keep their saved disposition; ordinary runs can
4521                // retain the task's merge override.
4522                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
4523                    .overrides
4524                    .as_ref()
4525                    .and_then(|o| o.merge.as_deref())
4526                    .and_then(|m| merge_mode(m).ok())
4527                {
4528                    r.state.config.merge.mode = mode;
4529                }
4530                Ok(r)
4531            })
4532        }
4533        Starter::Start => {
4534            if let Some(branch) = &review_branch {
4535                tracing::warn!(
4536                    "conductor chose review for task {} but branch `{branch}` no longer \
4537                     exists; requeuing as a fresh competition instead",
4538                    task.short()
4539                );
4540            }
4541            let instruction = prepare_instruction(&starter, None, task)
4542                .unwrap_or_else(|| task.instruction.clone());
4543            Runner::start_naming(
4544                &repo,
4545                instruction,
4546                &task.title,
4547                config,
4548                crate::run::Origin::queue(&task.id),
4549            )
4550            .await
4551            .map(|mut r| {
4552                r.state.attachments = attachments.clone();
4553                r.state.sources = task.sources.clone();
4554                r
4555            })
4556        }
4557    }})).await;
4558    let mut runner = match started {
4559        Ok(r) => r,
4560        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
4561            task.last_error = Some(e.to_string());
4562            if stop.parking() || interrupt_pause.parked() {
4563                let attempts = task.attempts;
4564                task.park(e.to_string());
4565                // Startup has not spent an attempt to refund.
4566                task.attempts = attempts;
4567            } else {
4568                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
4569            }
4570            record(queue, task);
4571            return Vec::new();
4572        }
4573        // A branch an earlier attempt still holds and magi will not release
4574        // by itself is the operator's call, not a failed attempt: hold the
4575        // task with the reason, spend nothing, and say so on the bell.
4576        Err(e) if task.pr_recovery.is_some() => {
4577            task.startup_notice_cause("startup-public-head");
4578            task.attempts += 1;
4579            if let Some(partial) = e.downcast_ref::<crate::pr_recovery::StartupFailed>() {
4580                task.link_run(&partial.run);
4581                task.record_pass(&partial.run, 0, task.attempts, None);
4582            }
4583            task.last_error = Some(format!("{start_failed}{e:#}"));
4584            task.hold_unrequested_retry(Some(format!(
4585                "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."
4586            )));
4587            record(queue, task);
4588            return Vec::new();
4589        }
4590        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
4591            let detail = match e.downcast_ref::<crate::handover::Refused>() {
4592                Some(r) => (p.handover_refused)(r),
4593                None => format!("{e:#}"),
4594            };
4595            task.startup_notice_cause("startup-handover");
4596            let reason = format!("{start_failed}{detail}");
4597            task.last_error = Some(reason.clone());
4598            // Consumed above by `take`; keep it so the released task retries
4599            // as a review of this same branch.
4600            let branch = match &starter {
4601                Starter::Review(branch) => Some(branch.clone()),
4602                _ => None,
4603            };
4604            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
4605            // one page; the guidance rides in the reason, fixed per state so a
4606            // re-put never changes the wording and relights it.
4607            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
4608            record(queue, task);
4609            tracing::warn!(
4610                "holding {} for a branch it cannot take over: {e:#}",
4611                task.short()
4612            );
4613            return Vec::new();
4614        }
4615        // A branch that differs between here and the remote in ways magi
4616        // cannot prove are the same change is a decision for the owner, not a
4617        // failed attempt: ask with both sides laid out, spend no attempt, and
4618        // let the answer requeue the task.
4619        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
4620            let d = e
4621                .downcast_ref::<crate::reconcile::Diverged>()
4622                .expect("checked by the guard");
4623            let mut q = ask::Question::new(
4624                task.id.clone(),
4625                crate::reconcile::NODE.to_owned(),
4626                crate::reconcile::SEAT.to_owned(),
4627                d.summary(),
4628                d.detail(),
4629                d.choices(),
4630            );
4631            match Questions::open().put(&mut q) {
4632                Ok(()) => {
4633                    task.last_error = Some(format!("{e:#}"));
4634                    // Consumed above by `take`; the answer has to reach a review
4635                    // of this same branch, so keep pointing the task at it.
4636                    task.review_branch = Some(d.branch.clone());
4637                    task.review_instruction = Some(task.instruction.clone());
4638                    task.block(vec![q.id.clone()], Some(d.summary()));
4639                }
4640                Err(put) => {
4641                    tracing::warn!("could not file the divergence question: {put:#}");
4642                    task.attempts += 1;
4643                    task.fail_startup(
4644                        "startup-question-store",
4645                        format!("{start_failed}{e:#}"),
4646                        opts.max_attempts,
4647                    );
4648                }
4649            }
4650            record(queue, task);
4651            return Vec::new();
4652        }
4653        Err(e) => {
4654            // The answer was stale and nothing was applied: keep pointing at
4655            // the branch so the next attempt asks again against its new tips.
4656            // Nothing went wrong with the task, so no attempt is spent: a
4657            // budget one short of its limit must not hold it instead of
4658            // letting the question be asked again.
4659            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
4660                && let Starter::Review(branch) = &starter
4661            {
4662                task.review_branch = Some(branch.clone());
4663                task.review_instruction = Some(task.instruction.clone());
4664                task.last_error = Some(format!("{start_failed}{e:#}"));
4665                task.status = crate::queue::TaskStatus::Failed;
4666                record(queue, task);
4667                return Vec::new();
4668            }
4669            task.attempts += 1;
4670            task.last_error = Some(format!("{start_failed}{e:#}"));
4671            task.startup_notice_cause("startup-source");
4672            task.hold_unrequested_retry(Some(format!(
4673                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
4674            )));
4675            record(queue, task);
4676            return Vec::new();
4677        }
4678    };
4679    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
4680        runner.state.recovery_config = Some(config_evidence);
4681    }
4682    if let Some(replacement) = &task.replacement {
4683        if matches!(starter, Starter::Start) {
4684            runner.state.instruction.push_str(&format!(
4685                "\n\n# Replacement review context\n{}",
4686                replacement.context
4687            ));
4688        }
4689        runner.state.replaces = Some(replacement.clone());
4690        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
4691        if let Ok(mut old) = RunState::load(&replacement.run)
4692            && let Some(d) = &mut old.merge_decision
4693        {
4694            d.replacement_run = Some(runner.state.id.clone());
4695            old.event(
4696                "replacement",
4697                format!(
4698                    "replacement run {} owns the next attempt; old PR remains closed",
4699                    runner.state.id
4700                ),
4701            );
4702            if let Err(e) = old.save() {
4703                task.hold_manual(Some(format!(
4704                    "Could not link replacement history: {e}; no agents dispatched"
4705                )));
4706                record(queue, task);
4707                return Vec::new();
4708            }
4709        }
4710    }
4711    runner.state.task_instruction = Some(task.instruction.clone());
4712    // The follow-up depth is fixed now, while the task certainly exists:
4713    // deleting it later must not reset the cap (`crate::followup`).
4714    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
4715    if runner.state.origin_chat.is_none() {
4716        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
4717    }
4718    // A stop that means "park" reaches the graph through this handle.
4719    runner.on_pause(stop.pause());
4720    // `poll`'s interrupt scheduler reaches this one run - and no other -
4721    // through this handle. See `Pause`'s own doc for why these are never
4722    // the same one.
4723    runner.watch_interrupt(interrupt_pause);
4724
4725    // `start` has minted the run, so the task can now point at it. Persisting
4726    // `Running` before `execute` is what makes a crash mid-run legible.
4727    let run = runner.state.id.clone();
4728    task.start(run.clone());
4729    record(queue, task);
4730    lock(status).current.push(Current {
4731        worker: None,
4732        task: task.id.clone(),
4733        run,
4734    });
4735
4736    // `RunState::quota` is the run's whole history across every resume, so
4737    // only what this execution added may arm the cooldown or earn a refund.
4738    let quota_before = runner.state.quota.clone();
4739    runner.state.next_pass_task_entry = true;
4740    let result = runner.execute().await;
4741    finish_attempt(
4742        opts.max_attempts,
4743        queue,
4744        task,
4745        &runner.state,
4746        &quota_before,
4747        result,
4748    )
4749}
4750
4751/// Settle `task` after its run executed: the verdict, the diagnosis, the
4752/// supersession of earlier attempts and the save. Shared by the loop and by
4753/// `magi run --resume`, so an attempt is counted one way wherever it ran.
4754/// Returns the quota losses this execution added to the run.
4755pub fn finish_attempt(
4756    max_attempts: usize,
4757    queue: &Queue,
4758    task: &mut Task,
4759    state: &RunState,
4760    quota_before: &[QuotaLoss],
4761    result: Result<()>,
4762) -> Vec<QuotaLoss> {
4763    let detail = match result {
4764        Ok(()) => describe(state),
4765        Err(e) => format!("{e:#}"),
4766    };
4767    let fresh = losses_this_attempt(quota_before, &state.quota);
4768    let verdict = Verdict {
4769        status: state.status,
4770        // A run that opened a pull request handed its work over, whatever the
4771        // gate then decided about merging it.
4772        left_pr: state.pr.is_some(),
4773        // Only a rate limit earns the task its attempt back - and only one
4774        // suffered now: a refund justified by a previous session's loss is
4775        // the same mistake as re-arming the cooldown from it. A stalled run
4776        // resumed without hitting quota again therefore spends its attempt,
4777        // like any other failure of the task's own.
4778        quota_hit: !fresh.is_empty(),
4779        // A run that parked was asked to stop; that is not a failure and must
4780        // not spend an attempt, or replacing the binary a few times would
4781        // exhaust a task's budget without an agent ever misbehaving.
4782        parked: state.parked,
4783        // A quota loss that left nothing viable is the same machine fact as a
4784        // `Stalled` quota loss; see `settle`'s doc table.
4785        no_viable_candidates: state.viable().is_empty(),
4786    };
4787    if let Some(replacement) = &state.replaces
4788        && let Some(pr) = &state.pr
4789        && let Ok(mut old) = RunState::load(&replacement.run)
4790        && let Some(d) = &mut old.merge_decision
4791    {
4792        d.replacement_pr = Some(pr.url.clone());
4793        let _ = old.save();
4794    }
4795    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
4796    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
4797        task.hold_unrequested_retry(Some(format!(
4798            "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.",
4799            task.short()
4800        )));
4801    }
4802    if task.status == TaskStatus::Done {
4803        supersede_prior_runs(task, &crate::run::home());
4804    }
4805    record(queue, task);
4806    tracing::info!(
4807        "task {} is {} after run {} ({})",
4808        task.short(),
4809        task.status.as_str(),
4810        state.short(),
4811        label(state.status)
4812    );
4813    fresh
4814}
4815
4816/// A task a hand-started run leaves runnable (failed with attempts to spare,
4817/// or requeued) is **held**: nobody asked for a retry, and a loop starting
4818/// later must not spend agent calls on it. `magi task release` retries.
4819pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
4820    // Parked work (including legacy Failed records with a parked run) is a
4821    // checkpoint or owner handoff, not an unrequested retry.
4822    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
4823        && !awaiting_resume_with(task, RunState::load)
4824        // A run parked on the owner's word about a withheld PR title/body
4825        // resumes via `land_resume_state`, including review-only tasks that
4826        // `awaiting_resume_with` does not consider.
4827        && withheld_text_wait(task).is_none()
4828        && !(task.fresh_start && task.replacement.is_some())
4829    {
4830        let why = task.last_error.clone().map_or_else(
4831            || "the run did not finish".to_owned(),
4832            |e| format!("the run did not finish: {e}"),
4833        );
4834        task.hold_unrequested_retry(Some(format!(
4835            "{why}. It was started by hand, so it is not retried \
4836             automatically; `magi task release` retries it."
4837        )));
4838        record(queue, task);
4839    }
4840}
4841
4842/// Whether an attempt at a task whose newest run is `run` would resume that
4843/// run rather than start a fresh competition. `magi run --resume` hands a run
4844/// to a live loop only when this holds.
4845#[must_use]
4846pub fn loop_would_resume(run: &str) -> bool {
4847    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
4848}
4849
4850/// A loop in another process that is alive right now: a fresh heartbeat in
4851/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
4852/// carries the pid it published (`None` inside when it published none - a
4853/// fresh heartbeat is still evidence of a live loop).
4854///
4855/// The one judgement of "is somebody else serving this queue", shared by the
4856/// web UI's refusal to start a second loop and by `magi run` / `magi review`
4857/// deciding whether to hand a task to the loop. A claim file proves nothing
4858/// here: whether a claim succeeds says nothing about whether its owner lives.
4859#[must_use]
4860pub fn foreign_loop(
4861    reading: Option<&Reading>,
4862    now: Timestamp,
4863    own_pid: u32,
4864) -> Option<Option<u32>> {
4865    let reading = reading.filter(|r| r.running(now))?;
4866    match reading.pid {
4867        Some(pid) if pid == own_pid => None,
4868        pid => Some(pid),
4869    }
4870}
4871
4872fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
4873    reading.worker_protocol != Some(1)
4874        && (foreign_loop(Some(reading), now, own_pid).is_some()
4875            || reading
4876                .pid
4877                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
4878}
4879
4880/// Low-level claimed-task execution shared by the detached standalone worker
4881/// and focused lifecycle fixtures. The caller must retain the queue claim for
4882/// this entire call. CLI callers transfer ownership through
4883/// [`run_detached_claimed`] instead of executing inside their own runtime.
4884///
4885/// The one deliberate difference from the loop: a task the attempt leaves
4886/// runnable (failed with attempts to spare, or requeued) is **held** instead.
4887/// Nobody asked for a retry, and a daemon starting later must not spend agent
4888/// calls re-running a hand-started task behind the operator's back;
4889/// `magi task release` is the explicit retry.
4890pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
4891    run_claimed_until(opts, queue, task, &Stop::new()).await;
4892}
4893
4894async fn run_claimed_until(
4895    opts: &Opts,
4896    queue: &Queue,
4897    task: &mut Task,
4898    stop: &Stop,
4899) -> Vec<QuotaLoss> {
4900    let status = Arc::new(Mutex::new(Status::new()));
4901    // An attempt embeds startup and graph futures. Keep it off the standalone
4902    // caller's stack, on both the initial execution and withheld-text resume.
4903    let mut quota = Box::pin(attempt(
4904        opts,
4905        queue,
4906        &status,
4907        stop,
4908        crate::graph::Pause::new(),
4909        task,
4910    ))
4911    .await;
4912    // A run parked on the owner's word about a withheld PR title/body has no
4913    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
4914    // here with the claim still held, and resume once the question is settled
4915    // (answered, or abandoned at its deadline -> the neutral text).
4916    // A rejected reply files one more question (the gate asks at most twice),
4917    // so after a resume the run may be waiting again: keep going, with a fresh
4918    // limit for the new question. `resumes` bounds it even if a resume parks
4919    // without asking anything new.
4920    let mut resumes = 0;
4921    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
4922        let Some(timeout) = withheld_text_wait(task) else {
4923            break;
4924        };
4925        eprintln!(
4926            "waiting for the owner's answer on a withheld pull request text \
4927             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
4928        );
4929        // The deadline abandons the question itself; the extra margin only
4930        // covers an abandon that could not be saved.
4931        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
4932        let ready = loop {
4933            match land_resume_state(task) {
4934                LandResume::StillWaiting
4935                    if !stop.parking() && std::time::Instant::now() < limit =>
4936                {
4937                    tokio::time::sleep(WITHHELD_POLL).await;
4938                }
4939                LandResume::Ready => break true,
4940                _ => break false,
4941            }
4942        };
4943        if !ready || stop.parking() {
4944            break;
4945        }
4946        resumes += 1;
4947        quota.extend(
4948            Box::pin(attempt(
4949                opts,
4950                queue,
4951                &status,
4952                stop,
4953                crate::graph::Pause::new(),
4954                task,
4955            ))
4956            .await,
4957        );
4958    }
4959    hold_if_runnable(queue, task);
4960    quota
4961}
4962
4963/// Resumes an in-process run makes for withheld-text questions: the gate asks
4964/// at most twice, plus one for a resume that asks nothing new.
4965const MAX_WITHHELD_RESUMES: u32 = 3;
4966
4967/// How often an in-process run rechecks its withheld-text question.
4968const WITHHELD_POLL: Duration = Duration::from_secs(15);
4969
4970/// The `answer_timeout` (seconds) of the task's last run when that run is
4971/// parked on an unresolved withheld-text question; `None` otherwise.
4972fn withheld_text_wait(task: &Task) -> Option<u64> {
4973    let id = task.runs.last()?;
4974    let s = RunState::load(id).ok()?;
4975    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
4976        .then_some(s.config.graph.answer_timeout)
4977}
4978
4979/// The quota losses `after` holds that `before` did not: what one execution
4980/// suffered, as opposed to the run's history.
4981///
4982/// Compared by value rather than by length or position because
4983/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
4984/// the vector can shrink and shift under a resume. A retried seat that hits
4985/// quota again is a `push` with a new `at`, so it shows up as new here.
4986/// `reclaim` deliberately keeps reading the whole history: after a crash there
4987/// is no attempt boundary to diff against.
4988fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
4989    after
4990        .iter()
4991        .filter(|q| !before.contains(q))
4992        .cloned()
4993        .collect()
4994}
4995
4996/// When the loop-wide quota cooldown should end, given this attempt's losses;
4997/// `None` when there were none. Reset-hint parsing and the cap live here.
4998fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
4999    if quota.is_empty() {
5000        return None;
5001    }
5002    let with_hint = quota.iter().find(|q| q.reset.is_some());
5003    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5004    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5005    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5006    Some(
5007        now.checked_add(jiff::SignedDuration::from_secs(secs))
5008            .unwrap_or(Timestamp::MAX),
5009    )
5010}
5011
5012/// An explicit task count must agree with a run before any resume.
5013fn implementers_match(task: &Task, state: &RunState) -> bool {
5014    task.replacement.as_ref().map_or_else(
5015        || {
5016            task.implementers()
5017                .is_none_or(|n| n == state.config.graph.implementers)
5018        },
5019        |replacement| {
5020            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5021                && state.config.graph.implementers == 1
5022        },
5023    )
5024}
5025
5026/// Never resume or take over candidate work built for a different seat count.
5027fn starter_with_implementers(
5028    task: &Task,
5029    previous: Option<&RunState>,
5030    proposed: Starter,
5031) -> Starter {
5032    if previous.is_some_and(|s| !implementers_match(task, s)) {
5033        task.review_of
5034            .as_ref()
5035            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5036    } else {
5037        proposed
5038    }
5039}
5040
5041/// Apply this task's explicit count to the new attempt, without changing defaults.
5042fn apply_task_implementers(config: &mut Config, task: &Task) {
5043    if let Some(n) = task.implementers() {
5044        config.graph.implementers = n;
5045    }
5046}
5047
5048/// [`prepare`] for one task: its own `--config` and command-line overrides
5049/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5050/// over the loop's, so handing a hand-started task to a daemon changes nothing
5051/// about what it does.
5052#[cfg(test)]
5053fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5054    let explicit = match &task.overrides {
5055        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5056        _ => opts.config.as_deref(),
5057    };
5058    let (mut config, _) = Config::discover(repo, explicit)?;
5059    apply_options(&mut config, opts, task)?;
5060    Ok(config)
5061}
5062
5063fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5064    if task
5065        .overrides
5066        .as_ref()
5067        .is_none_or(|o| o.inherit_daemon_options)
5068        && let Some(mode) = opts.merge.as_deref()
5069    {
5070        config.merge.mode = merge_mode(mode)?;
5071    }
5072    if let Some(o) = &task.overrides {
5073        o.apply(config);
5074    }
5075    Ok(())
5076}
5077
5078/// Load the config for a task's repository, with the merge override applied.
5079fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5080    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5081    if let Some(mode) = &opts.merge {
5082        config.merge.mode = merge_mode(mode)?;
5083    }
5084    Ok(config)
5085}
5086
5087/// Prune the shared build cache at a between-runs boundary. The detached cache
5088/// service checks authoritative task jobs first; dispatch waits for that finite
5089/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5090/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5091async fn maybe_prune_cache_between_runs(
5092    repo: &Path,
5093    opts: &Opts,
5094    home: &Path,
5095    stop: &Stop,
5096    last_checked: &mut Option<Timestamp>,
5097    now: Timestamp,
5098) {
5099    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5100        return;
5101    }
5102    *last_checked = Some(now);
5103    let cfg = match prepare(repo, opts) {
5104        Ok(cfg) => cfg,
5105        Err(e) => {
5106            tracing::warn!("cache check: no config: {e:#}");
5107            return;
5108        }
5109    };
5110    match clean::prune_cache_if_over_limit(&cfg, home) {
5111        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5112            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5113            pruned.files,
5114            pruned.freed
5115        ),
5116        Ok(_) => {}
5117        Err(e) => {
5118            tracing::warn!("housekeep: prune cache: {e:#}");
5119            notices::raise_in(
5120                home,
5121                Notice::warn(
5122                    "housekeep:cache",
5123                    format!(
5124                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5125                        e.to_string()
5126                            .lines()
5127                            .next()
5128                            .unwrap_or("unknown cleanup error")
5129                    ),
5130                ),
5131            );
5132        }
5133    }
5134}
5135
5136/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5137/// now, given when it last did (if ever). Pure, so the cadence is asserted
5138/// directly rather than by waiting out real minutes in a test.
5139fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5140    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5141}
5142
5143/// The disk janitor, with its housekeeping logged rather than fatal.
5144///
5145/// Called only at the loop's idle points, for the reason the caller documents:
5146/// a prune racing a live compile would delete files mid-build. The config is
5147/// re-read on every call because the repository that just ran may not be the
5148/// daemon's own default, and the cache directory is a repository fact.
5149///
5150/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5151/// and [`crate::run::default_worktree_root`] read here, for the same reason
5152/// [`drive`] takes its queue and status file rather than resolving them: a
5153/// test driving the loop must not reach through to the operator's real home
5154/// or worktree bay just because the janitor runs on every idle tick.
5155/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5156/// to get wrong silently - a test's `home` was already isolated, but nothing
5157/// exercised the parameter next to it, so a real worktree bay stayed wired in
5158/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5159/// it for real, every test in this file that drives the loop at all started
5160/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5161async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5162    let cfg = match prepare(repo, opts) {
5163        Ok(cfg) => cfg,
5164        Err(e) => {
5165            tracing::warn!("housekeep: no config: {e:#}");
5166            return;
5167        }
5168    };
5169    // A run's own worktree lives under `config.graph.worktree_root` when the
5170    // repository sets one - the same precedence `RunState::worktree_root`
5171    // uses - and `worktrees_root` only stands in for the *default* an
5172    // unconfigured repository resolves to (see this function's own
5173    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5174    // that always swept the default regardless of this override would never
5175    // see, and so never reclaim, a single worktree for a repository that
5176    // relocated them elsewhere.
5177    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5178    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5179    // Reported whenever there is anything to say, not only when `folded > 0`:
5180    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5181    // folded, on every single pass, for months - a report gated on `folded`
5182    // would have stayed silent through every one of them.
5183    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5184        let mut extra = Vec::new();
5185        if out.unreadable > 0 {
5186            extra.push(format!("{} unreadable", out.unreadable));
5187        }
5188        if out.orphaned_worktrees > 0 {
5189            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5190        }
5191        let detail = if extra.is_empty() {
5192            String::new()
5193        } else {
5194            format!(" ({})", extra.join(", "))
5195        };
5196        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5197    }
5198    if out.external_merges_recorded > 0 {
5199        tracing::info!(
5200            "housekeep: recorded {} run(s) as merged externally",
5201            out.external_merges_recorded
5202        );
5203    }
5204    if out.stale_pr_states_repaired > 0 {
5205        tracing::info!(
5206            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5207            out.stale_pr_states_repaired
5208        );
5209    }
5210    if out.cache_files > 0 {
5211        tracing::info!(
5212            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5213            out.cache_files,
5214            out.cache_freed
5215        );
5216    }
5217    if out.questions_abandoned > 0 {
5218        tracing::info!(
5219            "housekeep: abandoned {} question(s) left open by a finished run",
5220            out.questions_abandoned
5221        );
5222    }
5223}
5224
5225/// Run [`triage::run_once`] and log whatever it did, the same "only when
5226/// there is something to say" rule [`janitor`] follows for its own report.
5227///
5228/// Called at the same idle points as [`janitor`] - once per full poll
5229/// interval, never mid-attempt - for the same reason: it is not liveness
5230/// critical, and a task's own `hold_reason` string is the one thing this
5231/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5232/// tick for no benefit.
5233async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5234    let questions = Questions::at(home.join("questions"));
5235    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5236    if report.is_empty() {
5237        return;
5238    }
5239    if !report.quarantined.is_empty() {
5240        tracing::info!(
5241            "triage: held {} blocked task(s) whose blocked-on task or \
5242             question no longer exists: {}",
5243            report.quarantined.len(),
5244            report.quarantined.join(", ")
5245        );
5246    }
5247    if !report.resumed.is_empty() {
5248        tracing::info!(
5249            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5250            report.resumed.len(),
5251            report.resumed.join(", ")
5252        );
5253    }
5254    if !report.asked.is_empty() {
5255        tracing::info!(
5256            "triage: asked about {} held task(s): {}",
5257            report.asked.len(),
5258            report.asked.join(", ")
5259        );
5260    }
5261    if !report.answered.is_empty() {
5262        tracing::info!(
5263            "triage: applied {} operator answer(s): {}",
5264            report.answered.len(),
5265            report.answered.join(", ")
5266        );
5267    }
5268}
5269
5270/// The free-space gate: what stands between this task and a new run, if
5271/// anything. `Some(reason)` holds the task; `None` lets it start.
5272///
5273/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5274/// the operator opted out. A measurement failure is a gate, not a pass: both
5275/// sides of "cannot tell" are served by not starting.
5276pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5277    disk_gate_with(repo, config, crate::disk::free_bytes)
5278}
5279
5280/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
5281/// test can assert the exact wiring `attempt` runs - config's threshold in,
5282/// task-holding reason out - without asking the real machine's disk anything.
5283fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5284    repo: &Path,
5285    config: &Config,
5286    free_bytes: F,
5287) -> Option<String> {
5288    let min = config.disk.min_free_bytes;
5289    if min == 0 {
5290        return None;
5291    }
5292    let mut paths = vec![repo.to_owned()];
5293    if let Some(cache) = config.cache_dir() {
5294        paths.push(cache);
5295    }
5296    if let Some(root) = &config.graph.worktree_root {
5297        paths.push(root.clone());
5298    }
5299    for path in paths {
5300        let probe = if path == repo {
5301            path.as_path()
5302        } else {
5303            path.ancestors().find(|p| p.exists()).unwrap_or(&path)
5304        };
5305        let reason = match free_bytes(probe) {
5306            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5307            Err(e) => Some(crate::disk::unmeasured_in(
5308                probe,
5309                &e,
5310                &config.graph.language,
5311            )),
5312        };
5313        if reason.is_some() {
5314            return reason;
5315        }
5316    }
5317    None
5318}
5319
5320/// How long to wait before offering another task when a run lost a seat to a
5321/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
5322/// could read, or carried nothing at all. Long enough that a quota outage
5323/// cannot burn through a whole backlog in the few seconds each doomed attempt
5324/// takes to fail; short enough that a quota which clears early is not left
5325/// idle for the fallback's sake.
5326const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5327
5328/// Longest a parsed reset hint may push the wait out to. The hint comes from
5329/// the CLI's own words, not a contract, so a parsing slip that lands a day
5330/// away must not leave the loop asleep for a day.
5331const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5332
5333/// How long [`poll`] should wait before offering the next task, after a run
5334/// lost at least one seat to a rate limit.
5335///
5336/// Pure and separate from the loop so the policy can be exercised without a
5337/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
5338/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
5339/// nothing to parse, or the parsed time has already passed; `cap` bounds how
5340/// far a parsed hint is trusted to push the wait out.
5341fn quota_wait(
5342    reset_at: Option<Timestamp>,
5343    now: Timestamp,
5344    fallback: Duration,
5345    cap: Duration,
5346) -> Duration {
5347    match reset_at {
5348        Some(at) if at > now => {
5349            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
5350            Duration::from_secs(secs).min(cap)
5351        }
5352        _ => fallback,
5353    }
5354}
5355
5356/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
5357///
5358/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
5359/// explains why parsing it exactly "would be a bug factory" — so this only
5360/// recognises the shapes actually observed in the wild, and returns `None`
5361/// for anything else rather than guess at a format nobody has seen.
5362///
5363/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
5364/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
5365/// said it, not from whenever this loop happens to read it: anchoring on `now`
5366/// would push the reset later on every read and would read an already-elapsed
5367/// reset as still in the future. (A long hint is still clamped by
5368/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
5369fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
5370    parse_reset_hint_zoned(text, now)
5371        .or_else(|| parse_reset_hint_dated(text))
5372        .or_else(|| parse_reset_hint_relative(text, recorded))
5373}
5374
5375/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
5376/// optional but at least one required, in that order. A bare number or any
5377/// unknown unit is refused.
5378fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
5379    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
5380    let mut rest = rest.trim();
5381    if rest.is_empty() {
5382        return None;
5383    }
5384    let mut total: i64 = 0;
5385    let mut matched = false;
5386    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
5387        if let Some((digits, tail)) = rest.split_once(unit)
5388            && !digits.is_empty()
5389            && digits.bytes().all(|b| b.is_ascii_digit())
5390        {
5391            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
5392            rest = tail;
5393            matched = true;
5394        }
5395    }
5396    if !rest.is_empty() || !matched {
5397        return None;
5398    }
5399    recorded
5400        .checked_add(jiff::SignedDuration::from_secs(total))
5401        .ok()
5402}
5403
5404/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
5405/// case-insensitive) into a 24-hour hour and minute. Shared by every
5406/// reset-hint shape below.
5407fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
5408    let clock = clock.trim().to_lowercase();
5409    let (digits, pm) = clock
5410        .strip_suffix("am")
5411        .map(|d| (d, false))
5412        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
5413    let (h, m) = digits.trim().split_once(':')?;
5414    let mut hour: i8 = h.trim().parse().ok()?;
5415    let minute: i8 = m.trim().parse().ok()?;
5416    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
5417        return None;
5418    }
5419    if pm && hour != 12 {
5420        hour += 12;
5421    } else if !pm && hour == 12 {
5422        hour = 0;
5423    }
5424    Some((hour, minute))
5425}
5426
5427/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
5428/// and a zone, never a date. A clock reading already past today is read as
5429/// tomorrow's: a CLI naming a same-day reset that has already gone by means
5430/// the window rolled over while nothing was watching.
5431fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
5432    let open = text.find('(')?;
5433    let close = text.rfind(')')?;
5434    if close <= open {
5435        return None;
5436    }
5437    let zone = text[open + 1..close].trim();
5438    let (hour, minute) = parse_12h_clock(&text[..open])?;
5439    let tz = jiff::tz::TimeZone::get(zone).ok()?;
5440    let candidate = now
5441        .to_zoned(tz)
5442        .with()
5443        .hour(hour)
5444        .minute(minute)
5445        .second(0)
5446        .millisecond(0)
5447        .microsecond(0)
5448        .nanosecond(0)
5449        .build()
5450        .ok()?;
5451    let mut at = candidate.timestamp();
5452    if at <= now {
5453        at += jiff::SignedDuration::from_hours(24);
5454    }
5455    Some(at)
5456}
5457
5458/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
5459/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
5460/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
5461/// "already past today" correction to make: the year already disambiguates
5462/// it. Scanned as a five-word window so it can be pulled out of the middle
5463/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
5464/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
5465/// any other timestamp with no zone attached.
5466fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
5467    let words: Vec<&str> = text.split_whitespace().collect();
5468    if words.len() < 5 {
5469        return None;
5470    }
5471    (0..=words.len() - 5)
5472        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
5473}
5474
5475/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
5476/// parenthesis right after the window is refused rather than ignored — it
5477/// reads as an explicit zone annotation on a shape that otherwise carries
5478/// none, and guessing UTC anyway would be exactly the silent misread this
5479/// module's parsing otherwise avoids.
5480fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
5481    if trailing.is_some_and(|next| next.starts_with('(')) {
5482        return None;
5483    }
5484    let month = month_number(window[0])?;
5485    let day_token = window[1].strip_suffix(',')?.to_lowercase();
5486    let day_digits = ["st", "nd", "rd", "th"]
5487        .iter()
5488        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
5489    let day: i8 = day_digits.parse().ok()?;
5490    let year_token = window[2];
5491    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
5492        return None;
5493    }
5494    let year: i16 = year_token.parse().ok()?;
5495    // The am/pm word carries the sentence's own trailing punctuation, e.g.
5496    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
5497    // reusing the same 12-hour clock reader the bracketed shape uses.
5498    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
5499    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
5500    let date = jiff::civil::Date::new(year, month, day).ok()?;
5501    let candidate = date
5502        .at(hour, minute, 0, 0)
5503        .to_zoned(jiff::tz::TimeZone::UTC)
5504        .ok()?;
5505    Some(candidate.timestamp())
5506}
5507
5508/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
5509/// case-insensitively, into a 1-based month number.
5510fn month_number(name: &str) -> Option<i8> {
5511    const NAMES: [&str; 12] = [
5512        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
5513    ];
5514    let lower = name.to_lowercase();
5515    NAMES
5516        .iter()
5517        .position(|n| *n == lower.as_str())
5518        .map(|i| i as i8 + 1)
5519}
5520
5521/// Test probe for the shared resume policy's review-budget exclusion.
5522#[cfg(test)]
5523fn exhausted_review_budget(state: &RunState) -> bool {
5524    // A run whose task-head publication failed has nothing left to review:
5525    // resuming it only retries the publication, so it is never "exhausted".
5526    !crate::handover::can_resume(state)
5527        && state.status == RunStatus::Blocked
5528        && !state.released()
5529        && state.retired_to.is_none()
5530}
5531
5532/// This task's *most recent* run, if resuming it would actually make
5533/// progress. `short` is only for the warning's own message.
5534///
5535/// Only ever `runs.last()` — never a search back through older history.
5536/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
5537/// mint, oldest first, and every entry before the last one was already
5538/// superseded at the moment it was minted: the daemon only ever starts a new
5539/// run when the previous one was not worth resuming (unresumable, exhausted,
5540/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
5541/// opens a fresh review-only run alongside an older, already-failed
5542/// competition. Searching further back would let an old run that merely
5543/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
5544/// behind, say — get resumed instead of the fresh competition
5545/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
5546/// nothing asked to revisit.
5547///
5548/// Two runs paid for the "prefer resuming over restarting" half of this
5549/// lesson, which is why this still checks `runs.last()` rather than always
5550/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
5551/// task a moment later, duplicating two and a half hours of agent work. Then
5552/// b25f stalled on a judge that timed out and one that answered with no JSON
5553/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
5554/// **one second** later, buying three fresh implementations to reach the
5555/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
5556/// the second case: a stall is terminal, and its cheap recovery re-asks only
5557/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
5558/// that is technically `resumable()` but provably cannot progress must not
5559/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
5560/// no-op instead of the fresh competition it promises.
5561///
5562/// A load failure is warned about rather than silently read as "not
5563/// resumable": the alternative is exactly what let a schema mismatch on run
5564/// `eba2` fall through to a full re-competition with nobody told why.
5565/// `crate::conduct` is what actually offers a better answer than
5566/// `Runner::start` here (see `Recovery::Review`), once this task's next
5567/// failure shows it up as `held`/`failed` with the run state unreadable.
5568fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
5569    unfinished_run_with(runs, short, RunState::load)
5570}
5571
5572/// [`unfinished_run`] with an injected state reader. Tests provide their
5573/// fixtures directly rather than touching the process-global run home.
5574pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
5575where
5576    F: FnMut(&str) -> Result<RunState>,
5577{
5578    let mut id = runs.last()?.clone();
5579    let mut visited = std::collections::BTreeSet::new();
5580    let mut repo = None;
5581    loop {
5582        if !runs.contains(&id) || !visited.insert(id.clone()) {
5583            tracing::warn!("invalid or cyclic recovery authority for task {short}");
5584            return None;
5585        }
5586        let state = match load(&id) {
5587            Ok(state) if state.id == id => state,
5588            Ok(_) => return None,
5589            Err(e) => {
5590                tracing::warn!("could not read run {id} for task {short}: {e:#}");
5591                return None;
5592            }
5593        };
5594        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
5595            return None;
5596        }
5597        repo = Some(state.repo.clone());
5598        if let Some(authority) = state.retired_to {
5599            id = authority;
5600            continue;
5601        }
5602        return (crate::handover::can_resume(&state)
5603            && state.liveness(false) != crate::run::Liveness::Live)
5604            .then_some(id);
5605    }
5606}
5607
5608/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
5609/// that [`attempt`] will resume it on its own?
5610///
5611/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
5612/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
5613/// injected reader like its sibling. An unreadable run is not awaiting
5614/// anything: it keeps going to the conductor as before.
5615fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
5616where
5617    F: FnOnce(&str) -> Result<RunState>,
5618{
5619    // `Failed` stays: a record an older build wrote for a parked run.
5620    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
5621        || task.fresh_start
5622        || task.review_branch.is_some()
5623    {
5624        return false;
5625    }
5626    let Some(id) = task.runs.last() else {
5627        return false;
5628    };
5629    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
5630}
5631
5632/// Which of the three ways [`attempt`] can mint or continue a run this task
5633/// should use.
5634#[derive(Debug, Clone, PartialEq, Eq)]
5635enum Starter {
5636    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
5637    /// and that still exists.
5638    Review(String),
5639    /// `crate::graph::Runner::resume` on an unfinished run of this task.
5640    Resume(String),
5641    /// `crate::graph::Runner::start`: a fresh competition.
5642    Start,
5643}
5644
5645/// A second bound independent of inputs and the resettable failure counter.
5646/// Count recovery records, not history entries: resuming appends the same id.
5647/// Unknown history is not evidence that a new set of worktrees is affordable.
5648fn retained_attempt_hold(
5649    task: &Task,
5650    starter: &Starter,
5651    limit: usize,
5652    mut load: impl FnMut(&str) -> Result<RunState>,
5653) -> Option<String> {
5654    if limit == 0 || matches!(starter, Starter::Resume(_)) {
5655        return None;
5656    }
5657    let mut retained = 0;
5658    for id in task.runs.iter().collect::<std::collections::BTreeSet<_>>() {
5659        let state = match load(id) {
5660            Ok(state) if state.id == *id => state,
5661            _ => {
5662                return Some(format!(
5663                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
5664                ));
5665            }
5666        };
5667        if state.retired_to.is_some() || state.released() {
5668            continue;
5669        }
5670        // Neither a completed status nor an empty candidate array proves that
5671        // all recovery sources (including unrecorded preparation) were retired.
5672        retained += 1;
5673    }
5674    (retained >= limit).then(|| format!(
5675        "[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."
5676    ))
5677}
5678
5679/// A selected public implementation overrides every historical candidate and pin.
5680fn selected_starter(
5681    selected: &crate::pr_recovery::Selection,
5682    previous: Option<&RunState>,
5683    unfinished: Option<&str>,
5684) -> Starter {
5685    if let Some(id) = unfinished
5686        && previous.is_some_and(|r| {
5687            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
5688        })
5689    {
5690        Starter::Resume(id.to_owned())
5691    } else {
5692        Starter::Review(selected.branch.clone())
5693    }
5694}
5695
5696/// The owner's answer to this branch's divergence question, consumed from the
5697/// task so a later, different divergence asks again. The runner applies it
5698/// (see `Runner::review_taking_over`), after the earlier worktree is released.
5699fn take_divergence_answer(
5700    branch: &str,
5701    remote: &str,
5702    task: &mut Task,
5703) -> Option<crate::reconcile::Choice> {
5704    let summary = crate::reconcile::summary_for(branch, remote);
5705    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
5706        (a.question == summary)
5707            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
5708            .flatten()
5709            .map(|c| (i, c))
5710    })?;
5711    task.answers.remove(idx);
5712    Some(choice)
5713}
5714
5715/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
5716/// this attempt should use. Pure, and separate from [`attempt`], so the
5717/// routing itself is assertable without spawning a real graph or a git
5718/// process: `attempt`'s own `crate::git::branch_exists` call has already
5719/// happened by the time this is called.
5720///
5721/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
5722/// whose branch is gone falls all the way through to [`Starter::Start`], not
5723/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
5724/// old (likely `Blocked`) run in the first place, and a branch that vanished
5725/// out from under that choice is not evidence resuming it would fare better.
5726fn choose_starter(
5727    review_branch: Option<&str>,
5728    branch_exists: bool,
5729    unfinished: Option<&str>,
5730) -> Starter {
5731    match review_branch {
5732        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
5733        Some(_) => Starter::Start,
5734        None => match unfinished {
5735            Some(id) => Starter::Resume(id.to_owned()),
5736            None => Starter::Start,
5737        },
5738    }
5739}
5740
5741/// Reuse a compatible latest review owner instead of taking its checked-out
5742/// branch into a new run. Different branches and changed criteria still use
5743/// the ordinary review/takeover policy.
5744fn review_retry_starter(
5745    task: &Task,
5746    previous: Option<&RunState>,
5747    branch: Option<&str>,
5748    exists: bool,
5749    unfinished: Option<&str>,
5750) -> Starter {
5751    if let Some(run) = previous
5752        && unfinished == Some(run.id.as_str())
5753        && run.reviewed_commits.is_some()
5754        && branch.is_some_and(|branch| {
5755            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
5756        })
5757        && may_resume_run(run, task)
5758    {
5759        return Starter::Resume(run.id.clone());
5760    }
5761    match (branch, unfinished, &task.review_of) {
5762        (None, None, Some(branch)) => Starter::Review(branch.clone()),
5763        _ => choose_starter(branch, exists, unfinished),
5764    }
5765}
5766
5767/// Consume a retained review only while its authored criteria still match.
5768fn take_review_branch(task: &mut Task, previous: Option<&RunState>) -> Option<String> {
5769    let branch = task.review_branch.take();
5770    let instruction = task.review_instruction.take();
5771    branch.filter(|branch| match &instruction {
5772        Some(authored) => *authored == task.instruction,
5773        // Legacy retained branches must agree with their prior run; only an
5774        // explicitly pinned review can proceed without recoverable provenance.
5775        None => previous.map_or_else(
5776            || task.review_of.as_ref() == Some(branch),
5777            |run| compatible_run_instruction(run, task),
5778        ),
5779    })
5780}
5781
5782/// A current explicit pin can select an otherwise incompatible run. Edits
5783/// and subsequent approvals invalidate pins selected for earlier criteria.
5784fn may_resume_run(run: &RunState, task: &Task) -> bool {
5785    task.resume_override
5786        .as_ref()
5787        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
5788        || compatible_run_instruction(run, task)
5789}
5790
5791/// Review scaffolding is execution context, not evidence of an operator edit.
5792pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
5793    if let Some(authored) = &run.task_instruction {
5794        return compatible_instruction(authored, task);
5795    }
5796    if compatible_instruction(&run.instruction, task) {
5797        return true;
5798    }
5799    // Recognize only the existing generated review shapes on legacy runs.
5800    // Ordinary authored text with a similar heading is left intact.
5801    if run.reviewed_commits.is_some() {
5802        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
5803            return strip_answers_block(authored, task).trim() == task.instruction.trim();
5804        }
5805        if let Some(branch) = &task.review_of {
5806            let canonical = format!(
5807                "Review the branch `{branch}` (review-only: no implementation, no judging)."
5808            );
5809            let generated = format!(
5810                "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"
5811            );
5812            return task.instruction == canonical && run.instruction.starts_with(&generated);
5813        }
5814    }
5815    false
5816}
5817
5818/// Compare authored instructions, excluding answer blocks appended by the daemon.
5819pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
5820    strip_answers_block(old, task) == task.instruction
5821}
5822
5823/// Which repository a task runs in. A task that names none — the normal case
5824/// for one filed from a phone — runs in the daemon's own default.
5825fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
5826    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
5827        return fallback.to_path_buf();
5828    }
5829    task.repo.clone()
5830}
5831
5832/// The header [`append_answers`] appends operator answers under. Shared with
5833/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
5834/// rather than grown a new block on every resume.
5835const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
5836
5837/// Render the first `count` answers in the block appended to an instruction.
5838fn answers_block(task: &Task, count: usize) -> String {
5839    let mut s = ANSWERS_HEADER.to_owned();
5840    for a in &task.answers[..count] {
5841        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
5842    }
5843    s
5844}
5845
5846/// Render the approval independently of transient task state, so historical
5847/// suffixes remain recognizable after another explicit release.
5848fn resumption_block(r: &crate::queue::Resumption) -> String {
5849    format!(
5850        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
5851         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
5852        r.generation, r.at, r.instruction, r.answers_through,
5853    )
5854}
5855
5856/// Append audit answers and the latest explicit approval to the instruction.
5857fn append_answers(base: &str, task: &Task) -> String {
5858    let mut s = base.to_owned();
5859    if !task.answers.is_empty() {
5860        s.push_str(&answers_block(task, task.answers.len()));
5861    }
5862    if let Some(r) = &task.resumption {
5863        s.push_str(&resumption_block(r));
5864    }
5865    s
5866}
5867
5868/// Drop the prior answer block only when it is exactly the suffix this task
5869/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
5870/// the task author is ordinary instruction text, not a block to remove.
5871fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
5872    let mut instruction = instruction;
5873    for approval in task
5874        .resumption
5875        .iter()
5876        .chain(task.resumption_history.iter().rev())
5877    {
5878        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
5879            instruction = base;
5880            break;
5881        }
5882    }
5883    for count in (1..=task.answers.len()).rev() {
5884        let block = answers_block(task, count);
5885        if let Some(base) = instruction.strip_suffix(&block) {
5886            return base;
5887        }
5888    }
5889    instruction
5890}
5891
5892/// The instruction handed to `Runner::start`: the task's own text, plus any
5893/// operator answers `crate::conduct` collected for it (see
5894/// [`Task::answers`]), so a decision the operator actually made reaches the
5895/// implementers rather than only clearing the block that was waiting on it.
5896///
5897/// Appended rather than merged into [`Task::instruction`] itself, so the
5898/// task's own record stays exactly what its author wrote.
5899fn instruction_for(task: &Task) -> String {
5900    append_answers(&task.instruction, task)
5901}
5902
5903/// The instruction a resumed run should carry on with: whatever it already
5904/// had, refreshed with the task's *current* operator answers.
5905///
5906/// A resumable run's own `RunState::instruction` predates any answer
5907/// `crate::conduct` collects after the run parks, so resuming it unchanged —
5908/// the behaviour before this function existed — silently drops the very
5909/// decision the operator made to unblock it. Re-stripping any block this
5910/// function appended on an earlier resume before re-appending the current
5911/// list (rather than blindly appending again) is what keeps a task resumed
5912/// three times over three answered questions from carrying the same answer
5913/// three times.
5914fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
5915    append_answers(strip_answers_block(old_instruction, task), task)
5916}
5917
5918/// Preserve the producer's verified boundary and target, independent of prose.
5919fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
5920    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
5921    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
5922    if let Some(cause) = task.hold_notice_cause.as_mut() {
5923        cause.target = failure.map(|f| f.target.clone());
5924    }
5925}
5926
5927#[derive(Debug, thiserror::Error)]
5928#[error("attachment `{name}` is recorded on the task but {path} is missing")]
5929struct MissingAttachment {
5930    name: String,
5931    path: PathBuf,
5932}
5933
5934/// The task's attachments as absolute paths, each checked to still exist.
5935fn task_attachments(
5936    queue: &Queue,
5937    task: &Task,
5938) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
5939    let paths = queue.attachment_paths(task);
5940    for (name, path) in task.attachments.iter().zip(&paths) {
5941        if !path.is_file() {
5942            return Err(MissingAttachment {
5943                name: name.clone(),
5944                path: path.clone(),
5945            });
5946        }
5947    }
5948    Ok(paths)
5949}
5950
5951/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
5952/// answers before handing it to `Runner` — the actual boundary between
5953/// [`choose_starter`]'s routing and the graph, factored out so it is
5954/// assertable without a real repository, git branch, or agent CLI.
5955///
5956/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
5957/// instruction from the reviewed branch's own commit log because there is no
5958/// task statement to speak of for hand-written work, and splicing operator
5959/// answers into that text would contradict the very message it sends
5960/// reviewers ("there is no task statement").
5961fn prepare_instruction(
5962    starter: &Starter,
5963    old_instruction: Option<&str>,
5964    task: &Task,
5965) -> Option<String> {
5966    match starter {
5967        Starter::Start => Some(instruction_for(task)),
5968        Starter::Resume(_) => Some(resumed_instruction(
5969            old_instruction.expect("a resumed run always has a prior instruction"),
5970            task,
5971        )),
5972        Starter::Review(_) => None,
5973    }
5974}
5975
5976/// Persist a transition. A queue write failure is logged rather than fatal: the
5977/// run already happened, and taking the daemon down would only add a lost
5978/// backlog to a full disk.
5979fn record(queue: &Queue, task: &mut Task) {
5980    if let Err(e) = queue.put(task) {
5981        tracing::error!("could not record task {}: {e:#}", task.short());
5982        let notice = Notice::error(
5983            "loop:record",
5984            format!(
5985                "Task {} state could not be saved: {}. Check the disk.",
5986                task.id,
5987                e.to_string().lines().next().unwrap_or("unknown save error")
5988            ),
5989        )
5990        .link(Link::Task {
5991            id: task.id.clone(),
5992        });
5993        // The queue lives at `<home>/queue`, so its parent is the home.
5994        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
5995            Some(home) => notices::raise_in(home, notice),
5996            None => notices::raise(notice),
5997        }
5998    }
5999}
6000
6001/// Every runnable task, in the order the loop should try them.
6002///
6003/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6004/// tail exists so that a claim somebody else holds costs the loop the next
6005/// candidate rather than a whole poll interval of idleness.
6006fn runnable(queue: &Queue) -> Vec<Task> {
6007    let mut tasks: Vec<Task> = queue
6008        .list()
6009        .into_iter()
6010        .filter(|t| t.status.runnable())
6011        .collect();
6012    tasks.sort_unstable_by(crate::queue::dispatch_order);
6013    tasks
6014}
6015
6016/// Why a run ended where it did, in one line, for [`Task::last_error`].
6017///
6018/// A stalled run names the seats the quota took out: "out of quota" is not
6019/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6020/// agent to replace or which plan to top up.
6021///
6022/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6023/// purpose: unlike `label`'s other callers (an internal log line, an
6024/// already-a-bug fallback message), this string becomes `Task::last_error`
6025/// verbatim, which the phone renders in the same alarm-styled box an
6026/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6027/// `.err` styling. A bare `verified_noop` there would read exactly like the
6028/// failure this whole feature exists to tell apart from one.
6029fn describe(state: &RunState) -> String {
6030    let p = phrases(&state.config.graph.language);
6031    let mut detail = if state.status == RunStatus::Stalled {
6032        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6033        seats.sort_unstable();
6034        seats.dedup();
6035        if seats.is_empty() {
6036            p.quorum_lost.to_owned()
6037        } else {
6038            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6039        }
6040    } else {
6041        format!("{}{}", p.run_ended, state.status.display_label())
6042    };
6043    if let Some(last) = state.events.last() {
6044        // The review loop's "never answered" stop is the one event worth
6045        // translating; it is recognised from structured state, not by
6046        // matching the English event text (which stays as recorded).
6047        let unanswered = state
6048            .reviews
6049            .last()
6050            .filter(|r| {
6051                state.status == RunStatus::Blocked
6052                    && last.node == "review"
6053                    && r.incomplete()
6054                    && r.blocking == 0
6055                    && r.round == state.config.graph.review_rounds
6056                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6057            })
6058            .map(|r| (r.expected - r.answered, r.round));
6059        match unanswered {
6060            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6061                detail.push_str(&format!(
6062                    " ({}: {})",
6063                    last.node,
6064                    (p.reviewers_never_answered)(missing, rounds)
6065                ));
6066            }
6067            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6068        }
6069    }
6070    detail.push_str(&format!(" [run {}]", state.id));
6071    detail
6072}
6073
6074/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6075///
6076/// The task file lives in the backlog indefinitely; a diagnostic is an
6077/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6078/// stay small regardless of how much a gate command or a candidate printed.
6079const DIAGNOSTIC_MAX: usize = 4_000;
6080
6081/// Tail kept from a single failing command's output inside a diagnostic.
6082/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6083/// pointer for a human deciding whether to go read the full artifact by hand,
6084/// not a replacement for reading it.
6085const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6086
6087/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6088/// `magi task show` says more than the one-line reason in [`describe`].
6089///
6090/// The one-liner answers "where did the run stop"; this answers "what would a
6091/// human have found opening `artifacts/` by hand" — the point of the whole
6092/// feature is the case that one-liner actively misleads on: a run held as "no
6093/// candidate produced a change" can mean the implementer actually finished
6094/// the task (opened a PR, merged it, tagged a release) and only left a clean
6095/// local worktree behind, which reads as "nothing happened" unless someone
6096/// goes and reads what the agent actually said. `None` when the run carries
6097/// none of the three shapes this recognises — an ordinary run held for
6098/// something not diagnosable from `RunState` alone still explains itself
6099/// through `Task::last_error`.
6100fn diagnostic(state: &RunState) -> Option<String> {
6101    let mut parts: Vec<String> = Vec::new();
6102
6103    // Gate failure: which check(s), and the tail of what each printed.
6104    for o in state.gate.iter().filter(|o| !o.ok()) {
6105        parts.push(format!(
6106            "gate `{}` failed ({}):\n{}",
6107            o.command,
6108            notices::exit_status(o.code),
6109            crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6110        ));
6111    }
6112
6113    // The land loop gave up because the fixer declined while checks were
6114    // still red: the message already names them (see `land::run`).
6115    if let Some(last) = state
6116        .events
6117        .iter()
6118        .rev()
6119        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6120    {
6121        parts.push(last.message.clone());
6122    }
6123
6124    // No viable candidate: every implementer's own final word, sanitized the
6125    // same way a judge would have read it, so a run that actually finished
6126    // the job does not read as an unexplained failure. A verified no-op is
6127    // called out ahead of its own summary and apart from an ordinary
6128    // failure's `why` — this is the one candidate shape whose diagnostic a
6129    // human is expected to actually judge, not just skim.
6130    if state.viable().is_empty() {
6131        for c in &state.candidates {
6132            if let Some(evidence) = &c.verified_noop {
6133                parts.push(format!(
6134                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6135                    c.label
6136                ));
6137            } else if !c.summary.trim().is_empty() {
6138                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6139            } else if let Some(why) = &c.failed {
6140                parts.push(format!("candidate {}: {why}", c.label));
6141            }
6142        }
6143    }
6144
6145    if parts.is_empty() {
6146        return None;
6147    }
6148    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6149    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6150    // back slightly over. Leave it enough room to always land under the
6151    // limit.
6152    Some(crate::run::tail(
6153        &parts.join("\n\n"),
6154        DIAGNOSTIC_MAX.saturating_sub(100),
6155    ))
6156}
6157
6158/// Stable lower-case name for a run status, for an internal log line and the
6159/// "graph stopped without reaching a terminal status" bug message in
6160/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6161/// doc for why that one reads [`RunStatus::display_label`] instead. One
6162/// definition of a status's name, on the type that owns it: this table used
6163/// to live here as a second copy, and a status renamed in one place would
6164/// have gone on reading correctly in the other.
6165fn label(status: RunStatus) -> &'static str {
6166    status.as_str()
6167}
6168
6169/// Parse a merge mode override.
6170pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6171    match mode {
6172        "none" => Ok(MergeMode::None),
6173        "local" => Ok(MergeMode::Local),
6174        "pr" => Ok(MergeMode::Pr),
6175        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6176    }
6177}
6178
6179/// Take the status lock, recovering from a poisoned one.
6180///
6181/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6182/// data, and the worst a poisoned lock can hold is a stale timestamp.
6183fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6184    mutex
6185        .lock()
6186        .unwrap_or_else(std::sync::PoisonError::into_inner)
6187}
6188
6189#[cfg(test)]
6190mod tests {
6191    use super::*;
6192    use crate::queue::{Source, TaskStatus};
6193    use crate::run::{Candidate, CommandOutcome};
6194    use pretty_assertions::assert_eq;
6195
6196    fn task() -> Task {
6197        Task::new(
6198            "add retries".to_owned(),
6199            "add retries".to_owned(),
6200            PathBuf::from("/repo"),
6201            Source::Human,
6202        )
6203    }
6204
6205    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6206        let job = crate::worker::Job {
6207            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6208            sequence: 1,
6209            kind: "task".into(),
6210            key: format!("task:{}", request.task),
6211            payload: serde_json::to_value(request).unwrap(),
6212            generation: "a".repeat(64),
6213            version: None,
6214            status: crate::worker::Status::Starting,
6215            result: None,
6216            pid: None,
6217            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6218            finished_at: None,
6219        };
6220        let dir = home.join("workers/jobs").join(&job.id);
6221        std::fs::create_dir_all(&dir).unwrap();
6222        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6223        job
6224    }
6225
6226    #[test]
6227    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6228        let home = tempfile::tempdir().unwrap();
6229        let request = TaskWorker {
6230            opts: Opts::default(),
6231            queue: home.path().join("queue"),
6232            task: "startup".into(),
6233            lane: PermitKind::Ordinary,
6234            standalone: false,
6235        };
6236        let job = starting_task_reservation(home.path(), &request);
6237        let error = task_worker_spawn_error(
6238            home.path(),
6239            &request,
6240            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6241        )
6242        .expect_err("our own reservation must not turn a failed spawn into a resync");
6243        let active = crate::worker::active(home.path()).unwrap();
6244        assert_eq!(active.len(), 1);
6245        assert_eq!(active[0].id, job.id);
6246        assert_eq!(active[0].status, crate::worker::Status::Starting);
6247        assert!(
6248            crate::worker::control(home.path(), &job.key)
6249                .unwrap()
6250                .is_none()
6251        );
6252        let notices = notices::Notices::at(home.path().join("notifications")).list();
6253        assert_eq!(notices.len(), 1);
6254        assert_eq!(notices[0].key, "loop:worker-startup");
6255        assert!(!notices[0].message.contains("private-error-detail"));
6256        assert!(notices[0].message.contains(&request.task));
6257        assert!(
6258            notices[0]
6259                .message
6260                .contains("could not be started or acknowledged")
6261        );
6262        assert!(notices[0].message.contains("worker.log"));
6263        assert_eq!(
6264            notices[0].link,
6265            Some(Link::Task {
6266                id: request.task.clone()
6267            })
6268        );
6269        assert!(format!("{error:#}").contains("private-error-detail"));
6270    }
6271
6272    #[test]
6273    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
6274        let home = tempfile::tempdir().unwrap();
6275        let mut request = TaskWorker {
6276            opts: Opts::default(),
6277            queue: home.path().join("queue"),
6278            task: "handoff".into(),
6279            lane: PermitKind::Ordinary,
6280            standalone: true,
6281        };
6282        let job = starting_task_reservation(home.path(), &request);
6283        request.standalone = false;
6284        task_worker_spawn_error(
6285            home.path(),
6286            &request,
6287            anyhow::anyhow!("operation key is already reserved for a different request"),
6288        )
6289        .expect("a different standalone request is the handoff race, not our startup failure");
6290        let active = crate::worker::active(home.path()).unwrap();
6291        assert_eq!(active.len(), 1);
6292        assert_eq!(active[0].id, job.id);
6293        assert_eq!(active[0].payload, job.payload);
6294        assert!(
6295            notices::Notices::at(home.path().join("notifications"))
6296                .list()
6297                .is_empty()
6298        );
6299    }
6300
6301    #[test]
6302    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
6303        let home = tempfile::tempdir().unwrap();
6304        let queue = Queue::at(home.path().join("queue"));
6305        let mut task = task();
6306        task.runs = vec!["previous".into()];
6307        queue.put(&mut task).unwrap();
6308        let request = TaskWorker {
6309            opts: Opts::default(),
6310            queue: home.path().join("queue"),
6311            task: task.id.clone(),
6312            lane: PermitKind::Ordinary,
6313            standalone: false,
6314        };
6315        let job = starting_task_reservation(home.path(), &request);
6316        let claims = current_work(home.path(), Timestamp::now());
6317        assert_eq!(claims.len(), 1);
6318        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
6319        assert_eq!(claims[0].run, "previous");
6320        assert!(other_claims_run(&claims, "previous", None));
6321        // Only after confirming the executing caller may admission ignore
6322        // this exact projection. Cleanup continues to observe it as live.
6323        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
6324        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
6325    }
6326
6327    #[test]
6328    fn admission_excludes_only_the_callers_exact_reservation() {
6329        let own = Current {
6330            worker: Some("own".into()),
6331            task: "same-task".into(),
6332            run: "previous".into(),
6333        };
6334        assert!(!other_claims_run(
6335            std::slice::from_ref(&own),
6336            "previous",
6337            Some("own")
6338        ));
6339        assert!(other_claims_run(
6340            std::slice::from_ref(&own),
6341            "previous",
6342            None
6343        ));
6344        for worker in [None, Some("other".into())] {
6345            let other = Current {
6346                worker,
6347                ..own.clone()
6348            };
6349            assert!(other_claims_run(
6350                &[own.clone(), other],
6351                "previous",
6352                Some("own")
6353            ));
6354        }
6355        let legacy: Current =
6356            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
6357        assert!(other_claims_run(&[legacy], "previous", Some("own")));
6358    }
6359
6360    #[test]
6361    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
6362        let mut task = task();
6363        let mut run = run_state(RunStatus::Reviewing);
6364        run.task_instruction = Some(task.instruction.clone());
6365        run.reviewed_commits = Some(vec!["committed-fix".into()]);
6366        let branch = "magi/test/B";
6367        run.candidates.push(crate::run::Candidate {
6368            branch: branch.into(),
6369            ..candidate('B', "preserved work", false, None)
6370        });
6371        task.runs = vec![run.id.clone()];
6372        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
6373        assert_eq!(
6374            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6375            Starter::Resume(run.id.clone())
6376        );
6377        assert!(matches!(
6378            review_retry_starter(
6379                &task,
6380                Some(&run),
6381                Some("different"),
6382                true,
6383                unfinished.as_deref()
6384            ),
6385            Starter::Review(_)
6386        ));
6387        assert_eq!(
6388            review_retry_starter(
6389                &task,
6390                Some(&run),
6391                Some(branch),
6392                false,
6393                unfinished.as_deref()
6394            ),
6395            Starter::Start
6396        );
6397        task.instruction.push_str(" changed criteria");
6398        assert!(matches!(
6399            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
6400            Starter::Review(_)
6401        ));
6402        assert!(matches!(
6403            review_retry_starter(&task, Some(&run), Some(branch), true, None),
6404            Starter::Review(_)
6405        ));
6406    }
6407
6408    #[test]
6409    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
6410        let dir = tempfile::tempdir().unwrap();
6411        let queue = Queue::at(dir.path().join("queue"));
6412        let mut task = task();
6413        task.status = TaskStatus::Running;
6414        task.attempts = 1;
6415        queue.put(&mut task).unwrap();
6416        let live = std::collections::BTreeSet::from([task.id.clone()]);
6417        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
6418        drop(queue.claim(&task.id).unwrap());
6419        let saved = queue.get(&task.id).unwrap();
6420        assert_eq!(saved.status, TaskStatus::Running);
6421        assert_eq!(saved.attempts, 1);
6422        assert!(saved.last_error.is_none());
6423    }
6424
6425    #[test]
6426    fn standalone_workers_do_not_consume_scheduler_lanes() {
6427        let request = |task: &str, lane, standalone| TaskWorker {
6428            opts: Opts::default(),
6429            queue: PathBuf::from("/queue"),
6430            task: task.to_owned(),
6431            lane,
6432            standalone,
6433        };
6434        let mut jobs = vec![
6435            request("ordinary", PermitKind::Ordinary, false),
6436            request("standalone-urgent", PermitKind::Urgent, true),
6437            request("standalone-ordinary", PermitKind::Ordinary, true),
6438            request("decision", PermitKind::None, false),
6439        ];
6440        assert_eq!(available_slots(&jobs, 2), (1, 1));
6441        jobs.push(request("urgent", PermitKind::Urgent, false));
6442        assert_eq!(available_slots(&jobs, 2), (1, 0));
6443        assert_eq!(available_slots(&jobs, 0), (0, 0));
6444    }
6445
6446    #[test]
6447    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
6448        let now = Timestamp::now();
6449        let mut reading = Reading {
6450            pid: Some(std::process::id()),
6451            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
6452            ..Reading::default()
6453        };
6454        assert!(!reading.running(now));
6455        assert!(legacy_scheduler_running(&reading, now, 0));
6456        reading.worker_protocol = Some(1);
6457        assert!(!legacy_scheduler_running(&reading, now, 0));
6458    }
6459
6460    #[test]
6461    fn selected_public_head_overrides_historical_resume_and_pin() {
6462        let mut t = task();
6463        let mut old = run_state(RunStatus::Blocked);
6464        let selection = crate::pr_recovery::Selection {
6465            url: "url".into(),
6466            branch: format!("magi/task-{}", t.id),
6467            head: "a".repeat(40),
6468            source_head: None,
6469            source_run: None,
6470            source_proof: None,
6471            disposition: Some(crate::pr_recovery::Disposition::Review),
6472            instruction: t.instruction.clone(),
6473            approved_at: Timestamp::now(),
6474        };
6475        t.resume_override = Some(crate::queue::OperatorResume {
6476            pinned_run: Some(old.id.clone()),
6477            question_id: "choice".into(),
6478            at: Timestamp::now(),
6479            conductor_rehold: None,
6480            forced: false,
6481        });
6482        assert_eq!(
6483            selected_starter(&selection, Some(&old), Some(&old.id)),
6484            Starter::Review(selection.branch.clone())
6485        );
6486        old.pr_recovery = Some(selection.clone());
6487        assert_eq!(
6488            selected_starter(&selection, Some(&old), Some(&old.id)),
6489            Starter::Review(selection.branch.clone())
6490        );
6491        old.reviewed_commits = Some(vec!["implementation".into()]);
6492        assert_eq!(
6493            selected_starter(&selection, Some(&old), Some(&old.id)),
6494            Starter::Resume(old.id.clone())
6495        );
6496        let mut changed = selection.clone();
6497        changed.head = "b".repeat(40);
6498        assert_eq!(
6499            selected_starter(&changed, Some(&old), Some(&old.id)),
6500            Starter::Review(changed.branch)
6501        );
6502    }
6503
6504    #[test]
6505    fn candidate_transplant_failure_is_one_actionable_hold() {
6506        let dir = tempfile::tempdir().unwrap();
6507        let q = Queue::at(dir.path().join("queue"));
6508        let mut t = task();
6509        let mut state = run_state(RunStatus::Blocked);
6510        state.event("prep", "cannot apply referenced commit: conflict");
6511        state.prep_failure = Some("conflict".into());
6512        t.start(state.id.clone());
6513        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
6514        assert_eq!(t.attempts, 1);
6515        assert_eq!(t.status, TaskStatus::Held);
6516        assert!(t.operator_held());
6517        assert!(!t.status.runnable());
6518        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
6519        let first = t.chat_notice_key().unwrap();
6520        t.chat_notices.push(first.clone());
6521        t.release_operator("test", None);
6522        state.id = "another-unprepared-run".into();
6523        t.start(state.id.clone());
6524        finish_attempt(
6525            3,
6526            &q,
6527            &mut t,
6528            &state,
6529            &[],
6530            Err(anyhow::anyhow!("still conflicts")),
6531        );
6532        assert_eq!(
6533            t.chat_notice_key().as_ref(),
6534            Some(&first),
6535            "no work happened"
6536        );
6537        t.release_operator("test", None);
6538        state.prep_failure = None;
6539        state.status = RunStatus::Failed;
6540        state.begin_pass();
6541        t.start(state.id.clone());
6542        finish_attempt(
6543            1,
6544            &q,
6545            &mut t,
6546            &state,
6547            &[],
6548            Err(anyhow::anyhow!("new gate failure")),
6549        );
6550        let failure = t.chat_notice_key().unwrap();
6551        assert_ne!(failure, first, "approved recovery reached a real failure");
6552        t.release_operator("test", None);
6553        state.begin_pass();
6554        t.start(state.id.clone());
6555        finish_attempt(
6556            1,
6557            &q,
6558            &mut t,
6559            &state,
6560            &[],
6561            Err(anyhow::anyhow!("new failure on resume")),
6562        );
6563        assert_ne!(
6564            t.chat_notice_key().as_ref(),
6565            Some(&failure),
6566            "a new settled pass"
6567        );
6568    }
6569
6570    #[test]
6571    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
6572        for source in ["cli", "web"] {
6573            let mut t = task();
6574            let mut run = run_state(RunStatus::Blocked);
6575            run.instruction = "Run A original criteria".into();
6576            run.task_instruction = Some(run.instruction.clone());
6577            t.start(run.id.clone());
6578            t.release_operator("choice", Some("resume-question"));
6579            t.resume_override = Some(crate::queue::OperatorResume {
6580                question_id: "resume-question".into(),
6581                at: Timestamp::now(),
6582                conductor_rehold: None,
6583                forced: true,
6584                pinned_run: Some(run.id.clone()),
6585            });
6586            t.hold_machine(Some("not enough free space to start a run".into()));
6587            let mut unchanged = t.clone();
6588            unchanged
6589                .edit("title changed".into(), unchanged.instruction.clone())
6590                .unwrap();
6591            unchanged.release_operator(source, None);
6592            assert_eq!(
6593                unchanged
6594                    .resume_override
6595                    .as_ref()
6596                    .unwrap()
6597                    .pinned_run
6598                    .as_deref(),
6599                Some(run.id.as_str())
6600            );
6601            assert!(!compatible_run_instruction(&run, &unchanged));
6602            assert!(may_resume_run(&run, &unchanged));
6603
6604            t.edit(
6605                "approved recovery".into(),
6606                "Reuse measured PR head B; fix Clippy; review".into(),
6607            )
6608            .unwrap();
6609            assert!(t.resume_override.is_none());
6610            t.release_operator(source, None);
6611            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
6612            assert!(reloaded.resume_override.is_none());
6613            assert!(!may_resume_run(&run, &reloaded));
6614            let unfinished =
6615                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
6616                    .filter(|_| may_resume_run(&run, &reloaded));
6617            assert_eq!(
6618                choose_starter(None, false, unfinished.as_deref()),
6619                Starter::Start
6620            );
6621            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
6622            assert_eq!(
6623                reloaded.resumption_history[0].question_id.as_deref(),
6624                Some("resume-question")
6625            );
6626
6627            // A revision already persisted with the old approval/pin is also
6628            // invalidated when the new operator release is recorded.
6629            unchanged.instruction = "Reuse measured PR head B".into();
6630            unchanged.hold_machine(Some("disk hold".into()));
6631            unchanged.release_operator(source, None);
6632            assert!(unchanged.resume_override.is_none());
6633            assert!(!may_resume_run(&run, &unchanged));
6634        }
6635    }
6636
6637    #[test]
6638    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
6639        let mut t = task();
6640        let mut run = run_state(RunStatus::Blocked);
6641        t.review_of = Some("approved-head".into());
6642        t.instruction =
6643            "Review the branch `approved-head` (review-only: no implementation, no judging)."
6644                .into();
6645        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();
6646        run.reviewed_commits = Some(vec!["Commit log".into()]);
6647        t.start(run.id.clone());
6648        t.hold_machine(Some("interrupted review".into()));
6649        t.release_operator("cli", None);
6650        assert!(
6651            compatible_run_instruction(&run, &t),
6652            "legacy explicit review remains resumable"
6653        );
6654        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
6655            .filter(|_| compatible_run_instruction(&run, &t));
6656        assert_eq!(
6657            choose_starter(None, false, unfinished.as_deref()),
6658            Starter::Resume(run.id.clone())
6659        );
6660        run.task_instruction = Some(t.instruction.clone());
6661        assert!(compatible_run_instruction(&run, &t));
6662        let reloaded: RunState =
6663            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
6664        assert!(compatible_run_instruction(&reloaded, &t));
6665        t.edit(
6666            "new approved head".into(),
6667            "Reuse measured PR head B".into(),
6668        )
6669        .unwrap();
6670        assert!(!compatible_run_instruction(&run, &t));
6671
6672        // Legacy recovery reviews retain the task criteria ahead of the log.
6673        t.review_of = None;
6674        t.instruction = "Fix Clippy on approved head".into();
6675        run.task_instruction = None;
6676        run.instruction = format!(
6677            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
6678            t.instruction
6679        );
6680        assert!(compatible_run_instruction(&run, &t));
6681        t.instruction.push('\n');
6682        assert!(
6683            compatible_run_instruction(&run, &t),
6684            "legacy generated review trimmed the original criteria"
6685        );
6686        t.hold_for_handover(Some("approved-head".into()), "refused".into());
6687        let mut unchanged = t.clone();
6688        assert_eq!(
6689            take_review_branch(&mut unchanged, Some(&run)).as_deref(),
6690            Some("approved-head")
6691        );
6692        t.edit("new plan".into(), "Reuse measured PR head B".into())
6693            .unwrap();
6694        assert!(take_review_branch(&mut t, Some(&run)).is_none());
6695        assert!(!compatible_run_instruction(&run, &t));
6696        t.review_branch = Some("approved-head".into());
6697        t.review_instruction = None;
6698        assert!(
6699            take_review_branch(&mut t, Some(&run)).is_none(),
6700            "legacy retained candidate cannot replace a revised approved head"
6701        );
6702    }
6703
6704    #[test]
6705    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
6706        crate::run::pin_test_home();
6707        let dir = tempfile::tempdir().unwrap();
6708        let queue = Queue::at(dir.path().join("queue"));
6709        for resume in [true, false] {
6710            let state = run_state(RunStatus::Blocked);
6711            let mut t = task();
6712            t.start(state.id.clone());
6713            let action = if resume {
6714                ask::ChoiceAction::Resume {
6715                    run: state.id.clone(),
6716                }
6717            } else {
6718                ask::ChoiceAction::Requeue
6719            };
6720            let mut q = action_question(&state.id, action);
6721            q.status = ask::QuestionStatus::Open;
6722            q.answer = None;
6723            q.answered_at = None;
6724            t.fail("run stopped with a question", 3);
6725            hold_if_runnable(&queue, &mut t);
6726            assert!(t.operator_decided_at.is_none());
6727            assert!(t.operator_held());
6728            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
6729            let expected = if resume {
6730                ActionDecision::Resume(state.id.clone())
6731            } else {
6732                ActionDecision::Requeue
6733            };
6734            assert_eq!(
6735                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6736                expected
6737            );
6738            t.hold_manual(Some("later explicit hold".into()));
6739            assert_eq!(
6740                decide_action(&t, &q, phrases("en"), |_| Ok(state.clone())),
6741                ActionDecision::Stale
6742            );
6743        }
6744    }
6745
6746    #[test]
6747    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
6748        let mut t = task();
6749        t.answers.push(crate::queue::AnsweredQuestion {
6750            question: "Inspect the remote?".into(),
6751            answer: "Inspect then wait".into(),
6752        });
6753        let old = instruction_for(&t);
6754        assert!(compatible_instruction(&old, &t));
6755        t.instruction = "Reuse approved PR head and review".into();
6756        t.release_operator("cli", None);
6757        assert!(!compatible_instruction(&old, &t));
6758        let approved = instruction_for(&t);
6759        assert!(approved.contains("waiting premises are superseded"));
6760        assert!(compatible_instruction(&approved, &t));
6761        assert_eq!(resumed_instruction(&approved, &t), approved);
6762        t.release_operator("web", None);
6763        assert!(compatible_instruction(&approved, &t));
6764        assert_eq!(t.resumption_history.len(), 1);
6765        t.start("run".into());
6766        assert!(instruction_for(&t).contains("Explicit operator resumption"));
6767    }
6768
6769    /// A run that stopped on an infrastructure wait asked no agent anything:
6770    /// the task is held by the machine under a `[resource]` reason (resumable,
6771    /// re-checked by triage), and the attempt it started is given back.
6772    #[test]
6773    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
6774        let mut state = RunState::new(
6775            PathBuf::from("/repo"),
6776            "main".into(),
6777            "base".into(),
6778            "task".into(),
6779            Config::default(),
6780        );
6781        state.status = RunStatus::Landing;
6782        state.parked = true;
6783        state.pr_pushed_head = Some("head".into());
6784        state.land_unrelated = Some(
6785            serde_json::from_value(serde_json::json!({
6786                "head": "head", "question": "ci-question",
6787                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
6788            }))
6789            .unwrap(),
6790        );
6791        let mut t = task();
6792        t.start(state.id.clone());
6793        let verdict = Verdict {
6794            status: RunStatus::Landing,
6795            left_pr: true,
6796            quota_hit: false,
6797            parked: true,
6798            no_viable_candidates: false,
6799        };
6800        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6801        assert_eq!(t.attempts, 0);
6802        assert_eq!(t.status, TaskStatus::Held);
6803        assert!(!t.operator_held());
6804        assert!(
6805            t.hold_reason
6806                .as_deref()
6807                .unwrap()
6808                .starts_with("[ci-unrelated]")
6809        );
6810        // A second settlement must not refund an earlier task attempt.
6811        t.attempts = 1;
6812        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
6813        assert_eq!(t.attempts, 1);
6814        assert_eq!(t.passes.len(), 1);
6815        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
6816        state.pr_pushed_head = Some("new-head".into());
6817        state.parked = false;
6818        state.status = RunStatus::Blocked;
6819        let stale = Verdict {
6820            status: RunStatus::Blocked,
6821            parked: false,
6822            ..verdict
6823        };
6824        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
6825        assert_eq!(t.attempts, 1);
6826        // A new execution pass can refund its own newly charged attempt.
6827        state.begin_pass();
6828        state.begin_pass();
6829        state.status = RunStatus::Landing;
6830        state.parked = true;
6831        state.pr_pushed_head = Some("head".into());
6832        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
6833        assert_eq!(t.attempts, 0);
6834        assert_eq!(t.passes.len(), 2);
6835    }
6836
6837    #[test]
6838    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
6839        let mut state = RunState::new(
6840            PathBuf::from("/repo"),
6841            "main".to_owned(),
6842            "abc1234".to_owned(),
6843            "task".to_owned(),
6844            Config::default(),
6845        );
6846        state.status = RunStatus::Blocked;
6847        state.resource_block = Some(crate::run::ResourceBlock {
6848            cause: crate::run::ResourceBlockCause::Other,
6849            node: "graft".to_owned(),
6850            kind: "shared build cache".to_owned(),
6851            detail: "timed out".to_owned(),
6852            at: jiff::Timestamp::now(),
6853        });
6854        let mut t = task();
6855        t.start("20260902-000000-aaaa".to_owned());
6856        assert_eq!(t.attempts, 1);
6857        let verdict = Verdict {
6858            status: RunStatus::Blocked,
6859            left_pr: false,
6860            quota_hit: false,
6861            parked: false,
6862            no_viable_candidates: false,
6863        };
6864        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
6865        assert_eq!(t.status, TaskStatus::Held);
6866        assert_eq!(t.attempts, 0, "the attempt is refunded");
6867        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
6868        assert!(
6869            !t.operator_held(),
6870            "a machine hold, released without a human"
6871        );
6872
6873        let mut selected = task();
6874        selected.start("20260902-000000-cccc".into());
6875        selected.replacement = Some(crate::merge_decision::Replacement {
6876            question: "fixture".into(),
6877            run: "earlier".into(),
6878            pr: "https://example.invalid/pr/1".into(),
6879            agent: "selected".into(),
6880            context: "fixture".into(),
6881        });
6882        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
6883        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
6884        assert_eq!(selected.attempts, 0);
6885        assert!(
6886            !selected.operator_held(),
6887            "a selected agent also retains a machine resource hold"
6888        );
6889        assert!(
6890            selected
6891                .hold_reason
6892                .as_deref()
6893                .unwrap()
6894                .starts_with("[resource] ")
6895        );
6896
6897        // A park request outranks it: still the operator's doing.
6898        let mut p = task();
6899        p.start("20260902-000000-bbbb".to_owned());
6900        settle_and_diagnose(
6901            &mut p,
6902            Verdict {
6903                parked: true,
6904                ..verdict
6905            },
6906            "parked",
6907            2,
6908            &state,
6909        );
6910        assert_eq!(p.status, TaskStatus::Parked);
6911        assert_eq!(
6912            p.attempts, 0,
6913            "parking refunds once rather than also settling the resource hold"
6914        );
6915    }
6916
6917    #[test]
6918    fn record_failure_notice_links_the_task() {
6919        let dir = tempfile::tempdir().unwrap();
6920        // A regular file where the queue directory should be makes every
6921        // `put` fail, on every platform and whoever runs the test.
6922        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
6923        let queue = Queue::at(dir.path().join("queue"));
6924        let mut t = interrupt_task("rec-fail-1");
6925        record(&queue, &mut t);
6926
6927        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
6928        assert_eq!(found.len(), 1);
6929        assert_eq!(found[0].key, "loop:record");
6930        assert_eq!(
6931            found[0].link,
6932            Some(Link::Task {
6933                id: "rec-fail-1".to_owned()
6934            })
6935        );
6936    }
6937
6938    /// A runnable task marked to interrupt, with an id fixed for assertions
6939    /// rather than the random one [`Task::new`] mints.
6940    fn interrupt_task(id: &str) -> Task {
6941        let mut t = task();
6942        t.id = id.to_owned();
6943        t.interrupt = true;
6944        t
6945    }
6946
6947    /// An ordinary runnable task with an id fixed for assertions.
6948    fn task_with_id(id: &str) -> Task {
6949        let mut t = task();
6950        t.id = id.to_owned();
6951        t
6952    }
6953
6954    /// A runnable task marked `--urgent`, with an id fixed for assertions.
6955    fn urgent_task(id: &str) -> Task {
6956        let mut t = task();
6957        t.id = id.to_owned();
6958        t.urgent = true;
6959        t
6960    }
6961
6962    #[test]
6963    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
6964        let dir = tempfile::tempdir().unwrap();
6965        let queue = Queue::at(dir.path().join("queue"));
6966        let mut parked = task_with_id("parked");
6967        parked.start("run".into());
6968        parked.park("upgrade");
6969        parked.record_pass_at(
6970            "run",
6971            0,
6972            Some(Timestamp::now()),
6973            1,
6974            Some(crate::run::ParkCause::Upgrade {
6975                from: "old".into(),
6976                to: None,
6977            }),
6978        );
6979        let mut fresh = task_with_id("fresh");
6980        fresh.priority = 100;
6981        let mut urgent_task = urgent_task("urgent");
6982        for t in [&mut parked, &mut fresh, &mut urgent_task] {
6983            queue.put(t).unwrap();
6984        }
6985        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
6986        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
6987        let candidates = runnable(&queue);
6988        assert_eq!(candidates[0].id, parked.id);
6989        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
6990        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_none());
6991        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_some());
6992        drop(first);
6993        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
6994        let next = runnable(&queue)
6995            .into_iter()
6996            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent))
6997            .unwrap();
6998        assert_eq!(next.task.id, fresh.id);
6999        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7000        drop(claimed_elsewhere);
7001        drop(next);
7002        assert!(claim_dispatch(&queue, &parked, true, &ordinary, &urgent).is_none());
7003    }
7004
7005    #[test]
7006    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7007        let dir = tempfile::tempdir().unwrap();
7008        let queue = Queue::at(dir.path().join("queue"));
7009        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7010        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7011        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7012        let mut first = task();
7013        queue.put(&mut first).unwrap();
7014        let stale_plain = queue.get(&first.id).unwrap();
7015        first.set_urgent(true).unwrap();
7016        queue.put(&mut first).unwrap();
7017        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7018        let mut second = urgent_task("second");
7019        queue.put(&mut second).unwrap();
7020        assert!(claim_dispatch(&queue, &second, false, &ordinary, &urgent).is_none());
7021        drop(queue.claim(&second.id).unwrap());
7022        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7023        drop(dispatched);
7024        let stale_urgent = queue.get(&first.id).unwrap();
7025        first.set_urgent(false).unwrap();
7026        queue.put(&mut first).unwrap();
7027        assert!(claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent).is_none());
7028        assert_eq!(urgent.available_permits(), 1);
7029        drop(queue.claim(&first.id).unwrap());
7030        drop(occupied);
7031    }
7032
7033    #[test]
7034    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7035        let dir = tempfile::tempdir().unwrap();
7036        let queue = Queue::at(dir.path().join("queue"));
7037        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7038        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7039        let mut t = task();
7040        queue.put(&mut t).unwrap();
7041        for enabled in [true, false] {
7042            let stale = queue.get(&t.id).unwrap();
7043            t.set_urgent(enabled).unwrap();
7044            queue.put(&mut t).unwrap();
7045            assert_ne!(stale.urgent, enabled);
7046            let DispatchClaim {
7047                task: fresh,
7048                claim,
7049                permit,
7050            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7051            assert_eq!(fresh.urgent, enabled);
7052            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7053            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7054            assert!(queue.claim(&t.id).is_err());
7055            assert_eq!(fresh.attempts, stale.attempts);
7056            drop((claim, permit));
7057            assert_eq!(ordinary.available_permits(), 1);
7058            assert_eq!(urgent.available_permits(), 1);
7059        }
7060        t.set_urgent(true).unwrap();
7061        queue.put(&mut t).unwrap();
7062        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7063        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7064        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7065        drop(queue.claim(&t.id).unwrap());
7066        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7067        drop(occupied);
7068        assert!(claim_dispatch(&queue, &t, true, &ordinary, &urgent).is_none());
7069        drop(queue.claim(&t.id).unwrap());
7070        let held = queue.claim(&t.id).unwrap();
7071        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7072        drop(held);
7073        t.status = TaskStatus::Held;
7074        queue.put(&mut t).unwrap();
7075        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7076        drop(queue.claim(&t.id).unwrap());
7077        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7078        assert!(claim_dispatch(&queue, &t, false, &ordinary, &urgent).is_none());
7079        drop(queue.claim(&t.id).unwrap());
7080        assert_eq!(urgent.available_permits(), 1);
7081    }
7082
7083    /// The land-resume exemption wins outright, whether or not the candidate
7084    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7085    /// queue behind anything" guarantee cannot be weaker just because the
7086    /// same task was also filed with `--urgent`.
7087    #[test]
7088    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7089        assert_eq!(permit_kind(true, false), PermitKind::None);
7090        assert_eq!(permit_kind(true, true), PermitKind::None);
7091    }
7092
7093    /// The one property this whole feature exists for: `--urgent` draws from
7094    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7095    /// ordinary candidate draws from the ordinary pool exactly as before,
7096    /// untouched by the urgent slot's existence.
7097    #[test]
7098    fn permit_kind_separates_urgent_from_ordinary() {
7099        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7100        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7101    }
7102
7103    /// The exact wiring `attempt` runs before minting anything: a config's
7104    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7105    /// Free space is injected rather than asked of the real disk - the point
7106    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7107    /// is deterministic on every machine this test runs on, never dependent
7108    /// on how full the CI runner's own disk happens to be.
7109    #[test]
7110    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7111        let cfg = Config::default();
7112        let repo = Path::new("/any/repo/path");
7113
7114        let reason =
7115            disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
7116        assert!(reason.contains("1024"), "{reason}");
7117        assert!(
7118            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7119            "{reason}"
7120        );
7121
7122        assert_eq!(
7123            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
7124            None,
7125            "exactly at the floor is open"
7126        );
7127        assert_eq!(
7128            disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
7129            None,
7130            "comfortably above the floor is open"
7131        );
7132    }
7133
7134    #[test]
7135    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
7136        let mut cfg = Config::default();
7137        cfg.disk.min_free_bytes = 0;
7138        let repo = Path::new("/any/repo/path");
7139        assert_eq!(
7140            disk_gate_with(repo, &cfg, |_| Ok(0)),
7141            None,
7142            "a zero floor never measures at all"
7143        );
7144    }
7145
7146    #[test]
7147    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
7148        let cfg = Config::default();
7149        let repo = Path::new("/any/repo/path");
7150        let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
7151            .expect("a measurement failure must close the gate, not open it");
7152        assert!(reason.contains("could not measure"), "{reason}");
7153    }
7154
7155    #[test]
7156    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
7157        let ordinary = task();
7158        let next = advance_interrupt(
7159            Interrupt::Idle,
7160            std::slice::from_ref(&ordinary.id),
7161            std::slice::from_ref(&ordinary),
7162        );
7163        assert_eq!(next, Interrupt::Idle);
7164    }
7165
7166    #[test]
7167    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
7168        // Nothing to interrupt - this is just an ordinary candidate, and the
7169        // loop's normal dispatch will pick it up like any other.
7170        let marked = interrupt_task("marked");
7171        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7172        assert_eq!(next, Interrupt::Idle);
7173    }
7174
7175    #[test]
7176    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
7177        let marked = interrupt_task("marked");
7178        let next = advance_interrupt(
7179            Interrupt::Idle,
7180            &["running".to_owned()],
7181            std::slice::from_ref(&marked),
7182        );
7183        assert_eq!(
7184            next,
7185            Interrupt::Parking {
7186                parked: vec!["running".to_owned()],
7187                interrupt_task: "marked".to_owned(),
7188            }
7189        );
7190    }
7191
7192    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
7193    /// one run can be in flight when a task becomes runnable and marked.
7194    /// Parking all of them would mean `Resuming` later has more than one id
7195    /// to release back to ordinary dispatch, which cannot be made safe
7196    /// against that same setting's own extra concurrency slots letting two
7197    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
7198    /// The simplification the task's own constraints ask for: do not begin
7199    /// a sequence at all until the herd settles back to exactly one.
7200    #[test]
7201    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
7202        let marked = interrupt_task("marked");
7203
7204        let two = advance_interrupt(
7205            Interrupt::Idle,
7206            &["a".to_owned(), "b".to_owned()],
7207            std::slice::from_ref(&marked),
7208        );
7209        assert_eq!(two, Interrupt::Idle);
7210
7211        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
7212        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
7213    }
7214
7215    #[test]
7216    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
7217        let state = Interrupt::Parking {
7218            parked: vec!["running".to_owned()],
7219            interrupt_task: "marked".to_owned(),
7220        };
7221        // Still in flight: no change.
7222        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
7223        assert_eq!(still_going, state);
7224
7225        // Left flight, but the interrupt task has not been dispatched yet on
7226        // this tick - stays `Parking` so `interrupt_gate` can let it through,
7227        // as long as it is still runnable.
7228        let stopped_but_not_yet_dispatched =
7229            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
7230        assert_eq!(stopped_but_not_yet_dispatched, state);
7231
7232        // Left flight, and the interrupt task is now in flight itself.
7233        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
7234        assert_eq!(
7235            dispatched,
7236            Interrupt::Running {
7237                parked: vec!["running".to_owned()],
7238                interrupt_task: "marked".to_owned(),
7239            }
7240        );
7241    }
7242
7243    #[test]
7244    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
7245        let state = Interrupt::Running {
7246            parked: vec!["running".to_owned()],
7247            interrupt_task: "marked".to_owned(),
7248        };
7249        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
7250        assert_eq!(still_running, state);
7251
7252        // Whatever it ended as - merged, failed, held - is not this
7253        // function's concern: leaving flight is the only trigger, driven
7254        // straight off the same in-flight list `poll` already reaps. It does
7255        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
7256        // why that would let an unrelated task start ahead of, or alongside,
7257        // the guaranteed resume.
7258        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
7259        assert_eq!(
7260            ended,
7261            Interrupt::Resuming {
7262                parked: vec!["running".to_owned()]
7263            }
7264        );
7265    }
7266
7267    #[test]
7268    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
7269        let state = Interrupt::Resuming {
7270            parked: vec!["running".to_owned()],
7271        };
7272        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
7273        assert_eq!(still_waiting, state);
7274
7275        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
7276        assert_eq!(dispatched, Interrupt::Idle);
7277    }
7278
7279    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
7280    /// or otherwise moved on by an operator with no claim standing in the
7281    /// way - must not wedge the sequence (and so the whole loop's dispatch,
7282    /// via `interrupt_gate`) waiting forever for a dispatch that can never
7283    /// come. The parked run still gets its resume.
7284    #[test]
7285    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
7286    {
7287        let state = Interrupt::Parking {
7288            parked: vec!["running".to_owned()],
7289            interrupt_task: "marked".to_owned(),
7290        };
7291        // `marked` has been held/blocked/deleted since the sequence began:
7292        // it no longer appears in `runnable` at all.
7293        let next = advance_interrupt(state, &[], &[]);
7294        assert_eq!(
7295            next,
7296            Interrupt::Resuming {
7297                parked: vec!["running".to_owned()]
7298            },
7299            "abandoning the interrupt must not abandon the resume it owes"
7300        );
7301    }
7302
7303    /// The same abandonment, one step later: `Resuming` itself must not wait
7304    /// forever for a parked task that has since become unrunnable.
7305    #[test]
7306    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
7307        let state = Interrupt::Resuming {
7308            parked: vec!["running".to_owned()],
7309        };
7310        let next = advance_interrupt(state, &[], &[]);
7311        assert_eq!(
7312            next,
7313            Interrupt::Idle,
7314            "nothing is left to wait for; the loop must not stay wedged"
7315        );
7316    }
7317
7318    #[test]
7319    fn disabled_by_config_the_sequence_can_never_leave_idle() {
7320        let marked = interrupt_task("marked");
7321        let next = advance_interrupt_tick(
7322            false,
7323            Interrupt::Idle,
7324            &["running".to_owned()],
7325            std::slice::from_ref(&marked),
7326        );
7327        assert_eq!(
7328            next,
7329            Interrupt::Idle,
7330            "an unmarked, unconfigured daemon must behave exactly as before"
7331        );
7332    }
7333
7334    #[test]
7335    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
7336        let state = Interrupt::Parking {
7337            parked: vec!["running".to_owned()],
7338            interrupt_task: "marked".to_owned(),
7339        };
7340        let candidates = vec![interrupt_task("marked"), task()];
7341        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7342        assert!(
7343            allowed.is_empty(),
7344            "nothing may dispatch - not even the interrupt task itself - \
7345             until the parked run has actually stopped"
7346        );
7347    }
7348
7349    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
7350    /// grow a special case for it: an urgent candidate that is not the
7351    /// interrupt task withholds exactly like an ordinary one for as long as
7352    /// the parked run it is racing has not actually left flight. A version
7353    /// of this feature once bypassed the gate for urgent candidates, on the
7354    /// theory that a genuinely separate concurrency lane could not collide
7355    /// with 75dd's own; it could, and did - the bypassed task dispatched
7356    /// alongside a run 75dd's own state machine had only *asked* to park,
7357    /// not yet confirmed gone, which is exactly the second run
7358    /// `Interrupt::Parking`'s own doc says must never happen. There is no
7359    /// tick during Parking/Running/Resuming where letting an extra
7360    /// candidate through is safe, urgent or not - the parked run may still
7361    /// be genuinely mid-call.
7362    #[test]
7363    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
7364        for state in [
7365            Interrupt::Parking {
7366                parked: vec!["running".to_owned()],
7367                interrupt_task: "marked".to_owned(),
7368            },
7369            Interrupt::Running {
7370                parked: vec!["running".to_owned()],
7371                interrupt_task: "marked".to_owned(),
7372            },
7373            Interrupt::Resuming {
7374                parked: vec!["running".to_owned()],
7375            },
7376        ] {
7377            let candidates = vec![
7378                interrupt_task("marked"),
7379                urgent_task("hot"),
7380                task_with_id("ordinary"),
7381            ];
7382            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
7383            assert!(
7384                !allowed.iter().any(|t| t.id == "hot"),
7385                "an urgent candidate must wait out the same gate as anything \
7386                 else while the run it would run alongside has not actually \
7387                 left flight, for state {state:?}: {allowed:?}"
7388            );
7389        }
7390    }
7391
7392    /// The one case where marking a task `--urgent` and `interrupt` at once
7393    /// is not redundant: once the interrupt sequence's own guaranteed
7394    /// resume/dispatch actually admits the task, it is unaffected by also
7395    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
7396    /// never on the urgent flag.
7397    #[test]
7398    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
7399        let state = Interrupt::Resuming {
7400            parked: vec!["hot".to_owned()],
7401        };
7402        let candidates = vec![urgent_task("hot"), task()];
7403        let allowed = interrupt_gate(&state, &[], candidates);
7404        assert_eq!(
7405            allowed.iter().filter(|t| t.id == "hot").count(),
7406            1,
7407            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
7408        );
7409    }
7410
7411    #[test]
7412    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
7413        let state = Interrupt::Parking {
7414            parked: vec!["running".to_owned()],
7415            interrupt_task: "marked".to_owned(),
7416        };
7417        let other = task();
7418        let candidates = vec![interrupt_task("marked"), other.clone()];
7419        let allowed = interrupt_gate(&state, &[], candidates);
7420        assert_eq!(allowed.len(), 1);
7421        assert_eq!(allowed[0].id, "marked");
7422    }
7423
7424    #[test]
7425    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
7426        let state = Interrupt::Running {
7427            parked: vec!["running".to_owned()],
7428            interrupt_task: "marked".to_owned(),
7429        };
7430        let candidates = vec![task(), task()];
7431        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
7432        assert!(allowed.is_empty());
7433    }
7434
7435    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
7436    /// sequence began (only reachable above the default
7437    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
7438    /// never both in the same tick, which is what "exactly one resume, no
7439    /// simultaneous run" actually requires structurally rather than by
7440    /// coincidence of how many ordinary slots happen to be free.
7441    #[test]
7442    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
7443        let state = Interrupt::Resuming {
7444            parked: vec!["a".to_owned(), "c".to_owned()],
7445        };
7446        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
7447        let allowed = interrupt_gate(&state, &[], candidates);
7448        assert_eq!(
7449            allowed.len(),
7450            1,
7451            "at most one candidate may be offered while resuming: {allowed:?}"
7452        );
7453        assert_eq!(allowed[0].id, "a");
7454    }
7455
7456    #[test]
7457    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
7458        let state = Interrupt::Resuming {
7459            parked: vec!["a".to_owned()],
7460        };
7461        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
7462        assert!(allowed.is_empty());
7463    }
7464
7465    /// The invariant the completion criteria ask for by name: across a whole
7466    /// simulated sequence, there is never a tick where the gate would let
7467    /// through both the parked run's resume and the interrupt task, and
7468    /// exactly one candidate resumes the instant the interrupt task's run
7469    /// ends - never zero, never more than one.
7470    #[test]
7471    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
7472        let running = task(); // id: whatever `Task::new` minted
7473        let marked = interrupt_task("marked");
7474
7475        let mut state = Interrupt::Idle;
7476        // Tick 1: `running` is in flight, `marked` becomes runnable.
7477        let in_flight = vec![running.id.clone()];
7478        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
7479        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
7480        assert!(gated.is_empty(), "still waiting on `running` to park");
7481
7482        // Tick 2: `running` parked and left flight; nothing dispatched yet.
7483        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
7484        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
7485        assert_eq!(
7486            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7487            vec!["marked"],
7488            "only the interrupt task may be offered to the dispatcher now"
7489        );
7490
7491        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
7492        state = advance_interrupt_tick(
7493            true,
7494            state,
7495            &["marked".to_owned()],
7496            std::slice::from_ref(&running),
7497        );
7498        let gated = interrupt_gate(
7499            &state,
7500            &["marked".to_owned()],
7501            vec![marked.clone(), running.clone()],
7502        );
7503        assert!(
7504            gated.is_empty(),
7505            "the parked run must not be offered back while the interrupt \
7506             task is still running"
7507        );
7508
7509        // Tick 4: `marked`'s run reached a terminal status and left flight.
7510        // A higher-priority ordinary task `other` is also runnable now - it
7511        // must not be let through instead of, or alongside, `running`.
7512        let other = task_with_id("other");
7513        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
7514        assert_eq!(
7515            state,
7516            Interrupt::Resuming {
7517                parked: vec![running.id.clone()]
7518            }
7519        );
7520        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
7521        assert_eq!(
7522            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7523            vec![running.id.as_str()],
7524            "exactly the parked run resumes - not the unrelated task, even \
7525             though it was offered first"
7526        );
7527
7528        // Tick 5: `running` is now in flight (dispatched from tick 4's
7529        // gate). Only now does the sequence end and ordinary dispatch fully
7530        // resume.
7531        state = advance_interrupt_tick(
7532            true,
7533            state,
7534            std::slice::from_ref(&running.id),
7535            std::slice::from_ref(&other),
7536        );
7537        assert_eq!(state, Interrupt::Idle);
7538        let gated = interrupt_gate(
7539            &state,
7540            std::slice::from_ref(&running.id),
7541            vec![other.clone()],
7542        );
7543        assert_eq!(
7544            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7545            vec![other.id.as_str()],
7546            "ordinary dispatch is unrestricted again"
7547        );
7548    }
7549
7550    #[test]
7551    fn every_run_status_settles_the_task_it_came_from() {
7552        // run status, resulting task status, attempts still standing after one
7553        let table = [
7554            (RunStatus::Merged, TaskStatus::Done, 1),
7555            (RunStatus::Ready, TaskStatus::Done, 1),
7556            (RunStatus::Stalled, TaskStatus::Failed, 0),
7557            (RunStatus::Blocked, TaskStatus::Failed, 1),
7558            (RunStatus::Failed, TaskStatus::Failed, 1),
7559            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
7560            (RunStatus::Prep, TaskStatus::Failed, 1),
7561            (RunStatus::Implementing, TaskStatus::Failed, 1),
7562            (RunStatus::Judging, TaskStatus::Failed, 1),
7563            (RunStatus::Deliberating, TaskStatus::Failed, 1),
7564            (RunStatus::Voting, TaskStatus::Failed, 1),
7565            (RunStatus::Reviewing, TaskStatus::Failed, 1),
7566            (RunStatus::Gating, TaskStatus::Failed, 1),
7567        ];
7568        for (run, want, attempts) in table {
7569            let mut t = task();
7570            t.start("20260902-000000-aaaa".to_owned());
7571            settle(
7572                &mut t,
7573                Verdict {
7574                    status: run,
7575                    left_pr: false,
7576                    parked: false,
7577                    quota_hit: matches!(run, RunStatus::Stalled),
7578                    no_viable_candidates: false,
7579                },
7580                "why",
7581                2,
7582            );
7583            assert_eq!(t.status, want, "task status after {}", label(run));
7584            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
7585        }
7586    }
7587
7588    #[test]
7589    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
7590        let mut stalled = task();
7591        stalled.start("20260902-000000-aaaa".to_owned());
7592        settle(
7593            &mut stalled,
7594            Verdict {
7595                status: RunStatus::Stalled,
7596                left_pr: false,
7597                parked: false,
7598                quota_hit: true,
7599                no_viable_candidates: false,
7600            },
7601            "quota",
7602            1,
7603        );
7604        assert_eq!(stalled.attempts, 0);
7605        assert!(
7606            stalled.status.runnable(),
7607            "a machine problem must leave the task in line"
7608        );
7609
7610        let mut blocked = task();
7611        blocked.start("20260902-000000-aaaa".to_owned());
7612        settle(
7613            &mut blocked,
7614            Verdict {
7615                status: RunStatus::Blocked,
7616                left_pr: false,
7617                parked: false,
7618                quota_hit: false,
7619                no_viable_candidates: false,
7620            },
7621            "findings open",
7622            1,
7623        );
7624        assert_eq!(blocked.attempts, 1);
7625        assert_eq!(
7626            blocked.status,
7627            TaskStatus::Held,
7628            "the last attempt hands the task to a human"
7629        );
7630    }
7631
7632    #[test]
7633    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
7634        // Attempts to spare: without the pull request this task would go
7635        // straight back in line and run the whole competition again.
7636        let mut delivered = task();
7637        delivered.start("20260903-080619-01c2".to_owned());
7638        settle(
7639            &mut delivered,
7640            Verdict {
7641                status: RunStatus::Blocked,
7642                left_pr: true,
7643                parked: false,
7644                quota_hit: false,
7645                no_viable_candidates: false,
7646            },
7647            "no check status",
7648            4,
7649        );
7650        assert_eq!(
7651            delivered.status,
7652            TaskStatus::Held,
7653            "a pull request waiting on CI or a person is not a retryable failure"
7654        );
7655        assert!(
7656            !delivered.status.runnable(),
7657            "the loop must not pick this task up again"
7658        );
7659        assert_eq!(
7660            delivered.last_error.as_deref(),
7661            Some("no check status"),
7662            "the operator needs to be told what the gate was waiting for"
7663        );
7664
7665        // The same status without a pull request is a plain failure, and with
7666        // attempts left it is retried.
7667        let mut empty_handed = task();
7668        empty_handed.start("20260903-080619-01c2".to_owned());
7669        settle(
7670            &mut empty_handed,
7671            Verdict {
7672                status: RunStatus::Blocked,
7673                left_pr: false,
7674                parked: false,
7675                quota_hit: false,
7676                no_viable_candidates: false,
7677            },
7678            "findings open",
7679            4,
7680        );
7681        assert_eq!(empty_handed.status, TaskStatus::Failed);
7682        assert!(empty_handed.status.runnable());
7683    }
7684
7685    #[test]
7686    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
7687        // Every candidate agreed, with evidence, that nothing belonged in the
7688        // worktree. That is not a confirmed success to close automatically -
7689        // a human still has to check the claim - and it is not an ordinary
7690        // failure either, so this settles exactly like a pull request nobody
7691        // merged yet: `Held`, same as `Blocked` with a PR.
7692        let mut noop = task();
7693        noop.start("20260912-131304-391f".to_owned());
7694        settle(
7695            &mut noop,
7696            Verdict {
7697                status: RunStatus::VerifiedNoop,
7698                left_pr: false,
7699                parked: false,
7700                quota_hit: false,
7701                no_viable_candidates: true,
7702            },
7703            "candidate A: already fixed by b32cfc4, on main",
7704            4,
7705        );
7706        assert_eq!(
7707            noop.status,
7708            TaskStatus::Held,
7709            "an unverified claim is a request for a human, not a failure"
7710        );
7711        assert!(
7712            !noop.status.runnable(),
7713            "the loop must not requeue this on the same unverified claim"
7714        );
7715        // `Task::release` resets attempts to zero the moment a human looks at
7716        // the evidence and lets it run again, so it does not matter here
7717        // whether the one attempt already spent stays spent - what matters is
7718        // that nothing retries this task unattended in the meantime.
7719        assert_eq!(noop.attempts, 1);
7720    }
7721
7722    #[test]
7723    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
7724        // Parking is the operator asking for the process back - to replace the
7725        // binary, most of all. The run's work is intact on disk, so this is
7726        // not a failed attempt, and charging for it would mean a few upgrades
7727        // could exhaust a budget meant for agents that misbehaved.
7728        let mut parked = task();
7729        parked.start("20260903-183634-2d98".to_owned());
7730        settle(
7731            &mut parked,
7732            Verdict {
7733                status: RunStatus::Implementing,
7734                left_pr: false,
7735                quota_hit: false,
7736                parked: true,
7737                no_viable_candidates: false,
7738            },
7739            "parked after `implementing`",
7740            2,
7741        );
7742        assert_eq!(parked.attempts, 0, "a park is refunded");
7743        assert!(
7744            parked.status.runnable(),
7745            "and the task stays in line so the next loop resumes its run"
7746        );
7747        assert_eq!(parked.status, TaskStatus::Parked);
7748        assert_eq!(
7749            parked.park_reason.as_deref(),
7750            Some("parked after `implementing`"),
7751            "the card says where it stopped"
7752        );
7753        assert_eq!(parked.last_error, None, "nothing failed");
7754
7755        // Without the park flag the same non-terminal status is what it always
7756        // was: `execute` returning mid-flight, which is a bug and spends an
7757        // attempt so a task cannot loop on it forever.
7758        let mut broken = task();
7759        broken.start("20260903-183634-2d98".to_owned());
7760        settle(
7761            &mut broken,
7762            Verdict {
7763                status: RunStatus::Implementing,
7764                left_pr: false,
7765                quota_hit: false,
7766                parked: false,
7767                no_viable_candidates: false,
7768            },
7769            "returned mid-flight",
7770            2,
7771        );
7772        assert_eq!(broken.attempts, 1);
7773    }
7774
7775    #[test]
7776    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
7777        // Run e633: quorum lost because two judges answered with the wrong
7778        // JSON shape, `quota: []`. Refunding that takes the bound off the
7779        // retry loop, and each retry pays for a fresh hour-long implement
7780        // wave before it can fail the same way.
7781        let mut flaky = task();
7782        flaky.start("20260903-123023-e633".to_owned());
7783        settle(
7784            &mut flaky,
7785            Verdict {
7786                status: RunStatus::Stalled,
7787                left_pr: false,
7788                parked: false,
7789                quota_hit: false,
7790                no_viable_candidates: false,
7791            },
7792            "verdict rests on 1 of 3 judges",
7793            2,
7794        );
7795        assert_eq!(
7796            flaky.attempts, 1,
7797            "flakiness spends an attempt, so `max_attempts` still bounds it"
7798        );
7799        assert!(flaky.status.runnable(), "and it is still worth retrying");
7800
7801        // The same status, lost to a rate limit, is the machine's fault.
7802        let mut limited = task();
7803        limited.start("20260903-123023-e633".to_owned());
7804        settle(
7805            &mut limited,
7806            Verdict {
7807                status: RunStatus::Stalled,
7808                left_pr: false,
7809                parked: false,
7810                quota_hit: true,
7811                no_viable_candidates: false,
7812            },
7813            "judge-2, judge-3 out of quota",
7814            2,
7815        );
7816        assert_eq!(limited.attempts, 0, "a quota window is refunded");
7817        assert!(limited.status.runnable());
7818
7819        // And the bound really binds: a task that keeps stalling on flakiness
7820        // reaches a human instead of running the roster forever.
7821        let mut worn = task();
7822        for _ in 0..2 {
7823            worn.release();
7824        }
7825        worn.start("20260903-123023-e633".to_owned());
7826        worn.attempts = 2;
7827        settle(
7828            &mut worn,
7829            Verdict {
7830                status: RunStatus::Stalled,
7831                left_pr: false,
7832                parked: false,
7833                quota_hit: false,
7834                no_viable_candidates: false,
7835            },
7836            "no quorum again",
7837            2,
7838        );
7839        assert_eq!(worn.status, TaskStatus::Held);
7840        assert!(!worn.status.runnable());
7841    }
7842
7843    #[test]
7844    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
7845        // The implement wave loses every seat to the same rate limit and
7846        // `after_implement` bails with nothing viable, which surfaces as
7847        // `Failed` rather than `Stalled`. That is the same machine fact the
7848        // `Stalled`-quota row already refunds, and must be refunded the same
7849        // way, or a quota outage quietly holds every task it touches instead
7850        // of leaving them in line for the reset.
7851        let mut wiped_out = task();
7852        wiped_out.start("20260907-025000-a1b2".to_owned());
7853        settle(
7854            &mut wiped_out,
7855            Verdict {
7856                status: RunStatus::Failed,
7857                left_pr: false,
7858                parked: false,
7859                quota_hit: true,
7860                no_viable_candidates: true,
7861            },
7862            "no candidate produced a change; nothing to judge",
7863            2,
7864        );
7865        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
7866        assert!(
7867            wiped_out.status.runnable(),
7868            "a machine problem must leave the task in line"
7869        );
7870
7871        // This is the exemption that must stay narrow: a candidate that did
7872        // produce a change, and then failed for some other reason, still
7873        // spends the attempt even though a seat elsewhere hit its quota.
7874        // Otherwise every ordinary failure that happens to share a run with
7875        // an unrelated rate limit would be refunded for free.
7876        let mut partial_progress = task();
7877        partial_progress.start("20260907-025500-c3d4".to_owned());
7878        settle(
7879            &mut partial_progress,
7880            Verdict {
7881                status: RunStatus::Failed,
7882                left_pr: false,
7883                parked: false,
7884                quota_hit: true,
7885                no_viable_candidates: false,
7886            },
7887            "gate failed on the winning candidate",
7888            2,
7889        );
7890        assert_eq!(
7891            partial_progress.attempts, 1,
7892            "a candidate that actually produced a change spends the attempt \
7893             even though some other seat hit its quota"
7894        );
7895        assert!(partial_progress.status.runnable());
7896    }
7897
7898    #[test]
7899    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
7900        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
7901        // disk, and that construction must reach the same conclusion as the
7902        // one `attempt` builds from a live run, or a crash at exactly the
7903        // wrong moment gives a recovered task a different policy than one a
7904        // daemon finished settling itself.
7905        let mut t = task();
7906        t.start("20260907-025000-a1b2".to_owned());
7907        let mut state = run_state(RunStatus::Failed);
7908        state.quota.push(QuotaLoss {
7909            seat: "cand-a".to_owned(),
7910            node: "implement".to_owned(),
7911            at: Timestamp::now(),
7912            reset: None,
7913        });
7914        assert!(
7915            state.viable().is_empty(),
7916            "no candidate was added, so nothing is viable"
7917        );
7918        reclaim(&mut t, Some(state), 2, "en");
7919        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
7920        assert!(t.status.runnable());
7921    }
7922
7923    #[test]
7924    fn a_held_task_is_never_offered_to_the_loop() {
7925        let dir = tempfile::tempdir().unwrap();
7926        let queue = Queue::at(dir.path().to_path_buf());
7927        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
7928            let mut t = task();
7929            t.id = format!("2026090{n}-000000-000{n}");
7930            t.priority = priority;
7931            queue.put(&mut t).unwrap();
7932        }
7933        let mut held = task();
7934        held.id = "20260909-000000-9999".to_owned();
7935        held.priority = 99;
7936        held.hold_machine(None);
7937        queue.put(&mut held).unwrap();
7938
7939        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
7940        assert_eq!(order.len(), 3);
7941        assert!(!order.contains(&held.id));
7942        assert_eq!(
7943            order.first().cloned(),
7944            queue.next_runnable().map(|t| t.id),
7945            "the loop's first candidate is exactly what the queue offers"
7946        );
7947        assert_eq!(
7948            order,
7949            vec![
7950                "20260902-000000-0002".to_owned(),
7951                "20260903-000000-0003".to_owned(),
7952                "20260901-000000-0001".to_owned(),
7953            ],
7954            "priority first, then oldest, so nothing starves"
7955        );
7956    }
7957
7958    #[test]
7959    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
7960        let dir = tempfile::tempdir().unwrap();
7961        let queue = Queue::at(dir.path().to_path_buf());
7962        let mut old = task();
7963        old.id = "20260101-000000-old0".to_owned();
7964        queue.put(&mut old).unwrap();
7965        let mut fresh = task();
7966        fresh.id = "20260101-000000-new0".to_owned();
7967        queue.put(&mut fresh).unwrap();
7968
7969        // No parseable pid at all, so age is the only signal there is to
7970        // check - unlike a real `Queue::claim`, which always names a real,
7971        // and therefore alive, pid this test cannot fake as dead.
7972        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
7973        std::thread::sleep(Duration::from_millis(60));
7974        let live = queue.claim(&fresh.id).unwrap();
7975
7976        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
7977        assert_eq!(swept, vec![old.id.clone()]);
7978        assert!(
7979            queue.claim(&old.id).is_ok(),
7980            "an unparseable lock older than the threshold is swept"
7981        );
7982        assert!(
7983            queue.claim(&fresh.id).is_err(),
7984            "a live pid protects its lock regardless of age"
7985        );
7986        drop(live);
7987    }
7988
7989    #[test]
7990    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
7991        // A live worker's claim remains authoritative even beyond the sweep's
7992        // age limit. Sweeping it would permit a second competing attempt.
7993        let dir = tempfile::tempdir().unwrap();
7994        let queue = Queue::at(dir.path().to_path_buf());
7995        let mut t = task();
7996        t.id = "20260101-000000-live".to_owned();
7997        queue.put(&mut t).unwrap();
7998
7999        let claim = queue.claim(&t.id).unwrap();
8000        std::thread::sleep(Duration::from_millis(60));
8001
8002        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8003        assert!(
8004            swept.is_empty(),
8005            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8006        );
8007        assert!(
8008            queue.claim(&t.id).is_err(),
8009            "the lock still protects its task"
8010        );
8011        drop(claim);
8012    }
8013
8014    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8015    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8016    fn injected_dead_pid() -> u32 {
8017        std::process::id().checked_add(1).unwrap_or(1)
8018    }
8019
8020    #[test]
8021    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8022        let dir = tempfile::tempdir().unwrap();
8023        let queue = Queue::at(dir.path().to_path_buf());
8024        let mut t = task();
8025        t.id = "20260101-000000-dead".to_owned();
8026        queue.put(&mut t).unwrap();
8027        let dead_pid = injected_dead_pid();
8028
8029        // Written directly rather than through `Queue::claim`, which would
8030        // stamp this test process's own very much alive pid and defeat the
8031        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8032        // like moments after it died, not six hours later.
8033        std::fs::write(
8034            dir.path().join(format!("{}.lock", t.id)),
8035            dead_pid.to_string(),
8036        )
8037        .unwrap();
8038
8039        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8040            pid != dead_pid
8041        });
8042        assert_eq!(
8043            swept,
8044            vec![t.id.clone()],
8045            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8046        );
8047        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8048    }
8049
8050    #[test]
8051    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8052        let dir = tempfile::tempdir().unwrap();
8053        let queue = Queue::at(dir.path().to_path_buf());
8054        let mut t = task();
8055        t.id = "20260101-000000-late".to_owned();
8056        queue.put(&mut t).unwrap();
8057        let dead_pid = injected_dead_pid();
8058
8059        // Tick one, standing in for the sweep `poll` already runs at
8060        // startup: nothing to find yet.
8061        assert!(
8062            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8063            "nothing has claimed the task yet"
8064        );
8065
8066        // A second daemon claims the task and dies before it ever writes
8067        // `running`, well after this loop's own startup sweep already ran.
8068        std::fs::write(
8069            dir.path().join(format!("{}.lock", t.id)),
8070            dead_pid.to_string(),
8071        )
8072        .unwrap();
8073
8074        // Tick two, standing in for a poll long into this daemon's uptime:
8075        // the same function, called again, notices what only just appeared -
8076        // proving the sweep is not a one-shot startup check.
8077        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8078            pid != dead_pid
8079        });
8080        assert_eq!(swept, vec![t.id.clone()]);
8081    }
8082
8083    #[test]
8084    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8085        // `reclaim_orphaned_running` looks up the task's last run, which
8086        // touches `run::home()`; the first call anywhere in this binary wins,
8087        // so this is a no-op if another test already pinned one, and either
8088        // way the run id below is never written under it.
8089        crate::run::pin_test_home();
8090        let dir = tempfile::tempdir().unwrap();
8091        let queue = Queue::at(dir.path().to_path_buf());
8092        let mut t = task();
8093        t.id = "20260101-000000-crsh".to_owned();
8094        t.status = TaskStatus::Running;
8095        t.attempts = 1;
8096        // No `run.json` behind this id: standing in for a run this test does
8097        // not need to make readable, since the point is the lock, not the
8098        // recovery table `reclaim` already has its own tests for.
8099        t.runs.push("20260904-000000-4043".to_owned());
8100        queue.put(&mut t).unwrap();
8101        let dead_pid = injected_dead_pid();
8102
8103        // The crashed daemon's own claim, naming a pid nothing on the
8104        // machine holds anymore.
8105        std::fs::write(
8106            dir.path().join(format!("{}.lock", t.id)),
8107            dead_pid.to_string(),
8108        )
8109        .unwrap();
8110
8111        // Before the lock is swept the task looks claimed, and
8112        // `reclaim_orphaned_running` must leave it alone - this is exactly
8113        // the bug: a `running` task stranded behind a dead daemon's lock,
8114        // invisible to the claim-as-proof check because the lock outlived
8115        // the process that wrote it.
8116        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
8117        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
8118
8119        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8120            pid != dead_pid
8121        });
8122        assert_eq!(swept, vec![t.id.clone()]);
8123
8124        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
8125        assert_eq!(reclaimed, vec![t.id.clone()]);
8126        let after = queue.get(&t.id).unwrap();
8127        assert_eq!(
8128            after.status,
8129            TaskStatus::Held,
8130            "no run.json to recover from, so a human is asked"
8131        );
8132        assert_eq!(
8133            after.runs,
8134            vec!["20260904-000000-4043".to_owned()],
8135            "the crashed run's id is kept as evidence, not discarded"
8136        );
8137    }
8138
8139    #[test]
8140    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
8141        let dir = tempfile::tempdir().unwrap();
8142        let queue = Queue::at(dir.path().to_path_buf());
8143        let mut t = task();
8144        t.id = "20260101-000000-unknown".to_owned();
8145        queue.put(&mut t).unwrap();
8146        let dead_pid = injected_dead_pid();
8147        std::fs::write(
8148            dir.path().join(format!("{}.lock", t.id)),
8149            dead_pid.to_string(),
8150        )
8151        .unwrap();
8152
8153        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
8154        assert!(swept.is_empty(), "an unknown pid must keep its lock");
8155        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
8156    }
8157
8158    fn run_state_in(status: RunStatus, language: &str) -> RunState {
8159        let mut s = run_state(status);
8160        s.config.graph.language = language.to_owned();
8161        s
8162    }
8163
8164    fn unstarted_verdict(status: RunStatus) -> Verdict {
8165        Verdict {
8166            status,
8167            left_pr: false,
8168            quota_hit: false,
8169            parked: false,
8170            no_viable_candidates: false,
8171        }
8172    }
8173
8174    #[test]
8175    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
8176        let mut t = task();
8177        t.attempts = 1;
8178        settle_in(
8179            &mut t,
8180            unstarted_verdict(RunStatus::AlreadyInBase),
8181            "already in main",
8182            1,
8183            phrases("en"),
8184        );
8185        assert_eq!(t.status, TaskStatus::Done);
8186        assert_eq!(t.attempts, 0);
8187    }
8188
8189    #[test]
8190    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
8191        let reason = |language: &str| {
8192            let mut t = task();
8193            settle_in(
8194                &mut t,
8195                unstarted_verdict(RunStatus::Judging),
8196                "boom",
8197                1,
8198                phrases(language),
8199            );
8200            t.last_error.or(t.hold_reason).unwrap_or_default()
8201        };
8202        assert!(
8203            reason("en").starts_with("the graph stopped at `"),
8204            "{}",
8205            reason("en")
8206        );
8207        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
8208        assert!(reason("日本語").contains("boom"));
8209        assert_eq!(reason("fr"), reason("en"));
8210    }
8211
8212    #[test]
8213    fn describe_follows_the_run_language_and_keeps_the_run_id() {
8214        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
8215        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
8216        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
8217        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
8218        assert!(ja.contains("[run "), "{ja}");
8219        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
8220        assert!(ended.starts_with("run 終了: "), "{ended}");
8221        let mut de = run_state_in(RunStatus::Failed, "de");
8222        let mut en = run_state_in(RunStatus::Failed, "en");
8223        de.id = "same".to_owned();
8224        en.id = "same".to_owned();
8225        assert_eq!(describe(&de), describe(&en));
8226    }
8227
8228    #[test]
8229    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
8230        use crate::handover::Refused;
8231        let cases = [
8232            Refused::Foreign {
8233                branch: "b".into(),
8234                path: "/w/x".into(),
8235                why: "made by hand".into(),
8236            },
8237            Refused::Unsafe {
8238                branch: "b".into(),
8239                path: "/w/x".into(),
8240                why: "its worktree has uncommitted changes (a.rs)".into(),
8241            },
8242            Refused::ReleaseFailed {
8243                branch: "b".into(),
8244                path: "/w/x".into(),
8245                run: "ab12".into(),
8246            },
8247        ];
8248        for r in &cases {
8249            let en = (phrases("en").handover_refused)(r);
8250            assert_eq!(en, r.to_string());
8251            let ja = (phrases("ja").handover_refused)(r);
8252            assert!(
8253                !ja.contains("is checked out") && !ja.contains("try again"),
8254                "{ja}"
8255            );
8256            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
8257            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
8258                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
8259            }
8260        }
8261        assert!(phrases("en").handover_hint.contains("release the task"));
8262        assert!(phrases("ja").handover_hint.contains("解放"));
8263    }
8264
8265    #[test]
8266    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
8267        let build = |lang: &str| {
8268            let mut s = run_state_in(RunStatus::Blocked, lang);
8269            s.id = "same".to_owned();
8270            s.config.graph.review_rounds = 3;
8271            let mut r = review_round(3);
8272            r.expected = 3;
8273            r.answered = 1;
8274            s.reviews.push(r);
8275            s.event(
8276                "review",
8277                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
8278            );
8279            s
8280        };
8281        let en = describe(&build("en"));
8282        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
8283        let ja = describe(&build("ja"));
8284        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
8285        assert!(!ja.contains("never answered"), "{ja}");
8286        assert!(ja.contains("[run "), "{ja}");
8287
8288        // An incomplete panel whose verification failed is a different stop:
8289        // the real event must survive in ja too.
8290        let mut failed = build("ja");
8291        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
8292            command: "cargo test".to_owned(),
8293            code: Some(1),
8294            output_tail: String::new(),
8295            duration_ms: 0,
8296            resource_blocked: false,
8297        });
8298        failed.event("review", "stopped; e2e failed: cargo test");
8299        let ja = describe(&failed);
8300        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
8301        assert!(!ja.contains("席のレビュアー"), "{ja}");
8302    }
8303
8304    #[test]
8305    fn refusals_and_recovery_prose_follow_the_language() {
8306        let t = held_task_with("r1");
8307        let q = action_question(
8308            "r1",
8309            ask::ChoiceAction::Resume {
8310                run: "r1".to_owned(),
8311            },
8312        );
8313        let refuse = |p: &Phrases| match decide_action(&t, &q, p, |_: &str| bail!("gone")) {
8314            ActionDecision::Refuse(s) => s,
8315            other => panic!("{other:?}"),
8316        };
8317        assert!(refuse(phrases("en")).contains("could not be read: gone"));
8318        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
8319        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
8320
8321        let mut held = task();
8322        reclaim(&mut held, None, 2, "ja");
8323        assert!(held.hold_reason.unwrap().contains("保留にしました"));
8324        let mut held = task();
8325        reclaim(&mut held, None, 2, "xx");
8326        assert!(held.hold_reason.unwrap().contains("held for a human"));
8327    }
8328
8329    fn run_state(status: RunStatus) -> RunState {
8330        let mut state = RunState::new(
8331            PathBuf::from("/repo"),
8332            "main".to_owned(),
8333            "abc1234def".to_owned(),
8334            "add retries".to_owned(),
8335            Config::default(),
8336        );
8337        state.status = status;
8338        state
8339    }
8340
8341    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
8342        Candidate {
8343            index: 0,
8344            label,
8345            agent: "claude".to_owned(),
8346            branch: format!("magi/x/{label}"),
8347            worktree: PathBuf::from("/repo"),
8348            summary: summary.to_owned(),
8349            stat: String::new(),
8350            files: 0,
8351            commits: usize::from(!empty),
8352            empty,
8353            failed: failed.map(str::to_owned),
8354            verified_noop: None,
8355            duration_ms: 0,
8356            folded: false,
8357        }
8358    }
8359
8360    #[test]
8361    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
8362        let mut state = run_state(RunStatus::Blocked);
8363        state.gate = vec![
8364            CommandOutcome {
8365                command: "cargo make check".to_owned(),
8366                code: Some(0),
8367                output_tail: "ok".to_owned(),
8368                duration_ms: 0,
8369                resource_blocked: false,
8370            },
8371            CommandOutcome {
8372                command: "cargo test".to_owned(),
8373                code: Some(101),
8374                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
8375                duration_ms: 0,
8376                resource_blocked: false,
8377            },
8378        ];
8379        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
8380        assert!(d.contains("cargo test"), "{d}");
8381        assert!(
8382            !d.contains("cargo make check"),
8383            "a passing check is not a diagnostic: {d}"
8384        );
8385        assert!(d.contains("assertion failed"), "{d}");
8386    }
8387
8388    #[test]
8389    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
8390        let mut state = run_state(RunStatus::Blocked);
8391        state.event(
8392            "land",
8393            "stopped: the fixer produced no commit while 2 check(s) were failing \
8394             (build, lint); stopping instead of looping on an unchanged tree",
8395        );
8396        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
8397        assert!(d.contains("build"), "{d}");
8398        assert!(d.contains("lint"), "{d}");
8399        assert!(d.contains("fixer produced no commit"), "{d}");
8400    }
8401
8402    #[test]
8403    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
8404        // `describe`'s output becomes `Task::last_error` verbatim, and the
8405        // phone renders that in the same alarm-styled box an ordinary
8406        // failure gets. A bare `verified_noop` there would read exactly like
8407        // the failure this status exists to be told apart from.
8408        let state = run_state(RunStatus::VerifiedNoop);
8409        let d = describe(&state);
8410        assert!(
8411            d.contains("agent-verified no-op"),
8412            "expected the display label, not the wire spelling: {d}"
8413        );
8414        assert!(!d.contains("verified_noop"), "{d}");
8415    }
8416
8417    #[test]
8418    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
8419        // The whole point of the feature: a run held as "no candidate produced
8420        // a change" can mean the implementer actually finished the task and
8421        // only left a clean local tree behind - see AGENTS.md on this exact
8422        // failure mode. The diagnostic has to carry what the agent actually
8423        // said, not just the fact that nothing was there to judge.
8424        let mut state = run_state(RunStatus::Failed);
8425        state.candidates = vec![candidate(
8426            'A',
8427            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
8428            true,
8429            None,
8430        )];
8431        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
8432        assert!(d.contains("candidate A"), "{d}");
8433        assert!(d.contains("tagged v1.2.3"), "{d}");
8434    }
8435
8436    #[test]
8437    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
8438        let mut state = run_state(RunStatus::Failed);
8439        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
8440        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
8441        assert!(d.contains("candidate A"), "{d}");
8442        assert!(d.contains("agent timed out"), "{d}");
8443    }
8444
8445    #[test]
8446    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
8447        // A viable candidate existed, the gate never ran, and nothing land
8448        // said matches - `Task::last_error` is left to explain this one alone.
8449        let mut state = run_state(RunStatus::Failed);
8450        state.candidates = vec![candidate('A', "did the work", false, None)];
8451        assert!(diagnostic(&state).is_none());
8452    }
8453
8454    #[test]
8455    fn diagnostic_is_bounded_however_much_a_run_printed() {
8456        let mut state = run_state(RunStatus::Blocked);
8457        state.gate = vec![
8458            CommandOutcome {
8459                command: "cargo test".to_owned(),
8460                code: Some(101),
8461                output_tail: "x".repeat(50_000),
8462                duration_ms: 0,
8463                resource_blocked: false,
8464            },
8465            CommandOutcome {
8466                command: "cargo clippy".to_owned(),
8467                code: Some(1),
8468                output_tail: "y".repeat(50_000),
8469                duration_ms: 0,
8470                resource_blocked: false,
8471            },
8472        ];
8473        state.candidates = vec![
8474            candidate('A', &"z".repeat(50_000), true, None),
8475            candidate('B', &"w".repeat(50_000), true, None),
8476        ];
8477        let d = diagnostic(&state).expect("plenty here to diagnose");
8478        assert!(
8479            d.len() <= DIAGNOSTIC_MAX,
8480            "diagnostic grew to {} bytes, unbounded",
8481            d.len()
8482        );
8483    }
8484
8485    #[test]
8486    fn selected_delivery_guards_survive_recovery_failure_accounting() {
8487        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
8488            let mut t = task();
8489            let mut state = run_state(status);
8490            t.pr_recovery = Some(crate::pr_recovery::Selection {
8491                url: "url".into(),
8492                branch: format!("magi/task-{}", t.id),
8493                head: "a".repeat(40),
8494                source_head: None,
8495                source_run: None,
8496                source_proof: None,
8497                disposition: Some(crate::pr_recovery::Disposition::Land),
8498                instruction: t.instruction.clone(),
8499                approved_at: Timestamp::now(),
8500            });
8501            state.pr_recovery = t.pr_recovery.clone();
8502            t.start(state.id.clone());
8503            settle_and_diagnose(
8504                &mut t,
8505                Verdict {
8506                    status,
8507                    left_pr: false,
8508                    quota_hit: false,
8509                    parked: false,
8510                    no_viable_candidates: false,
8511                },
8512                "delivery stopped",
8513                5,
8514                &state,
8515            );
8516            assert_eq!(t.status, TaskStatus::Held);
8517            let reason = t.hold_reason.as_deref().unwrap();
8518            if status == RunStatus::Ready {
8519                assert!(reason.contains("Selected PR delivery is incomplete"));
8520                assert!(t.recovery_budget.is_none());
8521            } else {
8522                assert!(reason.contains("Selected recovery stopped"));
8523                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
8524            }
8525            assert!(t.pr_recovery.is_some());
8526        }
8527    }
8528
8529    #[test]
8530    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
8531        let mut state = run_state(RunStatus::Blocked);
8532        state.gate = vec![CommandOutcome {
8533            command: "cargo test".to_owned(),
8534            code: Some(101),
8535            output_tail: "assertion failed".to_owned(),
8536            duration_ms: 0,
8537            resource_blocked: false,
8538        }];
8539        let verdict = Verdict {
8540            status: RunStatus::Blocked,
8541            left_pr: false,
8542            quota_hit: false,
8543            parked: false,
8544            no_viable_candidates: false,
8545        };
8546
8547        // Attempt one of two still has a retry coming: no diagnostic yet, the
8548        // task is going to run again and this run's evidence would go stale.
8549        let mut t = task();
8550        t.start("run-1".to_owned());
8551        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8552        assert_eq!(t.status, TaskStatus::Failed);
8553        assert!(t.diagnostic.is_none());
8554
8555        // Attempt two exhausts the budget: now it is held, and the
8556        // diagnostic is what `magi task show` has to say more than one line.
8557        t.start("run-2".to_owned());
8558        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
8559        assert_eq!(t.status, TaskStatus::Held);
8560        let d = t.diagnostic.expect("a held task must carry its diagnostic");
8561        assert!(d.contains("cargo test"), "{d}");
8562    }
8563
8564    #[test]
8565    fn a_held_task_names_the_open_question_it_is_waiting_on() {
8566        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
8567        // `magi ask` question settled Held with `hold_reason: null`, so the
8568        // notification said nothing actionable. `note_open_question` should
8569        // append the question id to whatever `handed_off` already wrote.
8570        crate::run::pin_test_home();
8571        let home = crate::run::home();
8572        let state = run_state(RunStatus::VerifiedNoop);
8573        let mut q = ask::Question::new(
8574            state.id.clone(),
8575            "implement".to_owned(),
8576            "impl-A".to_owned(),
8577            "is this really a no-op?".to_owned(),
8578            String::new(),
8579            Vec::new(),
8580        );
8581        Questions::at(home.join("questions")).put(&mut q).unwrap();
8582
8583        let verdict = Verdict {
8584            status: RunStatus::VerifiedNoop,
8585            left_pr: false,
8586            quota_hit: false,
8587            parked: false,
8588            no_viable_candidates: false,
8589        };
8590        let mut t = task();
8591        t.start(state.id.clone());
8592        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8593
8594        assert_eq!(t.status, TaskStatus::Held);
8595        let reason = t.hold_reason.expect("a held task must record why");
8596        assert!(
8597            reason.starts_with("run ended agent-verified no-op"),
8598            "the original settle reason must survive unchanged: {reason}"
8599        );
8600        assert!(
8601            reason.contains(q.short()),
8602            "the open question's id must be named so the notice is actionable: {reason}"
8603        );
8604    }
8605
8606    #[test]
8607    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
8608        crate::run::pin_test_home();
8609        let state = run_state(RunStatus::VerifiedNoop);
8610
8611        let verdict = Verdict {
8612            status: RunStatus::VerifiedNoop,
8613            left_pr: false,
8614            quota_hit: false,
8615            parked: false,
8616            no_viable_candidates: false,
8617        };
8618        let mut t = task();
8619        t.start(state.id.clone());
8620        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
8621
8622        assert_eq!(t.status, TaskStatus::Held);
8623        assert_eq!(
8624            t.hold_reason.as_deref(),
8625            Some("run ended agent-verified no-op"),
8626            "nothing to append when the question was already answered or never asked"
8627        );
8628    }
8629
8630    #[test]
8631    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
8632        crate::run::pin_test_home();
8633        let mut first = run_state(RunStatus::Blocked);
8634        first.id = "20260101-000000-sup1".to_owned();
8635        first.save().unwrap();
8636        let mut second = run_state(RunStatus::Merged);
8637        second.id = "20260101-000000-sup2".to_owned();
8638        second.save().unwrap();
8639
8640        let mut t = task();
8641        t.runs = vec![first.id.clone(), second.id.clone()];
8642        t.status = TaskStatus::Done;
8643
8644        supersede_prior_runs(&t, &crate::run::home());
8645
8646        assert_eq!(
8647            RunState::load(&first.id).unwrap().status,
8648            RunStatus::Superseded,
8649            "the first attempt's Blocked no longer needs anyone's attention"
8650        );
8651        assert_eq!(
8652            RunState::load(&second.id).unwrap().status,
8653            RunStatus::Merged,
8654            "the run that actually succeeded is left exactly as it was"
8655        );
8656    }
8657
8658    #[test]
8659    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
8660        // `is_working_on` alone only proves a *daemon* claim; a `magi run
8661        // --resume` invoked by hand outside the daemon never touches
8662        // `daemon.json` at all, so it would look identical to a genuinely
8663        // idle run without also consulting `RunState::liveness`, which reads
8664        // this run's own recorded `driver_pid` instead.
8665        crate::run::pin_test_home();
8666        let mut first = run_state(RunStatus::Blocked);
8667        first.id = "20260101-000000-sup9".to_owned();
8668        // This test process's own pid: guaranteed alive without needing a
8669        // real second process or daemon.
8670        first.driver_pid = Some(std::process::id());
8671        first.driver_started_at = Some(
8672            crate::proc::process_started_at(std::process::id())
8673                .expect("this test process's own start time must be queryable"),
8674        );
8675        first.save().unwrap();
8676        let mut second = run_state(RunStatus::Merged);
8677        second.id = "20260101-000000-supa".to_owned();
8678        second.save().unwrap();
8679
8680        let mut t = task();
8681        t.runs = vec![first.id.clone(), second.id.clone()];
8682        t.status = TaskStatus::Done;
8683
8684        supersede_prior_runs(&t, &crate::run::home());
8685
8686        assert_eq!(
8687            RunState::load(&first.id).unwrap().status,
8688            RunStatus::Blocked,
8689            "a live driver_pid means something is still actually working this run, \
8690             even though no daemon claims it - rewriting under it would just be \
8691             undone the next time that process saves"
8692        );
8693    }
8694
8695    #[test]
8696    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
8697        // The first resweep must skip a still-live attempt exactly like
8698        // `supersede_prior_runs` itself does; a later resweep, once that
8699        // process is no longer actually driving it, is what closes the gap
8700        // `supersede_prior_runs` alone leaves - a task only ever reaches
8701        // `Done` once, so nothing else would ever look at this run again.
8702        let dir = tempfile::tempdir().unwrap();
8703        let home = dir.path().to_path_buf();
8704        let queue = Queue::at(dir.path().join("queue"));
8705
8706        let mut first = run_state(RunStatus::Blocked);
8707        first.id = "20260101-000000-supd".to_owned();
8708        first.driver_pid = Some(std::process::id());
8709        first.driver_started_at = Some(
8710            crate::proc::process_started_at(std::process::id())
8711                .expect("this test process's own start time must be queryable"),
8712        );
8713        first.save_under(&home).unwrap();
8714        let mut second = run_state(RunStatus::Merged);
8715        second.id = "20260101-000000-supe".to_owned();
8716        second.save_under(&home).unwrap();
8717
8718        let mut t = task();
8719        t.runs = vec![first.id.clone(), second.id.clone()];
8720        t.status = TaskStatus::Done;
8721        queue.put(&mut t).unwrap();
8722
8723        resweep_superseded_attempts(&queue, &home);
8724        assert_eq!(
8725            RunState::load_under(&first.id, &home).unwrap().status,
8726            RunStatus::Blocked,
8727            "still live on the first pass, so still untouched"
8728        );
8729
8730        // Stand in for the manual process no longer being the one driving
8731        // this run: same pid (this test process really is still alive), but
8732        // an identity marker that no longer matches it - see
8733        // `RunState::liveness`'s own doc for why a mismatched
8734        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
8735        let mut stale = RunState::load_under(&first.id, &home).unwrap();
8736        stale.driver_started_at = Some("1".to_owned());
8737        stale.save_under(&home).unwrap();
8738
8739        resweep_superseded_attempts(&queue, &home);
8740        assert_eq!(
8741            RunState::load_under(&first.id, &home).unwrap().status,
8742            RunStatus::Superseded,
8743            "the second pass catches up what the first one correctly skipped"
8744        );
8745    }
8746
8747    #[test]
8748    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
8749        crate::run::pin_test_home();
8750        let mut first = run_state(RunStatus::Blocked);
8751        first.id = "20260101-000000-sup3".to_owned();
8752        first.save().unwrap();
8753        let mut second = run_state(RunStatus::Blocked);
8754        second.id = "20260101-000000-sup4".to_owned();
8755        second.save().unwrap();
8756
8757        let mut t = task();
8758        t.runs = vec![first.id.clone(), second.id.clone()];
8759        // Still retrying: nothing about this task's story is settled yet, so
8760        // neither Blocked run may be relabelled, even though a later attempt
8761        // already exists.
8762        t.status = TaskStatus::Failed;
8763
8764        supersede_prior_runs(&t, &crate::run::home());
8765
8766        assert_eq!(
8767            RunState::load(&first.id).unwrap().status,
8768            RunStatus::Blocked
8769        );
8770        assert_eq!(
8771            RunState::load(&second.id).unwrap().status,
8772            RunStatus::Blocked
8773        );
8774    }
8775
8776    #[test]
8777    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
8778        // `magi task done` (or the API's equivalent) can close a task with no
8779        // run of its own ever having succeeded - there is nothing here that
8780        // counts as "the attempt that finished it", so nothing is rewritten.
8781        crate::run::pin_test_home();
8782        let mut first = run_state(RunStatus::Blocked);
8783        first.id = "20260101-000000-sup5".to_owned();
8784        first.save().unwrap();
8785
8786        let mut t = task();
8787        t.runs = vec![first.id.clone()];
8788        t.status = TaskStatus::Done;
8789
8790        supersede_prior_runs(&t, &crate::run::home());
8791
8792        assert_eq!(
8793            RunState::load(&first.id).unwrap().status,
8794            RunStatus::Blocked,
8795            "a single-attempt task has no earlier run to supersede"
8796        );
8797    }
8798
8799    #[test]
8800    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
8801        // `magi task done` (or the web/conductor equivalents) can close a
8802        // task in any status, including one whose *last* recorded attempt is
8803        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
8804        // never watched, say. `runs.last()` being `Done`-adjacent is not
8805        // proof it actually succeeded, so nothing earlier may be relabelled
8806        // on its say-so alone.
8807        crate::run::pin_test_home();
8808        let mut first = run_state(RunStatus::Blocked);
8809        first.id = "20260101-000000-supb".to_owned();
8810        first.save().unwrap();
8811        let mut second = run_state(RunStatus::Failed);
8812        second.id = "20260101-000000-supc".to_owned();
8813        second.save().unwrap();
8814
8815        let mut t = task();
8816        t.runs = vec![first.id.clone(), second.id.clone()];
8817        t.status = TaskStatus::Done;
8818
8819        supersede_prior_runs(&t, &crate::run::home());
8820
8821        assert_eq!(
8822            RunState::load(&first.id).unwrap().status,
8823            RunStatus::Blocked,
8824            "the task's last attempt never landed, so there is nothing here \
8825             actually superseding it"
8826        );
8827    }
8828
8829    #[test]
8830    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
8831        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
8832        // to look" - `Failed` and `VerifiedNoop` are already their own
8833        // terminal answers and must not be relabelled into a third one.
8834        crate::run::pin_test_home();
8835        let mut failed = run_state(RunStatus::Failed);
8836        failed.id = "20260101-000000-sup6".to_owned();
8837        failed.save().unwrap();
8838        let mut noop = run_state(RunStatus::VerifiedNoop);
8839        noop.id = "20260101-000000-sup7".to_owned();
8840        noop.save().unwrap();
8841        let mut winner = run_state(RunStatus::Ready);
8842        winner.id = "20260101-000000-sup8".to_owned();
8843        winner.save().unwrap();
8844
8845        let mut t = task();
8846        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
8847        t.status = TaskStatus::Done;
8848
8849        supersede_prior_runs(&t, &crate::run::home());
8850
8851        assert_eq!(
8852            RunState::load(&failed.id).unwrap().status,
8853            RunStatus::Failed
8854        );
8855        assert_eq!(
8856            RunState::load(&noop.id).unwrap().status,
8857            RunStatus::VerifiedNoop
8858        );
8859    }
8860
8861    fn approval_question(run: &str) -> ask::Question {
8862        ask::Question::new(
8863            run.to_owned(),
8864            land::APPROVAL_NODE.to_owned(),
8865            "land".to_owned(),
8866            "merge?".to_owned(),
8867            String::new(),
8868            vec!["merge".to_owned(), "hold".to_owned()],
8869        )
8870    }
8871
8872    #[test]
8873    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
8874        crate::run::pin_test_home();
8875        let mut state = run_state(RunStatus::Landing);
8876        state.id = "20260101-000000-fre1".to_owned();
8877        state.parked = true;
8878        state.save().unwrap();
8879        ask::Questions::open()
8880            .put(&mut approval_question(&state.id))
8881            .unwrap();
8882
8883        let mut t = task();
8884        t.runs.push(state.id.clone());
8885        assert_eq!(
8886            land_resume_state(&t),
8887            LandResume::StillWaiting,
8888            "nobody has answered and the timeout has not passed"
8889        );
8890    }
8891
8892    #[test]
8893    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
8894        crate::run::pin_test_home();
8895        let mut state = run_state(RunStatus::Gating);
8896        state.id = "20260101-000000-gt01".to_owned();
8897        state.parked = true;
8898        state.config.graph.answer_timeout = 60;
8899        state.github_text = Some(crate::run::GithubTextAsk {
8900            rewrite: None,
8901            fingerprint: "f".into(),
8902            title: true,
8903            body: false,
8904            categories: vec!["title-language".into()],
8905            question: None,
8906            asks: 1,
8907            resolved: false,
8908            chosen_title: None,
8909            choice: None,
8910        });
8911        state.save().unwrap();
8912        let store = ask::Questions::open();
8913        let mut q = ask::Question::new(
8914            state.id.clone(),
8915            crate::github_text::ASK_NODE.to_owned(),
8916            crate::github_text::ASK_SEAT.to_owned(),
8917            "s".into(),
8918            String::new(),
8919            vec!["use fallback".into()],
8920        );
8921        store.put(&mut q).unwrap();
8922        let mut t = task();
8923        t.runs.push(state.id.clone());
8924        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
8925        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
8926        store.put(&mut q).unwrap();
8927        assert_eq!(land_resume_state(&t), LandResume::Ready);
8928        assert!(!store.get(&q.id).unwrap().status.open());
8929        // Once decided, a parked run is an ordinary candidate again.
8930        state.github_text.as_mut().unwrap().resolved = true;
8931        state.save().unwrap();
8932        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
8933    }
8934
8935    #[test]
8936    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
8937        // `ask::ask_and_wait`'s own deadline used to retire a question
8938        // nobody answered; land's approval bypasses that wait (see
8939        // `land::approval_gate`), so this is now the only place
8940        // `graph.answer_timeout` is enforced for a land approval at all.
8941        crate::run::pin_test_home();
8942        let mut state = run_state(RunStatus::Landing);
8943        state.id = "20260101-000000-exp1".to_owned();
8944        state.parked = true;
8945        state.config.graph.answer_timeout = 60;
8946        state.save().unwrap();
8947
8948        let store = ask::Questions::open();
8949        let mut q = approval_question(&state.id);
8950        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
8951        store.put(&mut q).unwrap();
8952
8953        let mut t = task();
8954        t.runs.push(state.id.clone());
8955        assert_eq!(
8956            land_resume_state(&t),
8957            LandResume::Ready,
8958            "an expired question must not be waited on forever"
8959        );
8960
8961        let after = store.get(&q.id).unwrap();
8962        assert!(
8963            !after.status.open(),
8964            "the question is abandoned, not silently ignored"
8965        );
8966        assert!(
8967            after.resolution().is_none(),
8968            "an abandoned question is not read as a decision"
8969        );
8970    }
8971
8972    #[test]
8973    fn reclaim_settles_a_running_task_against_its_last_run() {
8974        let mut t = task();
8975        t.start("20260904-000000-4043".to_owned());
8976        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
8977        assert_eq!(
8978            t.status,
8979            TaskStatus::Done,
8980            "a run that actually finished must not stay `running` forever"
8981        );
8982    }
8983
8984    #[test]
8985    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
8986        let mut t = task();
8987        t.start("20260904-000000-4043".to_owned());
8988        t.last_error = Some("earlier trouble".to_owned());
8989        let mut state = run_state(RunStatus::Judging);
8990        state.parked = true;
8991        reclaim(&mut t, Some(state), 1, "en");
8992        assert_eq!(t.status, TaskStatus::Parked);
8993        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
8994        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
8995        assert!(t.park_reason.is_some());
8996        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
8997        assert!(!t.fresh_start);
8998        assert!(t.status.runnable());
8999    }
9000
9001    #[test]
9002    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
9003        let mut t = task();
9004        t.start("20260904-000000-4043".to_owned());
9005        t.last_error = Some("earlier trouble".to_owned());
9006        settle(
9007            &mut t,
9008            Verdict {
9009                status: RunStatus::Judging,
9010                left_pr: false,
9011                quota_hit: false,
9012                parked: true,
9013                no_viable_candidates: false,
9014            },
9015            "parked after `judging`",
9016            1,
9017        );
9018        assert_eq!(t.status, TaskStatus::Parked);
9019        assert_eq!(t.attempts, 0);
9020        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
9021        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
9022        assert_eq!(t.schema, crate::queue::SCHEMA);
9023        assert!(
9024            crate::notices::task_held(&t).is_none(),
9025            "a park is not news"
9026        );
9027        t.start("20260904-000000-4043".to_owned());
9028        assert_eq!(t.park_reason, None);
9029    }
9030
9031    #[test]
9032    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
9033        // A blocked run with attempts left goes back to `Failed`, exactly as
9034        // it would from `attempt` itself - `reclaim` must not invent a second
9035        // policy for a task a daemon merely stopped without reporting.
9036        let mut t = task();
9037        t.start("20260904-000000-4043".to_owned());
9038        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
9039        assert_eq!(t.status, TaskStatus::Failed);
9040        assert!(t.status.runnable());
9041    }
9042
9043    #[test]
9044    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
9045        let mut t = task();
9046        t.start("20260904-000000-4043".to_owned());
9047        assert_eq!(t.attempts, 1);
9048        let mut run = run_state(RunStatus::Implementing);
9049        run.id = "20260904-000000-4043".to_owned();
9050        run.begin_pass();
9051        let cause = crate::run::ParkCause::Upgrade {
9052            from: "0.121.0".to_owned(),
9053            to: Some("0.121.1".to_owned()),
9054        };
9055        run.end_pass_parked(cause.clone());
9056        run.parked = true;
9057        let verdict = Verdict {
9058            status: run.status,
9059            left_pr: false,
9060            quota_hit: false,
9061            parked: true,
9062            no_viable_candidates: false,
9063        };
9064        // A crash after the checkpoint but before queue settlement must
9065        // recover exactly the same scheduling evidence and refund.
9066        let mut orphan = t.clone();
9067        reclaim(&mut orphan, Some(run.clone()), 2, "en");
9068        assert_eq!(orphan.status, TaskStatus::Parked);
9069        assert_eq!(orphan.attempts, 0);
9070        assert_eq!(
9071            orphan.upgrade_resume_key(),
9072            Some((run.passes[0].started_at, orphan.id.as_str()))
9073        );
9074        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
9075        assert_eq!(t.attempts, 0);
9076        assert_eq!(t.passes.len(), 1);
9077        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9078        assert_eq!(t.passes[0].parked, Some(cause));
9079        assert_eq!(t.passes[0].pass_index, 0);
9080        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
9081        assert!(t.upgrade_resume_key().is_some());
9082
9083        // A resumed pass that then fails spends its attempt, and the earlier
9084        // pass's entry is untouched.
9085        t.start("20260904-000000-4043".to_owned());
9086        run.begin_pass();
9087        run.status = RunStatus::Failed;
9088        let verdict = Verdict {
9089            status: RunStatus::Failed,
9090            left_pr: false,
9091            quota_hit: false,
9092            parked: false,
9093            no_viable_candidates: false,
9094        };
9095        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
9096        assert_eq!(t.passes.len(), 2);
9097        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9098        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
9099        assert_eq!(t.passes[1].pass_index, 1);
9100        assert_eq!(t.attempts, 1);
9101    }
9102
9103    #[test]
9104    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
9105        let mut t = task();
9106        t.start("20260904-000000-4043".to_owned());
9107        reclaim(&mut t, None, 2, "en");
9108        assert_eq!(t.status, TaskStatus::Held);
9109        assert!(
9110            t.last_error
9111                .as_deref()
9112                .is_some_and(|e| e.contains("running")),
9113            "the operator needs to know why this task was held"
9114        );
9115    }
9116
9117    #[test]
9118    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
9119        let dir = tempfile::tempdir().unwrap();
9120        let queue = Queue::at(dir.path().to_path_buf());
9121
9122        // No run recorded, so this never has to touch `RunState::load`.
9123        let mut orphaned = task();
9124        orphaned.id = "20260904-000000-orph".to_owned();
9125        orphaned.status = TaskStatus::Running;
9126        orphaned.attempts = 1;
9127        queue.put(&mut orphaned).unwrap();
9128
9129        let mut alive = task();
9130        alive.id = "20260904-000000-live".to_owned();
9131        alive.status = TaskStatus::Running;
9132        alive.attempts = 1;
9133        queue.put(&mut alive).unwrap();
9134        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
9135
9136        let mut queued = task();
9137        queued.id = "20260904-000000-wait".to_owned();
9138        queue.put(&mut queued).unwrap();
9139
9140        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9141        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
9142
9143        assert_eq!(
9144            queue.get(&orphaned.id).unwrap().status,
9145            TaskStatus::Held,
9146            "nothing was driving it and there was no run to recover"
9147        );
9148        assert_eq!(
9149            queue.get(&alive.id).unwrap().status,
9150            TaskStatus::Running,
9151            "a live claim must protect the task it belongs to"
9152        );
9153        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
9154    }
9155
9156    /// Read a run.json back from an explicit `home`, the same way
9157    /// `reclaim_abandoned_runs` itself does - never through the
9158    /// process-global `RunState::load`, which this test's own `home` (an
9159    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
9160    /// use at all.
9161    fn read_run_under(home: &Path, id: &str) -> RunState {
9162        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
9163        serde_json::from_str(&body).unwrap()
9164    }
9165
9166    #[test]
9167    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
9168        let dir = tempfile::tempdir().unwrap();
9169        let home = dir.path().to_path_buf();
9170        let now = Timestamp::now();
9171        let overrun_seat = || crate::run::ActiveSeat {
9172            node: "implement".to_owned(),
9173            started_at: now - jiff::SignedDuration::new(21_000, 0),
9174            timeout_secs: 3_600,
9175            attempt: 0,
9176            task: None,
9177            command: None,
9178            index: None,
9179            total: None,
9180        };
9181
9182        let mut dead = run_state(RunStatus::Implementing);
9183        dead.id = "20260101-000000-dead".to_owned();
9184        dead.active.insert("impl-A".to_owned(), overrun_seat());
9185        // A `driver_pid` the injected query below confirms gone outright —
9186        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
9187        dead.driver_pid = Some(4242);
9188        dead.save_under(&home).unwrap();
9189
9190        // Same shape, but a live daemon's heartbeat names it: must be left
9191        // exactly alone, however far past its own timeout the seat sits.
9192        let mut alive = run_state(RunStatus::Implementing);
9193        alive.id = "20260101-000000-aliv".to_owned();
9194        alive.active.insert("impl-A".to_owned(), overrun_seat());
9195        alive.save_under(&home).unwrap();
9196        let mut status = Status::new();
9197        status.current = vec![Current {
9198            worker: None,
9199            task: "20260101-000000-task".to_owned(),
9200            run: alive.id.clone(),
9201        }];
9202        write_status_to(&home.join("daemon.json"), &status).unwrap();
9203
9204        // The abandoned seat left an open question behind: nobody is left to
9205        // read an answer once the run is failed, and this must not wait for
9206        // some later daemon startup's own sweep to notice that.
9207        let questions = Questions::at(home.join("questions"));
9208        let mut q = ask::Question::new(
9209            dead.id.clone(),
9210            "implement".to_owned(),
9211            "impl-A".to_owned(),
9212            "Which storage backend?".to_owned(),
9213            String::new(),
9214            vec!["SQLite".to_owned(), "Redis".to_owned()],
9215        );
9216        questions.put(&mut q).unwrap();
9217
9218        let abandoned = reclaim_abandoned_runs_with(
9219            &home,
9220            now,
9221            |pid| if pid == 4242 { Some(false) } else { None },
9222            |_| panic!("a query answering Dead outright needs no identity corroboration"),
9223        );
9224        assert_eq!(abandoned, vec![dead.id.clone()]);
9225
9226        let reloaded = read_run_under(&home, &dead.id);
9227        assert_eq!(reloaded.status, RunStatus::Failed);
9228        assert!(reloaded.active.is_empty());
9229        assert!(
9230            !questions.get(&q.id).unwrap().status.open(),
9231            "the failed run's own open question must be settled in the same pass"
9232        );
9233
9234        let still_alive = read_run_under(&home, &alive.id);
9235        assert_eq!(
9236            still_alive.status,
9237            RunStatus::Implementing,
9238            "a live daemon's claim protects it"
9239        );
9240        assert!(!still_alive.active.is_empty());
9241    }
9242
9243    /// The exact shape a review round flagged as broken: `magi serve` running
9244    /// in this same `home` scans *every* run on disk, including a manual
9245    /// `magi review` / `magi run` this daemon never started and that
9246    /// therefore claims no heartbeat of its own. Before this scan asked
9247    /// `liveness` rather than just `is_working_on`, a manual run whose active
9248    /// seat merely ran a little past its own timeout — the CLI finishing up,
9249    /// its result still being collected — got wiped and failed by a daemon
9250    /// that had nothing to do with it, out from under a process that was
9251    /// still very much running.
9252    #[test]
9253    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
9254        let dir = tempfile::tempdir().unwrap();
9255        let home = dir.path().to_path_buf();
9256        let now = Timestamp::now();
9257
9258        let mut manual = run_state(RunStatus::Reviewing);
9259        manual.id = "20260101-000000-manl".to_owned();
9260        manual.active.insert(
9261            "review-1".to_owned(),
9262            crate::run::ActiveSeat {
9263                node: "review".to_owned(),
9264                started_at: now - jiff::SignedDuration::new(21_000, 0),
9265                timeout_secs: 3_600,
9266                attempt: 0,
9267                task: None,
9268                command: None,
9269                index: None,
9270                total: None,
9271            },
9272        );
9273        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
9274        // but a real, still-running process: `liveness` must corroborate this
9275        // as `Live`, not read the missing daemon claim as death.
9276        manual.driver_pid = Some(4242);
9277        manual.driver_started_at = Some("1790000000".to_owned());
9278        manual.save_under(&home).unwrap();
9279
9280        let abandoned = reclaim_abandoned_runs_with(
9281            &home,
9282            now,
9283            |pid| if pid == 4242 { Some(true) } else { None },
9284            |pid| {
9285                if pid == 4242 {
9286                    Some("1790000000".to_owned())
9287                } else {
9288                    None
9289                }
9290            },
9291        );
9292        assert!(
9293            abandoned.is_empty(),
9294            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
9295        );
9296
9297        let reloaded = read_run_under(&home, &manual.id);
9298        assert_eq!(reloaded.status, RunStatus::Reviewing);
9299        assert!(!reloaded.active.is_empty());
9300    }
9301
9302    #[test]
9303    fn an_already_claimed_task_is_skipped_rather_than_failed() {
9304        let dir = tempfile::tempdir().unwrap();
9305        let queue = Queue::at(dir.path().to_path_buf());
9306        let mut only = task();
9307        queue.put(&mut only).unwrap();
9308
9309        let _elsewhere = queue.claim(&only.id).unwrap();
9310        let candidates = runnable(&queue);
9311        assert_eq!(candidates.len(), 1, "the task is still runnable");
9312        assert!(
9313            queue.claim(&candidates[0].id).is_err(),
9314            "the loop cannot take a claim somebody else holds"
9315        );
9316
9317        let after = queue.get(&only.id).unwrap();
9318        assert_eq!(after.status, TaskStatus::Queued);
9319        assert_eq!(
9320            after.attempts, 0,
9321            "losing the race is not an attempt at the task"
9322        );
9323        assert_eq!(after.last_error, None);
9324    }
9325
9326    #[test]
9327    fn the_status_file_round_trips_and_its_heartbeat_advances() {
9328        let dir = tempfile::tempdir().unwrap();
9329        let path = dir.path().join("daemon.json");
9330
9331        let mut status = Status::new();
9332        status.idle = false;
9333        status.completed = 7;
9334        status.current = vec![Current {
9335            worker: None,
9336            task: "20260902-000000-t111".to_owned(),
9337            run: "20260902-000001-r111".to_owned(),
9338        }];
9339        write_status_to(&path, &status).unwrap();
9340        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9341        assert_eq!(first.schema, SCHEMA);
9342        assert_eq!(first.pid, std::process::id());
9343        assert!(!first.idle);
9344        assert_eq!(first.completed, 7);
9345        assert_eq!(first.current, status.current);
9346        assert!(
9347            !path.with_extension("json.tmp").exists(),
9348            "the temp file is renamed, not left behind"
9349        );
9350
9351        std::thread::sleep(Duration::from_millis(5));
9352        status.updated_at = Timestamp::now();
9353        status.polls = 3;
9354        write_status_to(&path, &status).unwrap();
9355        let second: Status =
9356            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
9357        assert!(
9358            second.updated_at > first.updated_at,
9359            "a reader can only detect staleness if the heartbeat moves"
9360        );
9361        assert_eq!(
9362            second.started_at, first.started_at,
9363            "the start time is not a heartbeat"
9364        );
9365        assert_eq!(second.polls, 3);
9366    }
9367
9368    #[test]
9369    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
9370        let dir = tempfile::tempdir().unwrap();
9371
9372        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
9373
9374        let mut status = Status::new();
9375        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
9376        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9377        let stale = read_status(dir.path()).unwrap();
9378        assert!(
9379            !stale.running(Timestamp::now()),
9380            "a minute without a heartbeat is a dead daemon, not a busy one"
9381        );
9382        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
9383
9384        status.updated_at = Timestamp::now();
9385        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9386        let fresh = read_status(dir.path()).unwrap();
9387        assert!(fresh.running(Timestamp::now()));
9388    }
9389
9390    #[test]
9391    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
9392        let dir = tempfile::tempdir().unwrap();
9393        let now = Timestamp::now();
9394        let mine = "20260903-080619-01c2";
9395
9396        assert!(
9397            !is_working_on(dir.path(), mine, now),
9398            "no status file means nobody is working on anything"
9399        );
9400
9401        let mut status = Status::new();
9402        status.current = vec![Current {
9403            worker: None,
9404            task: "20260903-080340-0167".to_owned(),
9405            run: mine.to_owned(),
9406        }];
9407        status.updated_at = now;
9408        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9409        assert!(is_working_on(dir.path(), mine, now));
9410        assert!(
9411            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
9412            "a daemon busy with one run is not working on another"
9413        );
9414
9415        // A killed daemon stops writing heartbeats but leaves the file behind
9416        // naming the run it died in. That run must not be undeletable forever.
9417        status.updated_at = now - jiff::SignedDuration::from_secs(600);
9418        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9419        assert!(
9420            !is_working_on(dir.path(), mine, now),
9421            "a stale heartbeat is a dead daemon, so its run is a leftover"
9422        );
9423    }
9424
9425    #[test]
9426    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
9427        let dir = tempfile::tempdir().unwrap();
9428        let now = Timestamp::now();
9429
9430        assert!(
9431            !is_working_on_short(dir.path(), "01c2", now),
9432            "no status file means nobody is working on anything"
9433        );
9434
9435        let mut status = Status::new();
9436        status.current = vec![Current {
9437            worker: None,
9438            task: "20260903-080340-0167".to_owned(),
9439            run: "20260903-080619-01c2".to_owned(),
9440        }];
9441        status.updated_at = now;
9442        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
9443        assert!(
9444            is_working_on_short(dir.path(), "01c2", now),
9445            "the run's short id is the last block of its full id"
9446        );
9447        assert!(
9448            !is_working_on_short(dir.path(), "3cbf", now),
9449            "a daemon busy with one worktree bay is not working on another"
9450        );
9451    }
9452
9453    #[test]
9454    fn a_newer_status_file_still_yields_a_reading() {
9455        let dir = tempfile::tempdir().unwrap();
9456        // A field this build has never heard of must not turn the reading into
9457        // nothing at all; that is the whole reason the reader is permissive.
9458        std::fs::write(
9459            dir.path().join("daemon.json"),
9460            serde_json::json!({
9461                "schema": 2,
9462                "updated_at": Timestamp::now().to_string(),
9463                "idle": true,
9464                "surprise": { "nested": [1, 2, 3] },
9465            })
9466            .to_string(),
9467        )
9468        .unwrap();
9469
9470        let reading = read_status(dir.path()).expect("a forward-compatible read");
9471        assert!(reading.running(Timestamp::now()));
9472        assert!(reading.idle);
9473        assert!(reading.current.is_empty());
9474    }
9475
9476    #[test]
9477    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
9478        // A daemon started before `current` became a list keeps writing this
9479        // shape on every heartbeat until it is restarted. A rolling upgrade
9480        // - a newer `magi web` or `magi doctor` reading an older `magi
9481        // serve`'s heartbeat - must still see the run it is on, not "no
9482        // daemon" from a type mismatch failing the whole struct.
9483        let dir = tempfile::tempdir().unwrap();
9484        std::fs::write(
9485            dir.path().join("daemon.json"),
9486            serde_json::json!({
9487                "schema": 1,
9488                "pid": 4242,
9489                "updated_at": Timestamp::now().to_string(),
9490                "idle": false,
9491                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
9492                "completed": 3,
9493                "polls": 9,
9494            })
9495            .to_string(),
9496        )
9497        .unwrap();
9498
9499        let reading = read_status(dir.path()).expect("an older shape must still parse");
9500        assert!(reading.running(Timestamp::now()));
9501        assert_eq!(
9502            reading.current,
9503            vec![Current {
9504                worker: None,
9505                task: "20260902-140501-aaaa".to_owned(),
9506                run: "20260902-140502-bbbb".to_owned(),
9507            }]
9508        );
9509    }
9510
9511    #[test]
9512    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
9513        let dir = tempfile::tempdir().unwrap();
9514        std::fs::write(
9515            dir.path().join("daemon.json"),
9516            serde_json::json!({
9517                "schema": 1,
9518                "updated_at": Timestamp::now().to_string(),
9519                "idle": true,
9520                "current": null,
9521            })
9522            .to_string(),
9523        )
9524        .unwrap();
9525        let with_null = read_status(dir.path()).expect("null must still parse");
9526        assert!(with_null.current.is_empty());
9527
9528        std::fs::write(
9529            dir.path().join("daemon.json"),
9530            serde_json::json!({
9531                "schema": 1,
9532                "updated_at": Timestamp::now().to_string(),
9533                "idle": true,
9534            })
9535            .to_string(),
9536        )
9537        .unwrap();
9538        let absent = read_status(dir.path()).expect("a missing field must still parse");
9539        assert!(absent.current.is_empty());
9540    }
9541
9542    #[test]
9543    fn a_task_without_a_repository_runs_in_the_daemons_default() {
9544        let fallback = Path::new("/default");
9545        let mut blank = task();
9546        blank.repo = PathBuf::new();
9547        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
9548        let mut dot = task();
9549        dot.repo = PathBuf::from(".");
9550        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
9551        assert_eq!(
9552            repo_for(&task(), fallback),
9553            PathBuf::from("/repo"),
9554            "a task that names a repository keeps it"
9555        );
9556    }
9557
9558    #[test]
9559    fn task_implementers_edit_inherits_daemon_config_and_merge() {
9560        let dir = tempfile::tempdir().unwrap();
9561        let path = dir.path().join("explicit.toml");
9562        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
9563        let opts = Opts {
9564            config: Some(path),
9565            merge: Some("none".into()),
9566            ..Default::default()
9567        };
9568        let mut t = task();
9569        t.set_implementers(
9570            2,
9571            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9572                .unwrap(),
9573        )
9574        .unwrap();
9575        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9576        assert_eq!(cfg.graph.implementers, 2);
9577        assert_eq!(cfg.graph.judges, 1);
9578        assert_eq!(cfg.merge.mode, MergeMode::None);
9579        t.set_implementers(1, &cfg).unwrap();
9580        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
9581        apply_task_implementers(&mut cfg, &t);
9582        assert_eq!(cfg.graph.implementers, 1);
9583        assert_eq!(cfg.graph.judges, 1);
9584        assert_eq!(cfg.merge.mode, MergeMode::None);
9585    }
9586
9587    #[test]
9588    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
9589        let dir = tempfile::tempdir().unwrap();
9590        let repo = dir.path().join("repo");
9591        std::fs::create_dir(&repo).unwrap();
9592        std::fs::write(
9593            repo.join("magi.toml"),
9594            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
9595        )
9596        .unwrap();
9597        let daemon_config = dir.path().join("daemon.toml");
9598        std::fs::write(
9599            &daemon_config,
9600            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
9601        )
9602        .unwrap();
9603        let opts = Opts {
9604            config: Some(daemon_config),
9605            merge: Some("pr".into()),
9606            ..Default::default()
9607        };
9608        let q = Queue::at(dir.path().join("queue"));
9609        let validation: Config =
9610            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9611                .unwrap();
9612        // No provenance field on legacy direct tasks: both shapes stay isolated.
9613        for record in ["{}", r#"{"candidates":2}"#] {
9614            let overrides = serde_json::from_str(record).unwrap();
9615            let filing = crate::direct::Filing {
9616                instruction: "work".into(),
9617                title: "direct".into(),
9618                repo: repo.clone(),
9619                source: crate::queue::Source::Human,
9620                solo: false,
9621                overrides,
9622                review_of: None,
9623                sources: Default::default(),
9624            };
9625            let filed =
9626                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
9627            let crate::direct::Filed::Standalone {
9628                mut task,
9629                claim: _claim,
9630            } = filed
9631            else {
9632                panic!("local filing")
9633            };
9634            let before = prepare_for(&repo, &opts, &task).unwrap();
9635            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
9636            assert_eq!(
9637                before.merge.mode,
9638                MergeMode::None,
9639                "daemon --merge must not leak"
9640            );
9641            for n in [2, 1, 2] {
9642                task.set_implementers(n, &validation).unwrap();
9643                q.put(&mut task).unwrap();
9644                task = q.get(&task.id).unwrap();
9645                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
9646                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
9647                apply_task_implementers(&mut cfg, &task);
9648                assert_eq!(cfg.graph.implementers, usize::from(n));
9649                assert_eq!(cfg.graph.judges, 2);
9650                assert_eq!(cfg.merge.mode, MergeMode::None);
9651            }
9652        }
9653    }
9654
9655    #[test]
9656    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
9657        let cfg: Config =
9658            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9659                .unwrap();
9660        let mut t = task();
9661        t.review_of = Some("review-target".into());
9662        t.hold_manual(Some("retry".into()));
9663        let mut previous = RunState::new(
9664            PathBuf::from("/repo"),
9665            "main".into(),
9666            "abc1234".into(),
9667            "review".into(),
9668            cfg.clone(),
9669        );
9670        previous.config.graph.implementers = 2;
9671        for count in [1, 3] {
9672            t.set_implementers(count, &cfg).unwrap();
9673            t.release();
9674            assert_eq!(t.review_of.as_deref(), Some("review-target"));
9675            for proposed in [
9676                Starter::Resume(previous.id.clone()),
9677                Starter::Review("recovery-target".into()),
9678            ] {
9679                assert_eq!(
9680                    starter_with_implementers(&t, Some(&previous), proposed),
9681                    Starter::Review("review-target".into())
9682                );
9683            }
9684            let mut configured = cfg.clone();
9685            apply_task_implementers(&mut configured, &t);
9686            assert_eq!(configured.graph.implementers, usize::from(count));
9687            assert_eq!(previous.config.graph.implementers, 2);
9688        }
9689    }
9690
9691    #[test]
9692    fn task_implementers_dispatch_and_resume_agree() {
9693        let mut t = task();
9694        let cfg: crate::config::Config =
9695            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
9696                .unwrap();
9697        let mut run = RunState::new(
9698            PathBuf::from("/repo"),
9699            "main".into(),
9700            "abc1234".into(),
9701            "work".into(),
9702            cfg.clone(),
9703        );
9704        run.config.graph.implementers = 2;
9705        for n in [2, 1, 3, 2] {
9706            t.set_implementers(n, &cfg).unwrap();
9707            let mut dispatched = cfg.clone();
9708            apply_task_implementers(&mut dispatched, &t);
9709            assert_eq!(dispatched.graph.implementers, usize::from(n));
9710            assert_eq!(implementers_match(&t, &run), n == 2);
9711            for proposed in [
9712                Starter::Resume(run.id.clone()),
9713                Starter::Review("old-branch".into()),
9714            ] {
9715                let expected = if n == 2 {
9716                    proposed.clone()
9717                } else {
9718                    Starter::Start
9719                };
9720                assert_eq!(
9721                    starter_with_implementers(&t, Some(&run), proposed),
9722                    expected
9723                );
9724            }
9725            assert_eq!(
9726                run.config.graph.implementers, 2,
9727                "history must not be rewritten"
9728            );
9729        }
9730        t.solo = false;
9731        t.overrides = None;
9732        assert!(implementers_match(&t, &run));
9733    }
9734
9735    #[test]
9736    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
9737        // Three seats said out loud. What `solo` promises is one candidate
9738        // *whatever the config asks for*, so the contrast has to be a number
9739        // this test owns - it used to be `Config::default()`'s, which became
9740        // 1 when one implementation became the default and left the two
9741        // halves of this test asserting the same thing.
9742        let mut solo_cfg = Config::default();
9743        solo_cfg.graph.implementers = 3;
9744        let mut solo_task = task();
9745        solo_task.solo = true;
9746        apply_task_implementers(&mut solo_cfg, &solo_task);
9747        assert_eq!(solo_cfg.graph.implementers, 1);
9748
9749        let mut plain_cfg = Config::default();
9750        plain_cfg.graph.implementers = 3;
9751        let plain_task = task();
9752        assert!(!plain_task.solo);
9753        apply_task_implementers(&mut plain_cfg, &plain_task);
9754        assert_eq!(
9755            plain_cfg.graph.implementers, 3,
9756            "a task that did not ask to run alone keeps the config's candidates"
9757        );
9758    }
9759
9760    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
9761        QuotaLoss {
9762            seat: seat.into(),
9763            node: "judge".into(),
9764            at: at.parse().unwrap(),
9765            reset: reset.map(str::to_string),
9766        }
9767    }
9768
9769    #[test]
9770    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
9771        let old: Vec<QuotaLoss> = (1..=4)
9772            .map(|i| {
9773                loss(
9774                    &format!("judge-{i}"),
9775                    "2026-09-23T05:23:00Z",
9776                    Some("2:40pm (Asia/Tokyo)"),
9777                )
9778            })
9779            .collect();
9780        let fresh = losses_this_attempt(&old, &old);
9781        assert!(fresh.is_empty());
9782        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
9783        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
9784    }
9785
9786    #[test]
9787    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
9788        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
9789        let now = Timestamp::now();
9790        let mut after = old.clone();
9791        after.push(loss("judge-2", &now.to_string(), None));
9792        let fresh = losses_this_attempt(&old, &after);
9793        assert_eq!(fresh, vec![after[1].clone()]);
9794        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
9795        assert_eq!(
9796            until,
9797            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
9798        );
9799    }
9800
9801    #[test]
9802    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
9803        // `recover_stall` removes judge-1's loss and the retry then hits quota
9804        // again: the vector is the same length, so an index diff sees nothing.
9805        let before = vec![
9806            loss("judge-1", "2026-09-23T05:23:00Z", None),
9807            loss("judge-2", "2026-09-23T05:24:00Z", None),
9808        ];
9809        let after = vec![
9810            loss("judge-2", "2026-09-23T05:24:00Z", None),
9811            loss("judge-1", "2026-09-24T01:00:00Z", None),
9812        ];
9813        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
9814    }
9815
9816    #[test]
9817    fn merge_overrides_are_parsed_or_refused() {
9818        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
9819        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
9820        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
9821        assert!(merge_mode("squash").is_err());
9822    }
9823
9824    #[test]
9825    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
9826        let now = Timestamp::now();
9827        let fallback = Duration::from_secs(300);
9828        let cap = Duration::from_secs(1800);
9829
9830        // No reset hint at all: the fallback.
9831        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
9832
9833        // A reset ten minutes out, well inside the cap: waited for exactly.
9834        let soon = now + jiff::SignedDuration::from_secs(600);
9835        assert_eq!(
9836            quota_wait(Some(soon), now, fallback, cap),
9837            Duration::from_secs(600)
9838        );
9839
9840        // A reset already in the past is not trusted: the fallback, not a
9841        // zero or negative wait that would spin the loop right back around.
9842        let past = now - jiff::SignedDuration::from_secs(60);
9843        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
9844
9845        // A reset further out than the cap is trusted for direction but not
9846        // for magnitude: a parsing slip must not sleep the loop for a day.
9847        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
9848        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
9849    }
9850
9851    #[test]
9852    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
9853        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
9854
9855        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
9856        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
9857
9858        // Same clock reading, but it has already gone by today: read as
9859        // tomorrow's, since the CLI would not still be reporting a limit past
9860        // its own stated reset.
9861        let already_past =
9862            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
9863        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
9864
9865        assert!(
9866            parse_reset_hint("session limit reached", now, now).is_none(),
9867            "free text with no recognised shape is not guessed at"
9868        );
9869        assert!(
9870            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
9871            "an unresolvable zone name is not guessed at either"
9872        );
9873    }
9874
9875    #[test]
9876    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
9877        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
9878
9879        let at = parse_reset_hint(
9880            "You've hit your usage limit. Visit \
9881             https://chatgpt.com/codex/settings/usage to purchase more \
9882             credits or try again at Sep 19th, 2026 5:10 PM.",
9883            now,
9884            now,
9885        )
9886        .expect("the codex reset wording is a recognised shape");
9887        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
9888
9889        // The month is explicit, so a date already earlier in the same
9890        // sentence-implied year than `now` is trusted as written rather than
9891        // rolled forward a year the way the bracketed shape rolls a
9892        // same-day clock reading to tomorrow.
9893        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
9894            .expect("an explicit year needs no rollover");
9895        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
9896
9897        assert!(
9898            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
9899            "a two-digit year is not the documented shape and is not guessed at"
9900        );
9901        assert!(
9902            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
9903            "a four-letter month name is not the documented three-letter abbreviation"
9904        );
9905        assert!(
9906            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
9907            "an explicit zone on the dated shape is a format nobody has \
9908             documented, and is refused rather than guessed at as UTC"
9909        );
9910    }
9911
9912    #[test]
9913    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
9914        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
9915        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
9916
9917        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
9918        assert_eq!(at.as_second() - recorded.as_second(), 3769);
9919
9920        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
9921        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
9922
9923        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
9924            assert!(
9925                parse_reset_hint(bad, now, recorded).is_none(),
9926                "{bad:?} must not be guessed at"
9927            );
9928        }
9929    }
9930
9931    /// A loop whose queue lives in a temp tree and whose poll interval is far
9932    /// longer than the test's patience, so anything that waits out a poll
9933    /// instead of noticing the stop fails rather than merely being slow.
9934    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
9935        let config = dir.join("magi.toml");
9936        std::fs::write(
9937            &config,
9938            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
9939        )
9940        .unwrap();
9941        let opts = Opts {
9942            poll: Duration::from_secs(30),
9943            config: Some(config),
9944            // The explicit fixture config keeps startup cleanup from reading
9945            // machine configuration. This fictional repository likewise
9946            // keeps any best-effort git cleanup away from this checkout.
9947            repo: dir.join("repo"),
9948            ..Opts::default()
9949        };
9950        // The status file goes in a directory that does not exist yet, so its
9951        // creation is itself evidence the loop published one. `worktrees`
9952        // must be just as fictional: the janitor reclaims worktrees under it
9953        // for real, and a test that let it fall through to
9954        // `crate::run::default_worktree_root()` would have it reclaim
9955        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
9956        // which is exactly what happened before this function took the
9957        // parameter at all.
9958        let home = dir.join("home");
9959        // These control-only fixtures do not launch native workers. Give the
9960        // independently tested maintenance services a fresh cadence receipt.
9961        let stamps = home.join("service-ticks");
9962        std::fs::create_dir_all(&stamps).unwrap();
9963        for service in ["waiter", "deputies", "release-watch"] {
9964            std::fs::write(
9965                stamps.join(service),
9966                Timestamp::now().as_second().to_string(),
9967            )
9968            .unwrap();
9969        }
9970        for operation in [
9971            "conductor",
9972            "maintenance",
9973            "housekeeping",
9974            "disk-pressure",
9975            "cache",
9976            "fetch",
9977        ] {
9978            std::fs::write(
9979                stamps.join(format!("daemon-{operation}")),
9980                serde_json::to_vec(&Timestamp::now()).unwrap(),
9981            )
9982            .unwrap();
9983        }
9984        let worktrees = dir.join("wt");
9985        (
9986            opts,
9987            Queue::at(dir.join("queue")),
9988            home.join("daemon.json"),
9989            home,
9990            worktrees,
9991        )
9992    }
9993
9994    #[test]
9995    fn a_stop_is_idempotent_and_once_set_stays_set() {
9996        let stop = Stop::new();
9997        assert!(!stop.stopped());
9998
9999        stop.stop();
10000        assert!(stop.stopped());
10001        stop.stop();
10002        assert!(stop.stopped(), "a second stop is not a toggle");
10003
10004        let shared = stop.clone();
10005        assert!(
10006            shared.stopped(),
10007            "a clone is the same stop; that is how the loop and its caller share one"
10008        );
10009    }
10010
10011    #[tokio::test]
10012    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
10013        for operation in ["conductor", "maintenance", "housekeeping"] {
10014            let dir = tempfile::tempdir().unwrap();
10015            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
10016            opts.once = true;
10017            opts.poll = Duration::from_millis(1);
10018            let mut task = task();
10019            task.runs.push("fixture-run".into());
10020            queue.put(&mut task).unwrap();
10021            let claim = queue.claim(&task.id).unwrap();
10022
10023            // Model a live service holding the task's claim across the
10024            // scheduler's dispatch scan. No real subprocess or timed race.
10025            let directory = home.join("workers/jobs/abcdef");
10026            std::fs::create_dir_all(&directory).unwrap();
10027            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
10028            crate::pr_head::try_lock_file(&lease).unwrap();
10029            let mut job = crate::worker::Job {
10030                id: "abcdef".into(),
10031                sequence: 1,
10032                kind: "daemon-service".into(),
10033                key: format!("service:daemon-{operation}"),
10034                payload: serde_json::Value::Null,
10035                generation: "fixture".into(),
10036                version: None,
10037                status: crate::worker::Status::Running,
10038                result: None,
10039                pid: Some(std::process::id()),
10040                created_at: Timestamp::now().as_second() as u64,
10041                finished_at: None,
10042            };
10043            let record = directory.join("job.json");
10044            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10045
10046            let status = Arc::new(Mutex::new(Status::new()));
10047            let stop = Stop::new();
10048            let mut drain = Box::pin(poll(
10049                &opts,
10050                &queue,
10051                &status,
10052                &home,
10053                &worktrees,
10054                &stop,
10055                DispatchLimits {
10056                    max_concurrent: 1,
10057                    pause_for_interrupts: false,
10058                    recovery_cfg: None,
10059                },
10060            ));
10061            std::future::poll_fn(|cx| {
10062                use std::future::Future;
10063                assert!(
10064                    drain.as_mut().poll(cx).is_pending(),
10065                    "--once must wait for {operation} to release its queue claim"
10066                );
10067                std::task::Poll::Ready(())
10068            })
10069            .await;
10070            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
10071
10072            // An answer arrives while the service still owns the claim. A
10073            // fresh scheduling pass must apply it before declaring idle.
10074            let questions = Questions::at(home.join("questions"));
10075            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
10076            questions.put(&mut q).unwrap();
10077            drop(claim);
10078            // Model services that took longer than their cadence, without a
10079            // wall-clock sleep. The final scans must not respawn them even
10080            // though their receipts now permit another periodic invocation.
10081            let expired =
10082                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
10083            for service in [operation, "housekeeping"] {
10084                std::fs::write(
10085                    home.join("service-ticks").join(format!("daemon-{service}")),
10086                    &expired,
10087                )
10088                .unwrap();
10089            }
10090            job.status = crate::worker::Status::Finished;
10091            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
10092            drop(lease);
10093            tokio::time::timeout(Duration::from_secs(2), drain)
10094                .await
10095                .expect("the settled service must allow the drain to finish")
10096                .unwrap();
10097            let after = queue.get(&task.id).unwrap();
10098            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
10099            assert!(after.action_applied(&q.id));
10100            for service in [operation, "housekeeping"] {
10101                assert_eq!(
10102                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
10103                        .unwrap(),
10104                    expired,
10105                    "the final once rescan must not restart {service}"
10106                );
10107            }
10108        }
10109    }
10110
10111    #[test]
10112    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
10113        let stop = Stop::new();
10114        stop.busy.store(1, Ordering::SeqCst);
10115        assert!(
10116            !stop.finishing(),
10117            "a busy loop nobody has asked to stop is just running"
10118        );
10119
10120        stop.stop();
10121        assert!(
10122            stop.finishing(),
10123            "a stop asked for mid-run has not landed until the run is settled"
10124        );
10125
10126        stop.busy.store(0, Ordering::SeqCst);
10127        assert!(
10128            !stop.finishing(),
10129            "once the run is settled the stop has landed and there is nothing to finish"
10130        );
10131    }
10132
10133    #[test]
10134    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
10135        let stop = Stop::new();
10136        stop.busy.store(2, Ordering::SeqCst);
10137        stop.stop();
10138        assert!(stop.finishing(), "two runs still in flight");
10139
10140        stop.busy.store(1, Ordering::SeqCst);
10141        assert!(
10142            stop.finishing(),
10143            "one run finished, but a sibling is still working"
10144        );
10145
10146        stop.busy.store(0, Ordering::SeqCst);
10147        assert!(
10148            !stop.finishing(),
10149            "the last run out is what actually lands the stop"
10150        );
10151    }
10152
10153    #[tokio::test]
10154    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
10155        let dir = tempfile::tempdir().unwrap();
10156        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10157        let stop = Stop::new();
10158        stop.stop();
10159
10160        let began = std::time::Instant::now();
10161        tokio::time::timeout(
10162            Duration::from_secs(2),
10163            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10164        )
10165        .await
10166        .expect("a stopped loop must return, not sit out its poll interval")
10167        .expect("the loop's own setup and teardown must not fail");
10168        assert!(
10169            began.elapsed() < opts.poll,
10170            "returned only after {:?}, which is a poll interval, not a stop",
10171            began.elapsed()
10172        );
10173    }
10174
10175    #[tokio::test]
10176    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
10177        let dir = tempfile::tempdir().unwrap();
10178        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10179        let stop = Stop::new();
10180
10181        // Asked for after the loop is already parked on its empty queue, which
10182        // is the case an operator tapping stop on a phone actually hits.
10183        let asker = {
10184            let stop = stop.clone();
10185            tokio::spawn(async move {
10186                tokio::time::sleep(Duration::from_millis(20)).await;
10187                stop.stop();
10188            })
10189        };
10190
10191        let began = std::time::Instant::now();
10192        tokio::time::timeout(
10193            Duration::from_secs(2),
10194            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10195        )
10196        .await
10197        .expect("a stop asked for while idle must wake the wait")
10198        .expect("the loop's own setup and teardown must not fail");
10199        asker.await.unwrap();
10200        assert!(
10201            began.elapsed() < opts.poll,
10202            "returned only after {:?}, so the stop waited on the sleep",
10203            began.elapsed()
10204        );
10205    }
10206
10207    #[tokio::test]
10208    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
10209        let dir = tempfile::tempdir().unwrap();
10210        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
10211        let stop = Stop::new();
10212        stop.stop();
10213
10214        tokio::time::timeout(
10215            Duration::from_secs(2),
10216            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
10217        )
10218        .await
10219        .expect("a stopped loop must return")
10220        .expect("the loop's own setup and teardown must not fail");
10221
10222        assert!(
10223            home.is_dir(),
10224            "the loop did publish a status file, so its removal is the teardown and not an absence"
10225        );
10226        assert!(
10227            !status_file.exists(),
10228            "a stopped loop clears its status file"
10229        );
10230        assert!(
10231            read_status(&home).is_none(),
10232            "a reader must see no daemon at all, not a heartbeat that merely stopped"
10233        );
10234    }
10235
10236    #[tokio::test]
10237    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
10238        let dir = tempfile::tempdir().unwrap();
10239        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
10240
10241        let mut settled = RunState::new(
10242            dir.path().join("repo"),
10243            "main".to_owned(),
10244            "abc1234".to_owned(),
10245            "fixture".to_owned(),
10246            Config::default(),
10247        );
10248        settled.status = RunStatus::Ready;
10249        let run_dir = home.join("runs").join(&settled.id);
10250        std::fs::create_dir_all(&run_dir).unwrap();
10251        std::fs::write(
10252            run_dir.join("run.json"),
10253            serde_json::to_string_pretty(&settled).unwrap(),
10254        )
10255        .unwrap();
10256        let questions = Questions::at(home.join("questions"));
10257        let mut question = ask::Question::new(
10258            settled.id.clone(),
10259            "review".to_owned(),
10260            "reviewer-1".to_owned(),
10261            "Continue?".to_owned(),
10262            String::new(),
10263            Vec::new(),
10264        );
10265        questions.put(&mut question).unwrap();
10266
10267        run_service_worker(
10268            &home,
10269            serde_json::to_value(ServiceWorker {
10270                opts,
10271                queue: queue.root().to_path_buf(),
10272                worktrees_root: worktrees,
10273                operation: "housekeeping".to_owned(),
10274            })
10275            .unwrap(),
10276        )
10277        .await
10278        .unwrap();
10279
10280        assert_eq!(
10281            questions.get(&question.id).unwrap().status,
10282            ask::QuestionStatus::Abandoned,
10283            "the independent housekeeping worker settles ended-run questions"
10284        );
10285    }
10286
10287    #[test]
10288    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
10289        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10290
10291        assert!(
10292            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
10293            "never checked before: due at once"
10294        );
10295
10296        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
10297        assert!(
10298            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
10299            "well inside the interval: not due yet"
10300        );
10301
10302        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
10303        assert!(
10304            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
10305            "exactly at the edge: not yet due, same convention as `clean::due`"
10306        );
10307
10308        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10309        assert!(
10310            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
10311            "past the interval: due again"
10312        );
10313    }
10314
10315    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
10316    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
10317    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
10318    /// and the congestion test below both need, and must not drift apart.
10319    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
10320        let config = dir.join("magi.toml");
10321        // A literal (single-quoted) TOML string, not a basic one: the cache
10322        // path is a Windows path full of backslashes, and a basic string
10323        // would have TOML try to interpret `\U` (from `\Users\...`) as a
10324        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
10325        // `{{ vars.cache }}` rendering documents.
10326        std::fs::write(
10327            &config,
10328            format!(
10329                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
10330                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
10331                cache_dir.display()
10332            ),
10333        )
10334        .unwrap();
10335        Opts {
10336            config: Some(config),
10337            repo: dir.join("repo"),
10338            ..Opts::default()
10339        }
10340    }
10341
10342    #[tokio::test]
10343    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
10344        let dir = tempfile::tempdir().unwrap();
10345        let home = dir.path().join("home");
10346        let cache_dir = dir.path().join("cache");
10347        std::fs::create_dir_all(&cache_dir).unwrap();
10348        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10349        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10350
10351        // Nobody has asked this daemon to stop, which is the ordinary case;
10352        // the skip that a stop buys is asserted by its own test below.
10353        let running = Stop::new();
10354        let mut last_checked = None;
10355        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10356        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
10357            .await;
10358        assert_eq!(
10359            crate::disk::dir_size(&cache_dir),
10360            0,
10361            "over the cap on the first check ever: pruned at once, no idle queue required"
10362        );
10363        assert_eq!(last_checked, Some(t0));
10364
10365        // A fresh oversized file lands, but the next check is not due yet.
10366        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
10367        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
10368        maybe_prune_cache_between_runs(
10369            &opts.repo,
10370            &opts,
10371            &home,
10372            &running,
10373            &mut last_checked,
10374            too_soon,
10375        )
10376        .await;
10377        assert_eq!(
10378            crate::disk::dir_size(&cache_dir),
10379            10,
10380            "too soon since the last check: left alone rather than rescanned every call"
10381        );
10382        assert_eq!(
10383            last_checked,
10384            Some(t0),
10385            "an idle check does not reset the clock"
10386        );
10387
10388        // Once the interval elapses, the same oversized cache is caught again.
10389        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
10390        maybe_prune_cache_between_runs(
10391            &opts.repo,
10392            &opts,
10393            &home,
10394            &running,
10395            &mut last_checked,
10396            due_again,
10397        )
10398        .await;
10399        assert_eq!(
10400            crate::disk::dir_size(&cache_dir),
10401            0,
10402            "due again: pruned back under the cap"
10403        );
10404    }
10405
10406    /// A stop must not queue behind housekeeping. The prune below is a
10407    /// synchronous walk of the whole cache with no await point in it, so a
10408    /// loop that entered it could not get back to its own `stopped()` test
10409    /// until the walk finished - and because no run is in flight at this
10410    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
10411    /// the stop had already landed. The idle branch has always made this same
10412    /// check before reaching `janitor`; the between-runs path makes it too.
10413    #[tokio::test]
10414    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
10415        let dir = tempfile::tempdir().unwrap();
10416        let home = dir.path().join("home");
10417        let cache_dir = dir.path().join("cache");
10418        std::fs::create_dir_all(&cache_dir).unwrap();
10419        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
10420        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
10421
10422        let stop = Stop::new();
10423        stop.stop();
10424        assert!(
10425            !stop.finishing(),
10426            "no run is in flight at a between-runs boundary, so nothing else \
10427             would tell the operator this stop had not taken effect yet"
10428        );
10429
10430        let mut last_checked = None;
10431        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
10432        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
10433            .await;
10434        assert_eq!(
10435            crate::disk::dir_size(&cache_dir),
10436            10,
10437            "over its cap, and due for the first check ever, but a stop outranks \
10438             it: the cap is a standing policy the next start measures again"
10439        );
10440        assert_eq!(
10441            last_checked, None,
10442            "a check that never happened must not claim the interval"
10443        );
10444    }
10445
10446    /// A backlog must not starve cache pruning. The finite cache worker runs
10447    /// independently of queue drain and must not consume any task attempts.
10448    #[tokio::test]
10449    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
10450        let dir = tempfile::tempdir().unwrap();
10451        let cache_dir = dir.path().join("cache");
10452        std::fs::create_dir_all(&cache_dir).unwrap();
10453        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
10454
10455        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
10456        opts.poll = Duration::from_millis(20);
10457        opts.max_attempts = 1_000;
10458
10459        let queue = Queue::at(dir.path().join("queue"));
10460        for i in 0..128 {
10461            let mut task = Task::new(
10462                format!("queued work {i}"),
10463                format!("queued work {i}"),
10464                opts.repo.clone(),
10465                Source::Human,
10466            );
10467            queue.put(&mut task).unwrap();
10468        }
10469
10470        let home = dir.path().join("home");
10471        let worktrees = dir.path().join("wt");
10472        run_service_worker(
10473            &home,
10474            serde_json::to_value(ServiceWorker {
10475                opts,
10476                queue: queue.root().to_path_buf(),
10477                worktrees_root: worktrees,
10478                operation: "cache".to_owned(),
10479            })
10480            .unwrap(),
10481        )
10482        .await
10483        .unwrap();
10484        let after = queue.list();
10485        assert_eq!(after.len(), 128);
10486        assert!(
10487            after
10488                .iter()
10489                .all(|task| task.status.runnable() && task.attempts == 0)
10490        );
10491
10492        assert_eq!(
10493            crate::disk::dir_size(&cache_dir),
10494            0,
10495            "an oversized cache must not be left to grow unboundedly just because the \
10496             queue kept the loop busy the whole time"
10497        );
10498    }
10499
10500    #[test]
10501    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
10502        let dir = tempfile::tempdir().unwrap();
10503        let queue = Queue::at(dir.path().join("queue"));
10504        let questions = Questions::at(dir.path().join("questions"));
10505        let mut task = task();
10506        queue.put(&mut task).unwrap();
10507
10508        let mut task_question = ask::Question::new(
10509            task.id.clone(),
10510            crate::conduct::NODE.to_owned(),
10511            "conduct".to_owned(),
10512            "Which backend?".to_owned(),
10513            String::new(),
10514            Vec::new(),
10515        );
10516        questions.put(&mut task_question).unwrap();
10517        task.block(vec![task_question.id.clone()], None);
10518        queue.put(&mut task).unwrap();
10519
10520        let mut run_question = ask::Question::new(
10521            "20260101-000000-run1".to_owned(),
10522            "review".to_owned(),
10523            "reviewer-1".to_owned(),
10524            "Run question".to_owned(),
10525            String::new(),
10526            Vec::new(),
10527        );
10528        questions.put(&mut run_question).unwrap();
10529
10530        // A question from another node whose `run` happens to equal this
10531        // task's id — the same field, filled in for an unrelated reason. Only
10532        // `crate::conduct::NODE` questions use `run` as a task id; this one
10533        // must never be touched by this reconciliation, even after release.
10534        let mut coincidental = ask::Question::new(
10535            task.id.clone(),
10536            "review".to_owned(),
10537            "reviewer-1".to_owned(),
10538            "Unrelated review question".to_owned(),
10539            String::new(),
10540            Vec::new(),
10541        );
10542        questions.put(&mut coincidental).unwrap();
10543
10544        reconcile_task_questions(&queue, &questions);
10545        assert!(questions.get(&task_question.id).unwrap().status.open());
10546        assert!(questions.get(&run_question.id).unwrap().status.open());
10547        assert!(questions.get(&coincidental.id).unwrap().status.open());
10548
10549        task.release();
10550        queue.put(&mut task).unwrap();
10551        reconcile_task_questions(&queue, &questions);
10552        assert_eq!(
10553            questions.get(&task_question.id).unwrap().status,
10554            ask::QuestionStatus::Abandoned
10555        );
10556        assert!(
10557            questions.get(&run_question.id).unwrap().status.open(),
10558            "run questions remain the run janitor's responsibility"
10559        );
10560        assert!(
10561            questions.get(&coincidental.id).unwrap().status.open(),
10562            "a non-conductor question must not be abandoned just because its \
10563             run id coincides with a task id"
10564        );
10565    }
10566
10567    #[test]
10568    fn a_freshly_started_running_task_is_never_stalled() {
10569        let dir = tempfile::tempdir().unwrap();
10570        let mut t = task();
10571        t.start("run-1".to_owned());
10572        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
10573        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
10574        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
10575    }
10576
10577    #[test]
10578    fn a_long_running_task_with_no_live_daemon_is_stalled() {
10579        let dir = tempfile::tempdir().unwrap();
10580        let mut t = task();
10581        t.start("run-1".to_owned());
10582        t.updated_at = Timestamp::now()
10583            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10584        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
10585        assert_eq!(
10586            stalled_tasks(
10587                &Queue::at(dir.path().join("q")),
10588                dir.path(),
10589                Timestamp::now()
10590            )
10591            .len(),
10592            0,
10593            "the task was never written to this queue"
10594        );
10595    }
10596
10597    #[test]
10598    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
10599        let dir = tempfile::tempdir().unwrap();
10600        let mut t = task();
10601        t.id = "20260903-080340-0167".to_owned();
10602        t.start("20260903-080619-01c2".to_owned());
10603        t.updated_at = Timestamp::now()
10604            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
10605
10606        let mut status = Status::new();
10607        status.current = vec![Current {
10608            worker: None,
10609            task: t.id.clone(),
10610            run: "20260903-080619-01c2".to_owned(),
10611        }];
10612        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10613
10614        assert!(
10615            !is_stalled(&t, dir.path(), Timestamp::now()),
10616            "a live daemon's own heartbeat rules out stalled, however long the task has run"
10617        );
10618    }
10619
10620    /// Rewrite a task's `updated_at` on disk directly, bypassing
10621    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
10622    /// a fixture look like it has genuinely been `running` for a while.
10623    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
10624        let path = queue.path_of(id);
10625        let body = std::fs::read_to_string(&path).unwrap();
10626        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
10627        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
10628        v["updated_at"] = serde_json::Value::String(old.to_string());
10629        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
10630    }
10631
10632    #[test]
10633    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
10634        // The realistic `poll()` ordering, not `is_stalled` in isolation:
10635        // `reclaim_orphaned_running` runs first, on every poll, and settles
10636        // any `running` task whose claim it can actually take. For most
10637        // crashes that is immediate - a dead pid is proof enough for
10638        // `sweep_stale_claims` to drop the lock the same tick, and the very
10639        // next claim attempt succeeds. But a lock whose pid cannot be parsed
10640        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
10641        // `sweep_stale_claims`'s own doc), so the lock - and the claim
10642        // failure behind it - can legitimately outlive many polls. This is
10643        // exactly the gap `stalled_tasks` exists to surface well before that
10644        // six-hour sweep would: reclaim leaves the task `running`, and it
10645        // must still reach the conductor as stalled.
10646        let dir = tempfile::tempdir().unwrap();
10647        let queue = Queue::at(dir.path().join("queue"));
10648        let home = dir.path().join("home");
10649
10650        let mut t = task();
10651        t.id = "20260101-000001-lock".to_owned();
10652        t.start("run-1".to_owned());
10653        queue.put(&mut t).unwrap();
10654        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10655        std::fs::write(
10656            dir.path().join("queue").join(format!("{}.lock", t.id)),
10657            "not a pid",
10658        )
10659        .unwrap();
10660
10661        let now = Timestamp::now();
10662        assert!(
10663            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
10664            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
10665             and reclaim must leave the task alone"
10666        );
10667        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10668
10669        let stalled = stalled_tasks(&queue, &home, now);
10670        assert_eq!(
10671            stalled.len(),
10672            1,
10673            "reclaim's inability to claim it yet must not hide it from the conductor"
10674        );
10675        assert_eq!(stalled[0].id, t.id);
10676    }
10677
10678    #[test]
10679    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
10680        let dir = tempfile::tempdir().unwrap();
10681        crate::run::set_home(dir.path().join("run-home"));
10682        let queue = Queue::at(dir.path().join("queue"));
10683        let home = dir.path().join("home");
10684        let questions = Questions::at(dir.path().join("questions"));
10685
10686        let mut t = task();
10687        t.id = "20260101-000003-dead".to_owned();
10688        t.start("missing-run".to_owned());
10689        queue.put(&mut t).unwrap();
10690        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
10691
10692        // This is the real poll ordering: retain the deterministic stalled
10693        // input before a claim proves the owner is gone and reclaims it.
10694        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10695        assert_eq!(
10696            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
10697            [&t.id]
10698        );
10699        assert_eq!(
10700            reclaim_orphaned_running(&queue, 2, &Default::default()),
10701            [t.id.clone()]
10702        );
10703        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
10704
10705        // Reclaim drops its guard before conductor decisions are applied, so
10706        // the decision for the captured stalled input has a real write path.
10707        crate::conduct::apply(
10708            &queue,
10709            &questions,
10710            &crate::conduct::Verdict {
10711                decisions: vec![crate::conduct::Decision {
10712                    id: t.id.clone(),
10713                    recovery: Some(crate::conduct::Recovery::Requeue),
10714                    ..crate::conduct::Decision::default()
10715                }],
10716            },
10717        )
10718        .unwrap();
10719        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
10720    }
10721
10722    #[test]
10723    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
10724        let dir = tempfile::tempdir().unwrap();
10725        let queue = Queue::at(dir.path().join("queue"));
10726        let home = dir.path().join("home");
10727
10728        let mut fresh = task();
10729        fresh.id = "20260101-000001-aaaa".to_owned();
10730        fresh.start("run-1".to_owned());
10731        queue.put(&mut fresh).unwrap();
10732
10733        let mut old = task();
10734        old.id = "20260101-000002-bbbb".to_owned();
10735        old.start("run-2".to_owned());
10736        queue.put(&mut old).unwrap();
10737        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
10738
10739        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
10740        assert_eq!(stalled.len(), 1);
10741        assert_eq!(stalled[0].id, old.id);
10742    }
10743
10744    #[test]
10745    fn queued_and_finished_task_views_partition_by_status() {
10746        let dir = tempfile::tempdir().unwrap();
10747        let queue = Queue::at(dir.path().join("queue"));
10748
10749        let mut queued = task();
10750        queued.id = "20260101-000001-aaaa".to_owned();
10751        queue.put(&mut queued).unwrap();
10752
10753        let mut failed = task();
10754        failed.id = "20260101-000002-bbbb".to_owned();
10755        failed.start("run-1".to_owned());
10756        failed.fail("gate red", 5);
10757        queue.put(&mut failed).unwrap();
10758
10759        let mut held = task();
10760        held.id = "20260101-000003-cccc".to_owned();
10761        held.hold_machine(None);
10762        queue.put(&mut held).unwrap();
10763
10764        let mut running = task();
10765        running.id = "20260101-000004-dddd".to_owned();
10766        running.start("run-2".to_owned());
10767        queue.put(&mut running).unwrap();
10768
10769        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
10770        assert_eq!(queued_ids, [queued.id.clone()]);
10771
10772        let mut finished_ids: Vec<String> =
10773            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
10774        finished_ids.sort_unstable();
10775        let mut want = vec![failed.id.clone(), held.id.clone()];
10776        want.sort_unstable();
10777        assert_eq!(finished_ids, want);
10778    }
10779
10780    #[test]
10781    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
10782        for short in [false, true] {
10783            let dir = tempfile::tempdir().unwrap();
10784            let queue = Queue::at(dir.path().join("queue"));
10785            let questions = ask::Questions::at(dir.path().join("questions"));
10786            let mut running = task();
10787            running.id = "20261013-192213-feb2".into();
10788            running.start("existing-run".into());
10789            queue.put(&mut running).unwrap();
10790            let mut middle = task();
10791            middle.id = "20261013-193611-ca5b".into();
10792            middle.block(
10793                vec![if short {
10794                    "feb2".into()
10795                } else {
10796                    running.id.clone()
10797                }],
10798                None,
10799            );
10800            queue.put(&mut middle).unwrap();
10801            let mut waiting = task();
10802            waiting.id = "20261013-202849-ee37".into();
10803            waiting.block(
10804                vec![if short {
10805                    "ca5b".into()
10806                } else {
10807                    middle.id.clone()
10808                }],
10809                Some("wait for implementation".into()),
10810            );
10811            queue.put(&mut waiting).unwrap();
10812            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
10813            let inv = crate::blockers::Inventory::load(&queue, &questions);
10814            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
10815            assert!(inv.stuck().is_empty());
10816            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10817            assert!(report.quarantined.is_empty());
10818            assert!(report.asked.is_empty());
10819            resolve_blockers(&queue, &questions);
10820            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10821            assert!(questions.list().is_empty());
10822            // Finishing the transitive prerequisite alone does not satisfy
10823            // the task's direct dependency.
10824            running.succeed();
10825            queue.put(&mut running).unwrap();
10826            resolve_blockers(&queue, &questions);
10827            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
10828            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10829            middle = queue.get(&middle.id).unwrap();
10830            middle.succeed();
10831            queue.put(&mut middle).unwrap();
10832            resolve_blockers(&queue, &questions);
10833            let after = queue.get(&waiting.id).unwrap();
10834            assert_eq!(after.status, TaskStatus::Queued);
10835            assert!(after.blocked_by.is_empty());
10836            assert_eq!(after.instruction, waiting.instruction);
10837        }
10838    }
10839
10840    #[test]
10841    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
10842        for future_schema in [false, true] {
10843            let name = "20261013-193611-ca5b";
10844            let mut future = task();
10845            future.id = name.into();
10846            future.schema = crate::queue::SCHEMA + 1;
10847            let contents = if future_schema {
10848                serde_json::to_string(&future).unwrap()
10849            } else {
10850                "corrupt".into()
10851            };
10852            let dir = tempfile::tempdir().unwrap();
10853            let queue = Queue::at(dir.path().join("queue"));
10854            let questions = ask::Questions::at(dir.path().join("questions"));
10855            let mut waiting = task();
10856            waiting.id = "20261013-202849-ee37".into();
10857            waiting.block(vec!["ca5b".into()], None);
10858            queue.put(&mut waiting).unwrap();
10859            std::fs::write(queue.path_of(name), contents).unwrap();
10860            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
10861            assert!(
10862                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
10863            );
10864            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10865            assert!(report.asked.is_empty());
10866            resolve_blockers(&queue, &questions);
10867            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10868            assert!(questions.list().is_empty());
10869        }
10870        let dir = tempfile::tempdir().unwrap();
10871        let queue = Queue::at(dir.path().join("queue"));
10872        let questions = ask::Questions::at(dir.path().join("questions"));
10873        let mut waiting = task();
10874        waiting.id = "20261013-202849-ee37".into();
10875        waiting.block(vec!["ca5b".into()], None);
10876        queue.put(&mut waiting).unwrap();
10877        let mut done = task();
10878        done.id = "20261013-193611-ca5b".into();
10879        done.succeed();
10880        queue.put(&mut done).unwrap();
10881        // An unreadable second match must not disappear from uniqueness
10882        // checks just because Queue::list skips it.
10883        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
10884        assert!(queue.get("ca5b").is_err());
10885        assert_eq!(
10886            crate::queue::dependency(&queue, &questions, "ca5b"),
10887            crate::queue::Dependency::Ambiguous
10888        );
10889        resolve_blockers(&queue, &questions);
10890        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
10891        assert!(report.asked.is_empty());
10892        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
10893        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
10894    }
10895
10896    #[test]
10897    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
10898        for held in [false, true] {
10899            for question in [false, true] {
10900                for reference in ["ca5b", "20261013-193611-ca5b"] {
10901                    let dir = tempfile::tempdir().unwrap();
10902                    let queue = Queue::at(dir.path().join("queue"));
10903                    let questions = ask::Questions::at(dir.path().join("questions"));
10904                    let mut prerequisite = task();
10905                    prerequisite.id = "20261013-193611-ca5b".into();
10906                    prerequisite.start("existing-run".into());
10907                    queue.put(&mut prerequisite).unwrap();
10908                    let mut waiting = task();
10909                    waiting.id = "20261013-202849-ee37".into();
10910                    if held {
10911                        waiting.hold_machine(Some("waiting for separate consent".into()));
10912                    }
10913                    queue.put(&mut waiting).unwrap();
10914                    let reason = "Deleting saved data requires separate owner consent";
10915                    crate::conduct::apply(
10916                        &queue,
10917                        &questions,
10918                        &crate::conduct::Verdict {
10919                            decisions: vec![crate::conduct::Decision {
10920                                id: waiting.id.clone(),
10921                                blocked_by: vec![reference.into()],
10922                                question: question.then(|| "May the saved data be deleted?".into()),
10923                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
10924                                reason: Some(reason.into()),
10925                                ..crate::conduct::Decision::default()
10926                            }],
10927                        },
10928                    )
10929                    .unwrap();
10930                    let before = queue.get(&waiting.id).unwrap();
10931                    if question {
10932                        assert_eq!(before.status, TaskStatus::Blocked);
10933                        let q = questions.get(&before.blocked_by[0]).unwrap();
10934                        assert_eq!(q.summary, "May the saved data be deleted?");
10935                        assert!(q.status.open());
10936                    } else {
10937                        assert_eq!(before.status, TaskStatus::Held);
10938                        let recorded_reason = before.hold_reason.as_deref().unwrap();
10939                        assert!(recorded_reason.starts_with(reason));
10940                        if held {
10941                            assert!(recorded_reason.contains("waiting for separate consent"));
10942                        }
10943                    }
10944                    prerequisite.succeed();
10945                    queue.put(&mut prerequisite).unwrap();
10946                    resolve_blockers(&queue, &questions);
10947                    let after = queue.get(&waiting.id).unwrap();
10948                    assert_eq!(after.status, before.status);
10949                    assert_eq!(after.blocked_by, before.blocked_by);
10950                    assert_eq!(after.hold_reason, before.hold_reason);
10951                    assert_eq!(after.instruction, waiting.instruction);
10952                    if question {
10953                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
10954                    }
10955                    assert!(
10956                        queue.next_runnable().is_none(),
10957                        "dependency completion is not consent"
10958                    );
10959                }
10960            }
10961        }
10962    }
10963
10964    #[test]
10965    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
10966        let dir = tempfile::tempdir().unwrap();
10967        let queue = Queue::at(dir.path().join("queue"));
10968        let questions = ask::Questions::at(dir.path().join("questions"));
10969
10970        let mut dep = task();
10971        dep.id = "20260101-000001-dep0".to_owned();
10972        dep.succeed();
10973        queue.put(&mut dep).unwrap();
10974
10975        let mut still_going = task();
10976        still_going.id = "20260101-000002-dep1".to_owned();
10977        queue.put(&mut still_going).unwrap();
10978
10979        let mut blocked = task();
10980        blocked.id = "20260101-000003-main".to_owned();
10981        blocked.block(
10982            vec![dep.id.clone(), still_going.id.clone()],
10983            Some("waits on both".to_owned()),
10984        );
10985        queue.put(&mut blocked).unwrap();
10986
10987        resolve_blockers(&queue, &questions);
10988
10989        let after = queue.get(&blocked.id).unwrap();
10990        assert_eq!(
10991            after.status,
10992            TaskStatus::Blocked,
10993            "one dependency is still outstanding"
10994        );
10995        assert_eq!(after.blocked_by, [still_going.id.clone()]);
10996    }
10997
10998    #[test]
10999    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
11000        let dir = tempfile::tempdir().unwrap();
11001        let queue = Queue::at(dir.path().join("queue"));
11002        let questions = ask::Questions::at(dir.path().join("questions"));
11003
11004        let mut q = crate::ask::Question::new(
11005            "20260101-000001-main".to_owned(),
11006            crate::conduct::NODE.to_owned(),
11007            "conduct".to_owned(),
11008            "Which backend?".to_owned(),
11009            String::new(),
11010            Vec::new(),
11011        );
11012        questions.put(&mut q).unwrap();
11013        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
11014            .unwrap();
11015        questions.put(&mut q).unwrap();
11016
11017        let mut blocked = task();
11018        blocked.id = "20260101-000001-main".to_owned();
11019        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
11020        queue.put(&mut blocked).unwrap();
11021
11022        resolve_blockers(&queue, &questions);
11023
11024        let after = queue.get(&blocked.id).unwrap();
11025        assert_eq!(
11026            after.status,
11027            TaskStatus::Queued,
11028            "the only blocker resolved"
11029        );
11030        assert_eq!(after.answers.len(), 1);
11031        assert_eq!(after.answers[0].question, "Which backend?");
11032        assert_eq!(after.answers[0].answer, "SQLite");
11033
11034        // And the run this task starts next is told about it.
11035        let instruction = instruction_for(&after);
11036        assert!(instruction.contains("Which backend?"));
11037        assert!(instruction.contains("SQLite"));
11038    }
11039
11040    #[test]
11041    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
11042        let dir = tempfile::tempdir().unwrap();
11043        let queue = Queue::at(dir.path().join("queue"));
11044        let questions = ask::Questions::at(dir.path().join("questions"));
11045
11046        let mut q = crate::ask::Question::new(
11047            "20260101-000001-main".to_owned(),
11048            crate::conduct::NODE.to_owned(),
11049            "conduct".to_owned(),
11050            "Is the setup done?".to_owned(),
11051            String::new(),
11052            Vec::new(),
11053        );
11054        q.abandon("no answer within 60s of asking");
11055        questions.put(&mut q).unwrap();
11056
11057        let mut blocked = task();
11058        blocked.id = "20260101-000001-main".to_owned();
11059        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
11060        queue.put(&mut blocked).unwrap();
11061
11062        resolve_blockers(&queue, &questions);
11063
11064        let after = queue.get(&blocked.id).unwrap();
11065        assert_eq!(
11066            after.status,
11067            TaskStatus::Held,
11068            "never left blocked on nothing"
11069        );
11070        assert!(!after.operator_held(), "a machine hold, for triage");
11071        assert!(
11072            after
11073                .hold_reason
11074                .as_deref()
11075                .unwrap_or_default()
11076                .contains("went unanswered")
11077        );
11078    }
11079
11080    #[test]
11081    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
11082        // Reproduces the reported bug (task 3958): a task held out of
11083        // attempts, blocked on a `crate::conduct` follow-up question, must
11084        // come back `held` once that question is answered - never `queued`,
11085        // whatever the answer said - or it silently re-enters the
11086        // competition queue with its attempts already exhausted.
11087        let dir = tempfile::tempdir().unwrap();
11088        let queue = Queue::at(dir.path().join("queue"));
11089        let questions = ask::Questions::at(dir.path().join("questions"));
11090
11091        let mut q = crate::ask::Question::new(
11092            "20260101-000001-main".to_owned(),
11093            crate::conduct::NODE.to_owned(),
11094            "conduct".to_owned(),
11095            "How should this be handled?".to_owned(),
11096            String::new(),
11097            Vec::new(),
11098        );
11099        questions.put(&mut q).unwrap();
11100        q.answer(crate::ask::Answer::Text(
11101            "leave it held, a human will look at it later".to_owned(),
11102        ))
11103        .unwrap();
11104        questions.put(&mut q).unwrap();
11105
11106        let mut held = task();
11107        held.id = "20260101-000001-main".to_owned();
11108        held.hold_machine(Some("out of attempts".to_owned()));
11109        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
11110        queue.put(&mut held).unwrap();
11111
11112        resolve_blockers(&queue, &questions);
11113
11114        let after = queue.get(&held.id).unwrap();
11115        assert_eq!(after.status, TaskStatus::Held);
11116        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
11117        assert_eq!(
11118            after.answers[0].answer,
11119            "leave it held, a human will look at it later"
11120        );
11121    }
11122
11123    #[test]
11124    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
11125        let dir = tempfile::tempdir().unwrap();
11126        let queue = Queue::at(dir.path().join("queue"));
11127        let questions = ask::Questions::at(dir.path().join("questions"));
11128        let mut dep = task();
11129        dep.id = "20260101-000001-gone".to_owned();
11130        queue.put(&mut dep).unwrap();
11131        let mut blocked = task();
11132        blocked.id = "20260101-000003-main".to_owned();
11133        blocked.block(vec![dep.id.clone()], None);
11134        queue.put(&mut blocked).unwrap();
11135
11136        // Claimed, so `remove` cannot rewrite it and the resolver must.
11137        let claim = queue.claim(&blocked.id).unwrap();
11138        queue.remove(&dep.id, false, &questions).unwrap();
11139        drop(claim);
11140        resolve_blockers(&queue, &questions);
11141
11142        let after = queue.get(&blocked.id).unwrap();
11143        assert_eq!(after.status, TaskStatus::Queued);
11144        assert!(after.blocked_by.is_empty());
11145    }
11146
11147    #[test]
11148    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
11149        // Reproduces the reported bug: a task blocked on a task id that was
11150        // removed (`magi task rm`, or deleted by hand) can never see that id
11151        // reach `Done`, so the ordinary per-id loop has nothing to notice and
11152        // would otherwise leave the task `blocked` forever with no way for an
11153        // operator to find out why.
11154        let dir = tempfile::tempdir().unwrap();
11155        let queue = Queue::at(dir.path().join("queue"));
11156        let questions = ask::Questions::at(dir.path().join("questions"));
11157
11158        let mut still_going = task();
11159        still_going.id = "20260101-000002-dep1".to_owned();
11160        queue.put(&mut still_going).unwrap();
11161
11162        let mut blocked = task();
11163        blocked.id = "20260101-000003-main".to_owned();
11164        blocked.block(
11165            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
11166            Some("waits on both".to_owned()),
11167        );
11168        queue.put(&mut blocked).unwrap();
11169
11170        resolve_blockers(&queue, &questions);
11171
11172        let after = queue.get(&blocked.id).unwrap();
11173        assert_eq!(
11174            after.status,
11175            TaskStatus::Held,
11176            "a missing dependency must not leave the task blocked forever"
11177        );
11178        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
11179        assert!(after.blocked_by.is_empty());
11180        let reason = after.hold_reason.as_deref().unwrap_or_default();
11181        assert!(
11182            reason.contains("20260101-000001-gone"),
11183            "the missing id must be named so an operator can tell what happened: {reason}"
11184        );
11185        assert!(
11186            reason.contains(&still_going.id),
11187            "the still-valid dependency must not silently vanish from the record: {reason}"
11188        );
11189    }
11190
11191    #[test]
11192    fn instruction_for_is_unchanged_without_any_answers() {
11193        let t = task();
11194        assert_eq!(instruction_for(&t), t.instruction);
11195    }
11196
11197    #[test]
11198    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
11199        let dir = tempfile::tempdir().unwrap();
11200        let q = Queue::at(dir.path().join("queue"));
11201        let src = dir.path().join("shot.png");
11202        std::fs::write(&src, "x").unwrap();
11203        let mut t = task();
11204        q.attach(&mut t, &[src]).unwrap();
11205        let paths = task_attachments(&q, &t).unwrap();
11206        assert_eq!(paths.len(), 1);
11207        assert!(paths[0].is_absolute() && paths[0].is_file());
11208        std::fs::remove_file(&paths[0]).unwrap();
11209        let err = task_attachments(&q, &t).unwrap_err().to_string();
11210        assert!(err.contains("shot.png"), "{err}");
11211    }
11212
11213    #[tokio::test]
11214    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
11215        let dir = tempfile::tempdir().unwrap();
11216        let queue_path = dir.path().join("queue");
11217        let queue = Queue::at(queue_path.clone());
11218        let mut t = task();
11219        t.source = Source::Agent {
11220            run: "originating-chat".into(),
11221            node: crate::queue::CHAT_NODE.into(),
11222        };
11223        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
11224            stage: "config-fetch",
11225            target: "origin/main".into(),
11226        });
11227        record_config_failure(&mut t, &fetch);
11228        t.hold_machine(Some(format!("{fetch:#}")));
11229        let fetch_key = t.chat_notice_due().unwrap();
11230        t.chat_notices.push(fetch_key.clone());
11231        queue.put(&mut t).unwrap();
11232
11233        let queue = Queue::at(queue_path);
11234        let mut t = queue.get(&t.id).unwrap();
11235        let a = dir.path().join("a.toml");
11236        let b = dir.path().join("b.toml");
11237        for (path, text, new_cause) in [
11238            (&a, "[graph", true),
11239            (&a, "[verify", false),
11240            (&a, "[graph]\nimplementers = 'invalid-type'", true),
11241            (&b, "[graph]\nimplementers = 'invalid-type'", true),
11242        ] {
11243            t.release_operator("test", None);
11244            std::fs::write(path, text).unwrap();
11245            let error = Config::discover_fetched(dir.path(), Some(path))
11246                .await
11247                .unwrap_err();
11248            record_config_failure(&mut t, &error);
11249            t.hold_machine(Some(format!("{error:#}")));
11250            let due = t.chat_notice_due();
11251            assert_eq!(due.is_some(), new_cause, "{error:#}");
11252            if let Some(key) = due {
11253                assert_ne!(key, fetch_key);
11254                t.chat_notices.push(key);
11255            }
11256        }
11257        t.succeed();
11258        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
11259    }
11260
11261    #[test]
11262    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
11263        let dir = tempfile::tempdir().unwrap();
11264        let queue_path = dir.path().join("queue");
11265        let queue = Queue::at(queue_path.clone());
11266        let mut t = task();
11267        t.source = crate::queue::Source::Agent {
11268            run: "originating-chat".into(),
11269            node: crate::queue::CHAT_NODE.into(),
11270        };
11271        let a = dir.path().join("a.png");
11272        let b = dir.path().join("b.png");
11273        std::fs::write(&a, "a").unwrap();
11274        std::fs::write(&b, "b").unwrap();
11275        queue.attach(&mut t, &[a, b]).unwrap();
11276        let paths = task_attachments(&queue, &t).unwrap();
11277        for path in &paths {
11278            std::fs::remove_file(path).unwrap();
11279        }
11280        let missing = task_attachments(&queue, &t).unwrap_err();
11281        t.attempts += 1;
11282        let reason = missing.to_string();
11283        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11284        let first = t.chat_notice_due().expect("first attachment notice");
11285        t.chat_notices.push(first.clone());
11286        queue.put(&mut t).unwrap();
11287
11288        let queue = Queue::at(queue_path.clone());
11289        let mut t = queue.get(&t.id).unwrap();
11290        assert!(t.chat_notice_due().is_none(), "restart does not replay");
11291        t.release_operator("test", None);
11292        t.attempts += 1;
11293        let missing = task_attachments(&queue, &t).unwrap_err();
11294        t.fail_startup_target(
11295            "startup-attachments",
11296            missing.name,
11297            "same missing attachment with regenerated wording",
11298            1,
11299        );
11300        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
11301
11302        std::fs::write(&paths[0], "restored").unwrap();
11303        t.release_operator("test", None);
11304        t.attempts += 1;
11305        let missing = task_attachments(&queue, &t).unwrap_err();
11306        let reason = missing.to_string();
11307        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
11308        let second = t
11309            .chat_notice_due()
11310            .expect("different attachment must notify");
11311        assert_ne!(first, second);
11312        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
11313    }
11314
11315    #[test]
11316    fn resumed_instruction_is_unchanged_without_any_answers() {
11317        let t = task();
11318        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
11319    }
11320
11321    #[test]
11322    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
11323        let mut t = task();
11324        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11325        // The run's own instruction on disk predates the answer: it is the
11326        // plain original text `Runner::start` saved before the operator was
11327        // ever asked anything.
11328        let old = t.instruction.clone();
11329
11330        let refreshed = resumed_instruction(&old, &t);
11331        assert!(refreshed.starts_with(&old), "the original text is kept");
11332        assert!(refreshed.contains("Which backend?"));
11333        assert!(refreshed.contains("SQLite"));
11334    }
11335
11336    #[test]
11337    fn resumed_instruction_keeps_an_original_answers_heading() {
11338        let mut t = task();
11339        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
11340        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11341
11342        let refreshed = resumed_instruction(&t.instruction, &t);
11343
11344        assert!(
11345            refreshed.starts_with(&t.instruction),
11346            "an answers heading in the original instruction is not the appended block"
11347        );
11348        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
11349        assert!(refreshed.contains("Which backend?"));
11350        assert!(refreshed.contains("SQLite"));
11351
11352        let repeated = resumed_instruction(&refreshed, &t);
11353        assert_eq!(
11354            repeated, refreshed,
11355            "only the final appended block is refreshed"
11356        );
11357    }
11358
11359    #[test]
11360    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
11361        let mut t = task();
11362        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11363
11364        // A first resume appends the block; a second resume of the same run,
11365        // with no new answer in between, must reproduce exactly the same
11366        // text rather than appending the block a second time.
11367        let once = resumed_instruction(&t.instruction, &t);
11368        let twice = resumed_instruction(&once, &t);
11369        assert_eq!(once, twice);
11370        assert_eq!(once.matches("Which backend?").count(), 1);
11371
11372        // A later answer replaces the block wholesale rather than growing it.
11373        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
11374        let refreshed = resumed_instruction(&once, &t);
11375        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
11376        assert!(refreshed.contains("Which backend?"));
11377        assert!(refreshed.contains("Which cache?"));
11378    }
11379
11380    #[test]
11381    fn prepare_instruction_covers_all_three_starters() {
11382        let mut t = task();
11383        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
11384
11385        // Start: a fresh run gets the task text plus every answer so far —
11386        // exactly `instruction_for`.
11387        assert_eq!(
11388            prepare_instruction(&Starter::Start, None, &t),
11389            Some(instruction_for(&t))
11390        );
11391
11392        // Resume: the run's prior instruction is refreshed with the answer,
11393        // not discarded and not left stale.
11394        let old = t.instruction.clone();
11395        assert_eq!(
11396            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
11397            Some(resumed_instruction(&old, &t))
11398        );
11399
11400        // Review: a review-only pass builds its own instruction from the
11401        // branch's history in `crate::graph`, with no task statement at all -
11402        // this boundary must leave it alone.
11403        assert_eq!(
11404            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
11405            None
11406        );
11407    }
11408
11409    #[test]
11410    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
11411        assert_eq!(
11412            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
11413            Starter::Review("magi/eba2/A".to_owned())
11414        );
11415    }
11416
11417    #[test]
11418    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
11419        assert_eq!(
11420            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
11421            Starter::Start,
11422            "a vanished review branch must not fall back to resuming the old run either"
11423        );
11424    }
11425
11426    #[test]
11427    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
11428        let mut t = task();
11429        t.start("old-run".to_owned());
11430        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
11431        t.release();
11432        let branch = t.review_branch.take();
11433        assert_eq!(
11434            choose_starter(branch.as_deref(), true, Some("old-run")),
11435            Starter::Review("magi/eba2/A".to_owned()),
11436            "a review wins over resuming the old run"
11437        );
11438    }
11439
11440    #[test]
11441    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
11442        assert_eq!(
11443            choose_starter(None, false, Some("some-run")),
11444            Starter::Resume("some-run".to_owned())
11445        );
11446        assert_eq!(choose_starter(None, false, None), Starter::Start);
11447    }
11448
11449    #[test]
11450    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
11451        let mut released = task();
11452        released.start("stalled-run".to_owned());
11453        released.requeue();
11454        let unfinished = (!released.fresh_start)
11455            .then(|| Some("stalled-run".to_owned()))
11456            .flatten();
11457        assert_eq!(
11458            choose_starter(None, false, unfinished.as_deref()),
11459            Starter::Start,
11460            "release keeps run history but must not resume it"
11461        );
11462        assert_eq!(released.runs, ["stalled-run"]);
11463    }
11464
11465    fn stopped_public_run(status: RunStatus) -> RunState {
11466        let mut state = run_state(status);
11467        state.driver_exited = true;
11468        state.config.graph.land = true;
11469        state.config.graph.review_rounds = 1;
11470        state.reviews = vec![review_round(1)];
11471        state.merge = Some(crate::run::MergeOutcome {
11472            mode: MergeMode::Pr,
11473            ok: false,
11474            detail: "landing stopped".into(),
11475            empty: false,
11476        });
11477        state.pr = Some(crate::run::PrRecord {
11478            url: "https://example.test/pull/1".into(),
11479            number: 1,
11480            state: "open".into(),
11481            checks: "red".into(),
11482            round: 1,
11483            rounds: 1,
11484            red_at_merge: Vec::new(),
11485        });
11486        state
11487    }
11488
11489    #[test]
11490    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
11491        for status in [RunStatus::Blocked, RunStatus::Gating] {
11492            let home = tempfile::tempdir().unwrap();
11493            let mut state = stopped_public_run(status);
11494            state.save_under(home.path()).unwrap();
11495            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
11496            assert!(!exhausted_review_budget(&state));
11497            let mut task = held_task_with(&state.id);
11498            task.release();
11499            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11500            assert_eq!(
11501                choose_starter(None, false, unfinished.as_deref()),
11502                Starter::Resume(state.id.clone())
11503            );
11504            let question = action_question(&state.id, resume_action(&state.id));
11505            assert_eq!(
11506                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11507                ActionDecision::Resume(state.id.clone())
11508            );
11509            // The control-plane command uses this same preflight before pinning.
11510            assert_eq!(
11511                crate::resume::validate(home.path(), &state.id).unwrap().id,
11512                state.id
11513            );
11514            let queue = Queue::at(home.path().join("queue"));
11515            let mut controlled = Task::new(
11516                "resume land".into(),
11517                state.instruction.clone(),
11518                state.repo.clone(),
11519                Source::Agent {
11520                    run: "talk".into(),
11521                    node: crate::queue::CHAT_NODE.into(),
11522                },
11523            );
11524            controlled.runs.push(state.id.clone());
11525            controlled.hold_machine(Some("land stopped".into()));
11526            queue.put(&mut controlled).unwrap();
11527            let resumed =
11528                crate::chat_control::resume(&queue, home.path(), "talk", &state.id).unwrap();
11529            assert_eq!(resumed.status, TaskStatus::Queued);
11530            assert_eq!(
11531                resumed.resume_override.unwrap().pinned_run,
11532                Some(state.id.clone())
11533            );
11534            assert_eq!(resumed.attempts, 0);
11535        }
11536    }
11537
11538    #[test]
11539    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
11540        for review_rounds in [0, 1] {
11541            let home = tempfile::tempdir().unwrap();
11542            let mut state = run_state(RunStatus::Blocked);
11543            state.config.graph.review_rounds = review_rounds;
11544            if review_rounds > 0 {
11545                let mut review = review_round(1);
11546                review.clean = true;
11547                state.reviews = vec![review];
11548            }
11549            state.gate_ran = true;
11550            state.gate = vec![crate::run::CommandOutcome {
11551                command: "verify".into(),
11552                code: Some(1),
11553                output_tail: "gate failed after repair budget exhausted".into(),
11554                duration_ms: 0,
11555                resource_blocked: false,
11556            }];
11557            state.save_under(home.path()).unwrap();
11558            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11559            assert!(exhausted_review_budget(&state));
11560            let mut task = held_task_with(&state.id);
11561            task.release();
11562            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
11563            let question = action_question(&state.id, resume_action(&state.id));
11564            assert_ne!(
11565                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11566                ActionDecision::Resume(state.id.clone())
11567            );
11568            assert!(crate::resume::validate(home.path(), &state.id).is_err());
11569
11570            // An unexecuted gate still has work to do with or without reviews.
11571            state.gate_ran = false;
11572            state.gate.clear();
11573            assert!(!exhausted_review_budget(&state));
11574            assert_eq!(
11575                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
11576                Some(state.id)
11577            );
11578        }
11579    }
11580
11581    #[test]
11582    fn resource_blocked_verification_resumes_the_same_run() {
11583        for (kind, stage) in [
11584            ("cache", "clean"),
11585            ("coordination", "clean"),
11586            ("cache", "review-e2e"),
11587            ("coordination", "no-reviews"),
11588            ("coordination", "handoff"),
11589        ] {
11590            let home = tempfile::tempdir().unwrap();
11591            let mut state = run_state(RunStatus::Blocked);
11592            state.config.graph.review_rounds = 1;
11593            let mut review = review_round(1);
11594            review.clean = true;
11595            state.reviews = vec![review];
11596            if stage == "review-e2e" {
11597                let review = &mut state.reviews[0];
11598                review.clean = false;
11599                review.blocking = 1;
11600                review.e2e = vec![crate::run::CommandOutcome {
11601                    command: "verify".into(),
11602                    code: None,
11603                    output_tail: "resource wait expired".into(),
11604                    duration_ms: 0,
11605                    resource_blocked: true,
11606                }];
11607            } else if stage == "no-reviews" {
11608                state.config.graph.review_rounds = 0;
11609                state.reviews.clear();
11610            } else if stage == "handoff" {
11611                // A completed final verification can hand off to the gate
11612                // even when the review still carries contested findings.
11613                let review = &mut state.reviews[0];
11614                review.clean = false;
11615                review.blocking = 1;
11616                review.e2e = vec![crate::run::CommandOutcome {
11617                    command: "verify".into(),
11618                    code: Some(0),
11619                    output_tail: String::new(),
11620                    duration_ms: 0,
11621                    resource_blocked: false,
11622                }];
11623            }
11624            state.gate_ran = false;
11625            state.resource_block = Some(crate::run::ResourceBlock {
11626                cause: crate::run::ResourceBlockCause::Other,
11627                node: if stage == "review-e2e" {
11628                    "review"
11629                } else {
11630                    "gate"
11631                }
11632                .into(),
11633                kind: kind.into(),
11634                detail: "resource wait expired".into(),
11635                at: jiff::Timestamp::now(),
11636            });
11637            state.save_under(home.path()).unwrap();
11638            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
11639            assert!(!exhausted_review_budget(&state));
11640            let mut task = held_task_with(&state.id);
11641            task.release();
11642            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
11643            assert_eq!(
11644                choose_starter(None, false, unfinished.as_deref()),
11645                Starter::Resume(state.id.clone())
11646            );
11647            let question = action_question(&state.id, resume_action(&state.id));
11648            assert_eq!(
11649                decide_action(&task, &question, &PHRASES_EN, |_| Ok(state.clone())),
11650                ActionDecision::Resume(state.id.clone())
11651            );
11652            assert_eq!(
11653                crate::resume::validate(home.path(), &state.id).unwrap().id,
11654                state.id
11655            );
11656            let queue = Queue::at(home.path().join("queue"));
11657            let mut controlled = Task::new(
11658                "resume verification".into(),
11659                state.instruction.clone(),
11660                state.repo.clone(),
11661                Source::Agent {
11662                    run: "talk".into(),
11663                    node: crate::queue::CHAT_NODE.into(),
11664                },
11665            );
11666            controlled.runs.push(state.id.clone());
11667            controlled.hold_machine(Some("verification resource unavailable".into()));
11668            queue.put(&mut controlled).unwrap();
11669            let resumed =
11670                crate::chat_control::resume(&queue, home.path(), "talk", &state.id).unwrap();
11671            assert_eq!(resumed.status, TaskStatus::Queued);
11672            assert_eq!(
11673                resumed.resume_override.unwrap().pinned_run,
11674                Some(state.id.clone())
11675            );
11676            assert_eq!(resumed.attempts, 0);
11677
11678            // A genuinely unresolved final review still exhausts the budget.
11679            state.config.graph.review_rounds = 1;
11680            let mut unresolved = review_round(1);
11681            unresolved.blocking = 1;
11682            state.reviews = vec![unresolved];
11683            state.resource_block = None;
11684            state.save_under(home.path()).unwrap();
11685            assert!(exhausted_review_budget(&state));
11686            assert!(crate::resume::validate(home.path(), &state.id).is_err());
11687        }
11688    }
11689
11690    #[tokio::test]
11691    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
11692        if !crate::standalone_test(
11693            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
11694        ) {
11695            return;
11696        }
11697        let home = tempfile::tempdir().unwrap();
11698        let mut owner = stopped_public_run(RunStatus::Blocked);
11699        owner.save_under(home.path()).unwrap();
11700        let history = vec![owner.id.clone()];
11701        let repo = owner.repo.clone();
11702        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
11703        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
11704        let initial =
11705            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
11706        assert!(
11707            initial.is_pending(),
11708            "a busy record must not hold or resume the task"
11709        );
11710        owner.retired_to = Some("20260101-000001-bbbb".into());
11711        owner.save_under(home.path()).unwrap();
11712        drop(lock);
11713        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
11714            .await
11715            .expect("ownership lock released")
11716            .expect("read settled owner");
11717        assert!(
11718            result.is_none(),
11719            "the retired owner must not be resumed from a stale read"
11720        );
11721    }
11722
11723    #[tokio::test]
11724    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
11725        if !crate::standalone_test(
11726            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
11727        ) {
11728            return;
11729        }
11730        let home = tempfile::tempdir().unwrap();
11731        let mut owner = stopped_public_run(RunStatus::Blocked);
11732        let repo = tempfile::tempdir().unwrap();
11733        crate::git::git(repo.path(), &["init"]).await.unwrap();
11734        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
11735        owner.id = "20260101-000000-aaaa".into();
11736        owner.save_under(home.path()).unwrap();
11737        let mut successor = run_state(RunStatus::Blocked);
11738        successor.id = "20260101-000001-bbbb".into();
11739        successor.save_under(home.path()).unwrap();
11740        let runs = vec![owner.id.clone(), successor.id.clone()];
11741        assert_eq!(
11742            public_resume_owner(home.path(), &runs, &owner.repo)
11743                .await
11744                .unwrap()
11745                .unwrap()
11746                .id,
11747            owner.id
11748        );
11749        let subdir = owner.repo.join("nested");
11750        std::fs::create_dir(&subdir).unwrap();
11751        assert_eq!(
11752            public_resume_owner(home.path(), &runs, &subdir)
11753                .await
11754                .unwrap()
11755                .unwrap()
11756                .id,
11757            owner.id
11758        );
11759        #[cfg(unix)]
11760        {
11761            let alias = home.path().join("repo-alias");
11762            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
11763            assert_eq!(
11764                public_resume_owner(home.path(), &runs, &alias.join("nested"))
11765                    .await
11766                    .unwrap()
11767                    .unwrap()
11768                    .id,
11769                owner.id
11770            );
11771        }
11772        let different = tempfile::tempdir().unwrap();
11773        crate::git::git(different.path(), &["init"]).await.unwrap();
11774        assert!(
11775            public_resume_owner(home.path(), &runs, different.path())
11776                .await
11777                .is_err()
11778        );
11779        std::fs::remove_file(
11780            home.path()
11781                .join("runs")
11782                .join(&successor.id)
11783                .join("run.json"),
11784        )
11785        .unwrap();
11786        assert!(
11787            public_resume_owner(home.path(), &runs, &owner.repo)
11788                .await
11789                .is_err()
11790        );
11791    }
11792
11793    #[test]
11794    fn an_ordinary_release_keeps_a_resumable_run_available() {
11795        let mut released = task();
11796        released.start("stalled-run".to_owned());
11797        released.release();
11798        let unfinished = (!released.fresh_start)
11799            .then(|| Some("stalled-run".to_owned()))
11800            .flatten();
11801        assert_eq!(
11802            choose_starter(None, false, unfinished.as_deref()),
11803            Starter::Resume("stalled-run".to_owned()),
11804            "manual release must preserve the normal resume path"
11805        );
11806    }
11807
11808    #[test]
11809    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
11810        let mut state = run_state(RunStatus::Blocked);
11811        state.config.graph.review_rounds = 3;
11812        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
11813        assert!(exhausted_review_budget(&state));
11814
11815        // One round still unused: resuming can still ask a reviewer something.
11816        state.reviews.pop();
11817        assert!(!exhausted_review_budget(&state));
11818
11819        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
11820        // count: only a `Blocked` run re-enters the review loop on resume.
11821        let mut stalled = run_state(RunStatus::Stalled);
11822        stalled.config.graph.review_rounds = 1;
11823        stalled.reviews = vec![review_round(1)];
11824        assert!(!exhausted_review_budget(&stalled));
11825    }
11826
11827    fn review_round(round: usize) -> crate::run::ReviewRound {
11828        crate::run::ReviewRound {
11829            round,
11830            head: "deadbeef".to_owned(),
11831            verified_head: None,
11832            verified_at: None,
11833            reviews: Vec::new(),
11834            e2e: Vec::new(),
11835            verify_retried: false,
11836            e2e_deferred: false,
11837            e2e_defer_reason: None,
11838            fix: None,
11839            blocking: 0,
11840            answered: 1,
11841            expected: 1,
11842            clean: false,
11843            progressed: true,
11844            vote_split: false,
11845            reconsideration: Vec::new(),
11846            verdict: None,
11847        }
11848    }
11849
11850    #[test]
11851    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
11852        let mut run = RunState::new(
11853            PathBuf::from("/repo"),
11854            "main".to_owned(),
11855            "abc1234def".to_owned(),
11856            "add retries".to_owned(),
11857            Config::default(),
11858        );
11859        run.status = RunStatus::Judging;
11860        run.parked = true;
11861        let mut task = Task::new(
11862            "add retries".to_owned(),
11863            "add retries".to_owned(),
11864            PathBuf::from("/repo"),
11865            crate::queue::Source::Human,
11866        );
11867        task.status = TaskStatus::Failed;
11868        task.runs = vec![run.id.clone()];
11869        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
11870        assert!(with(&task, &run), "parked after judging is the case");
11871        let mut parked_task = task.clone();
11872        parked_task.status = TaskStatus::Parked;
11873        assert!(with(&parked_task, &run), "the Parked status is the case");
11874
11875        let mut not_parked = run.clone();
11876        not_parked.parked = false;
11877        not_parked.status = RunStatus::Stalled;
11878        assert!(!with(&task, &not_parked), "a stall is the conductor's");
11879
11880        let mut fresh = task.clone();
11881        fresh.fresh_start = true;
11882        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
11883
11884        let mut review = task.clone();
11885        review.review_branch = Some("magi/x/A".to_owned());
11886        assert!(!with(&review, &run), "review is ranked before resume");
11887
11888        let mut held = task.clone();
11889        held.status = TaskStatus::Held;
11890        assert!(!with(&held, &run), "a hold stays visible to the conductor");
11891
11892        let mut released = run.clone();
11893        released.released_to = Some("20260901-000000-new1".to_owned());
11894        assert!(!with(&task, &released), "nothing left to resume into");
11895
11896        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
11897            "unreadable"
11898        )));
11899    }
11900
11901    #[test]
11902    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
11903        let mut released = RunState::new(
11904            PathBuf::from("/repo"),
11905            "main".to_owned(),
11906            "abc1234def".to_owned(),
11907            "add retries".to_owned(),
11908            Config::default(),
11909        );
11910        released.status = RunStatus::Blocked;
11911        assert_eq!(
11912            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
11913            Some(released.id.clone())
11914        );
11915        released.released_to = Some("20260901-000000-new1".to_owned());
11916        assert_eq!(
11917            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
11918            None,
11919            "there is nothing left to resume it into"
11920        );
11921    }
11922
11923    #[test]
11924    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
11925        // Mirrors the failure this exists to close: a task's last run ended
11926        // `Blocked` with the review budget spent, `crate::conduct` chose
11927        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
11928        // evidence), and without this check `attempt` would go on treating
11929        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
11930        // review loop iterates zero times over an already-spent budget, so
11931        // the resumed run settles right back to `Blocked` having asked nobody
11932        // anything, and `Requeue`'s promised fresh competition never happens.
11933        let mut exhausted = RunState::new(
11934            PathBuf::from("/repo"),
11935            "main".to_owned(),
11936            "abc1234def".to_owned(),
11937            "add retries".to_owned(),
11938            Config::default(),
11939        );
11940        exhausted.status = RunStatus::Blocked;
11941        exhausted.config.graph.review_rounds = 1;
11942        exhausted.reviews = vec![review_round(1)];
11943
11944        assert_eq!(
11945            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
11946            None,
11947            "an exhausted `Blocked` run must not be offered as resumable"
11948        );
11949
11950        // A `Blocked` run with rounds still unused is genuinely worth
11951        // resuming, and must still be found.
11952        let mut has_budget_left = RunState::new(
11953            PathBuf::from("/repo"),
11954            "main".to_owned(),
11955            "abc1234def".to_owned(),
11956            "add retries".to_owned(),
11957            Config::default(),
11958        );
11959        has_budget_left.status = RunStatus::Blocked;
11960        has_budget_left.config.graph.review_rounds = 3;
11961        has_budget_left.reviews = vec![review_round(1)];
11962
11963        assert_eq!(
11964            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
11965                Ok(has_budget_left.clone())
11966            }),
11967            Some(has_budget_left.id.clone())
11968        );
11969    }
11970
11971    #[test]
11972    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
11973        let mut run = RunState::new(
11974            PathBuf::from("/repo"),
11975            "main".to_owned(),
11976            "abc1234def".to_owned(),
11977            "add retries".to_owned(),
11978            Config::default(),
11979        );
11980        run.status = RunStatus::Blocked;
11981        run.config.graph.review_rounds = 1;
11982        run.reviews = vec![review_round(1)];
11983        run.pr_publication_pending = true;
11984        assert_eq!(
11985            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
11986            Some(run.id.clone()),
11987            "a spent review budget must not turn a failed publication into a re-competition"
11988        );
11989    }
11990
11991    #[test]
11992    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
11993        let mut task = Task::new(
11994            "recover work".into(),
11995            "recover work".into(),
11996            PathBuf::from("/repo"),
11997            crate::queue::Source::Human,
11998        );
11999        let mut history = std::collections::BTreeMap::new();
12000        for index in 0..8 {
12001            let mut run = run_state(RunStatus::Blocked);
12002            run.id = format!("20260101-000000-{index:04}");
12003            run.base_commit = format!("upstream-{index}");
12004            // Seven empty newer attempts must not erase the old recovery owner.
12005            if index > 0 {
12006                run.candidates.clear();
12007            }
12008            task.runs.extend([run.id.clone(), run.id.clone()]);
12009            history.insert(run.id.clone(), run);
12010            task.requeue();
12011        }
12012        let check = |task: &Task, starter: &Starter, limit| {
12013            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
12014        };
12015        assert!(
12016            check(&task, &Starter::Start, 8)
12017                .unwrap()
12018                .contains("8 unretired")
12019        );
12020        assert!(check(&task, &Starter::Start, 9).is_none());
12021        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
12022        task.release_operator("owner", None);
12023        assert_eq!(task.attempts, 0);
12024        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
12025        assert!(check(&restored, &Starter::Start, 8).is_some());
12026        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
12027        assert!(check(&restored, &Starter::Start, 0).is_none());
12028    }
12029
12030    #[test]
12031    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
12032        let mut task = Task::new(
12033            "recover work".into(),
12034            "recover work".into(),
12035            PathBuf::from("/repo"),
12036            crate::queue::Source::Human,
12037        );
12038        let mut run = run_state(RunStatus::Superseded);
12039        run.candidates.clear();
12040        task.runs.push(run.id.clone());
12041        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
12042        run.retired_to = Some("authority".into());
12043        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12044        run.retired_to = None;
12045        run.released_to = Some("authority".into());
12046        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
12047        assert!(
12048            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
12049                .unwrap()
12050                .contains("Cannot verify")
12051        );
12052        // Resuming an existing owner needs no new inventory or worktree budget.
12053        assert!(
12054            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
12055                panic!("resume must not load historical attempts")
12056            })
12057            .is_none()
12058        );
12059    }
12060
12061    #[test]
12062    fn retired_resume_requires_a_valid_same_repository_authority() {
12063        let mut source = run_state(RunStatus::Blocked);
12064        let mut empty = run_state(RunStatus::Blocked);
12065        empty.retired_to = Some(source.id.clone());
12066        let runs = vec![source.id.clone(), empty.id.clone()];
12067        let resolve = |source: &RunState, empty: &RunState| {
12068            unfinished_run_with(&runs, "fixture", |id| {
12069                if id == source.id {
12070                    Ok(source.clone())
12071                } else if id == empty.id {
12072                    Ok(empty.clone())
12073                } else {
12074                    bail!("unreadable authority")
12075                }
12076            })
12077        };
12078        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
12079        assert_eq!(
12080            choose_starter(None, false, resolve(&source, &empty).as_deref()),
12081            Starter::Resume(source.id.clone())
12082        );
12083        source.retired_to = Some(empty.id.clone());
12084        assert!(
12085            resolve(&source, &empty).is_none(),
12086            "cycles do not revive obsolete runs"
12087        );
12088        source.retired_to = None;
12089        source.repo = PathBuf::from("/another-repository");
12090        assert!(resolve(&source, &empty).is_none());
12091        source.repo = empty.repo.clone();
12092        source.released_to = Some("later".into());
12093        assert!(resolve(&source, &empty).is_none());
12094        empty.retired_to = Some("unlisted-run".into());
12095        assert!(resolve(&source, &empty).is_none());
12096    }
12097
12098    #[test]
12099    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
12100        // A task whose history holds an *older* run that still looks
12101        // resumable (say, a competition `Runner::review` was started
12102        // alongside after that older run went `Stalled`) and a *newest* run
12103        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
12104        // on this task must mean a fresh competition — falling back to the
12105        // stale, superseded `Stalled` run instead would resurrect history
12106        // nothing asked to revisit and silently defeat the requeue.
12107        let mut older_stalled = RunState::new(
12108            PathBuf::from("/repo"),
12109            "main".to_owned(),
12110            "abc1234def".to_owned(),
12111            "add retries".to_owned(),
12112            Config::default(),
12113        );
12114        older_stalled.status = RunStatus::Stalled;
12115
12116        let mut newest_exhausted = RunState::new(
12117            PathBuf::from("/repo"),
12118            "main".to_owned(),
12119            "abc1234def".to_owned(),
12120            "add retries".to_owned(),
12121            Config::default(),
12122        );
12123        newest_exhausted.status = RunStatus::Blocked;
12124        newest_exhausted.config.graph.review_rounds = 1;
12125        newest_exhausted.reviews = vec![review_round(1)];
12126
12127        assert_eq!(
12128            unfinished_run_with(
12129                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
12130                "t",
12131                |_| Ok(newest_exhausted.clone())
12132            ),
12133            None,
12134            "the newest run is exhausted, so nothing here is worth resuming - \
12135             least of all the older, already-superseded run"
12136        );
12137    }
12138
12139    #[test]
12140    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
12141        assert_eq!(
12142            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
12143                Err(anyhow::anyhow!("fixture is absent"))
12144            }),
12145            None
12146        );
12147    }
12148
12149    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
12150        let mut q = ask::Question::new(
12151            run.to_owned(),
12152            "implement".to_owned(),
12153            "impl-A".to_owned(),
12154            "continue?".to_owned(),
12155            String::new(),
12156            vec!["resume で続行する".to_owned(), "other".to_owned()],
12157        );
12158        q.actions.insert("resume で続行する".to_owned(), action);
12159        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
12160            .unwrap();
12161        q
12162    }
12163
12164    fn held_task_with(run: &str) -> Task {
12165        let mut t = task();
12166        t.runs = vec![run.to_owned()];
12167        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
12168        t
12169    }
12170
12171    fn resume_action(run: &str) -> ask::ChoiceAction {
12172        ask::ChoiceAction::Resume { run: run.into() }
12173    }
12174
12175    #[test]
12176    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
12177        for parked in [false, true] {
12178            let mut t = task();
12179            t.start("A".into());
12180            t.start("B".into());
12181            assert_eq!(t.runs, vec!["A", "B"]);
12182            t.start("A".into());
12183            let mut resumed = run_state(RunStatus::Blocked);
12184            resumed.id = "A".into();
12185            resumed.parked = parked;
12186            resumed.driver_exited = true;
12187            t.hold_machine(Some("resumed run stopped".into()));
12188            let q = action_question("A", resume_action("A"));
12189            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12190            assert_eq!(
12191                decide_action(&t, &q, &PHRASES_EN, |id| {
12192                    assert_eq!(id, "A");
12193                    Ok(resumed.clone())
12194                }),
12195                ActionDecision::Resume("A".into())
12196            );
12197            assert_eq!(
12198                action_standing(&t, &action_question("B", resume_action("B"))),
12199                ActionStanding::Stale
12200            );
12201            t.release_operator("cli", None);
12202            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
12203                assert_eq!(id, "A");
12204                Ok(resumed.clone())
12205            });
12206            assert_eq!(
12207                choose_starter(None, false, unfinished.as_deref()),
12208                Starter::Resume("A".into())
12209            );
12210            assert_eq!(t.runs, vec!["B", "A"]);
12211        }
12212    }
12213
12214    #[test]
12215    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
12216        let mut state = crate::land::tests::repair_state(true, true);
12217        state.status = RunStatus::Landing;
12218        state.parked = true;
12219        state.driver_exited = true;
12220        let mut q = ask::Question::new(
12221            state.id.clone(),
12222            land::APPROVAL_NODE.into(),
12223            "land".into(),
12224            "Merge?".into(),
12225            String::new(),
12226            vec![land::APPROVE.into(), land::HOLD.into()],
12227        );
12228        q.id = state.id.clone();
12229        state.land_approval = Some(crate::run::LandApproval {
12230            question: q.id.clone(),
12231            head: "current-head".into(),
12232        });
12233        assert!(land::upgrade_repair_choice(&mut q, &state));
12234        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12235        let mut task = held_task_with(&state.id);
12236        task.status = TaskStatus::Parked;
12237        assert_eq!(
12238            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12239            ActionDecision::Resume(state.id.clone())
12240        );
12241        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12242        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
12243        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
12244        assert_eq!(
12245            decide_action(&task, &q, &PHRASES_EN, |_| Ok(state.clone())),
12246            ActionDecision::Resume(state.id.clone()),
12247            "a repair answer newer than the manual hold resumes the existing owner"
12248        );
12249        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12250        for answered_at in [q.answered_at, None] {
12251            let mut older = q.clone();
12252            older.answered_at = answered_at;
12253            let refused = decide_action(&task, &older, &PHRASES_EN, |_| {
12254                panic!("a later manual hold must prevent dispatch")
12255            });
12256            let ActionDecision::Refuse(reason) = refused else {
12257                panic!("expected an actionable refusal, got {refused:?}");
12258            };
12259            assert!(reason.contains("later operator decision"));
12260            assert!(reason.contains(&format!("magi task release {}", task.id)));
12261        }
12262        task.operator_decided_at = None;
12263        let mut superseded = state.clone();
12264        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
12265        assert_eq!(
12266            decide_action(&task, &q, &PHRASES_EN, |_| Ok(superseded)),
12267            ActionDecision::Stale
12268        );
12269        for case in 1..4 {
12270            let mut changed = state.clone();
12271            match case {
12272                1 => changed.status = RunStatus::Blocked,
12273                2 => changed.released_to = Some("new-owner".into()),
12274                _ => changed.land_approval.as_mut().unwrap().head.clear(),
12275            }
12276            assert!(matches!(
12277                decide_action(&task, &q, &PHRASES_EN, |_| Ok(changed)),
12278                ActionDecision::Refuse(_)
12279            ));
12280        }
12281        assert!(matches!(
12282            decide_action(&task, &q, &PHRASES_EN, |_| anyhow::bail!("missing owner")),
12283            ActionDecision::Refuse(_)
12284        ));
12285        task.runs.push("replacement".into());
12286        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
12287        assert_eq!(
12288            decide_action(&task, &q, &PHRASES_EN, |_| panic!(
12289                "old owner must not load"
12290            )),
12291            ActionDecision::Stale
12292        );
12293    }
12294
12295    #[test]
12296    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
12297        let mut state = crate::land::tests::repair_state(true, true);
12298        state.status = RunStatus::Landing;
12299        state.parked = true;
12300        state.driver_exited = true;
12301        let mut q = ask::Question::new(
12302            state.id.clone(),
12303            land::APPROVAL_NODE.into(),
12304            "land".into(),
12305            "Merge?".into(),
12306            String::new(),
12307            vec![land::APPROVE.into(), land::HOLD.into()],
12308        );
12309        q.id = state.id.clone();
12310        state.land_approval = Some(crate::run::LandApproval {
12311            question: q.id.clone(),
12312            head: "current-head".into(),
12313        });
12314        state.save().unwrap();
12315        land::upgrade_repair_choice(&mut q, &state);
12316        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12317        Questions::open().put(&mut q).unwrap();
12318        let tmp = tempfile::tempdir().unwrap();
12319        let queue = Queue::at(tmp.path().join("queue"));
12320        let mut task = held_task_with(&state.id);
12321        task.status = TaskStatus::Parked;
12322        queue.put(&mut task).unwrap();
12323        let empty = Arc::new(tokio::sync::Semaphore::new(0));
12324        let free = Arc::new(tokio::sync::Semaphore::new(1));
12325        assert!(claim_dispatch(&queue, &task, false, &empty, &free).is_none());
12326        assert!(claim_dispatch(&queue, &task, true, &free, &free).is_none());
12327        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
12328        assert!(claim.permit.is_some());
12329        assert!(claim_dispatch(&queue, &task, false, &free, &free).is_none());
12330        drop(claim);
12331        Questions::open()
12332            .update(&q.id, |q| {
12333                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
12334                Ok(())
12335            })
12336            .unwrap();
12337        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
12338        assert!(claim.permit.is_none());
12339        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
12340    }
12341
12342    #[test]
12343    fn decide_action_resumes_only_the_latest_resumable_run() {
12344        let t = held_task_with("r1");
12345        let q = action_question("r1", resume_action("r1"));
12346        let load = |s: RunState| move |_: &str| Ok(s);
12347        assert_eq!(
12348            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Blocked))),
12349            ActionDecision::Resume("r1".into())
12350        );
12351        // Not the latest run of the task.
12352        let q_other = action_question("r1", resume_action("r0"));
12353        assert!(matches!(
12354            decide_action(
12355                &t,
12356                &q_other,
12357                &PHRASES_EN,
12358                load(run_state(RunStatus::Blocked))
12359            ),
12360            ActionDecision::Refuse(_)
12361        ));
12362        // A finished run cannot make progress.
12363        assert!(matches!(
12364            decide_action(&t, &q, &PHRASES_EN, load(run_state(RunStatus::Ready))),
12365            ActionDecision::Refuse(_)
12366        ));
12367        // A released one either.
12368        let mut released = run_state(RunStatus::Blocked);
12369        released.released_to = Some("elsewhere".into());
12370        assert!(matches!(
12371            decide_action(&t, &q, &PHRASES_EN, load(released)),
12372            ActionDecision::Refuse(_)
12373        ));
12374        // Unreadable state is a refusal, never a fresh competition.
12375        assert!(matches!(
12376            decide_action(&t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
12377            ActionDecision::Refuse(_)
12378        ));
12379    }
12380
12381    #[test]
12382    fn decide_action_ignores_a_question_about_an_earlier_run() {
12383        let mut t = held_task_with("r1");
12384        t.runs.push("r2".to_owned());
12385        let never = |_: &str| -> Result<RunState> { bail!("not read") };
12386        assert_eq!(
12387            decide_action(
12388                &t,
12389                &action_question("r1", ask::ChoiceAction::Done),
12390                &PHRASES_EN,
12391                never
12392            ),
12393            ActionDecision::Stale
12394        );
12395    }
12396
12397    #[test]
12398    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
12399        let mut t = held_task_with("r1");
12400        let never = |_: &str| -> Result<RunState> { bail!("not read") };
12401        assert_eq!(
12402            decide_action(
12403                &t,
12404                &action_question("r1", ask::ChoiceAction::Requeue),
12405                &PHRASES_EN,
12406                never
12407            ),
12408            ActionDecision::Requeue
12409        );
12410        let done_q = action_question("r1", ask::ChoiceAction::Done);
12411        assert_eq!(
12412            decide_action(&t, &done_q, &PHRASES_EN, never),
12413            ActionDecision::Done
12414        );
12415        t.mark_action_applied(&done_q.id);
12416        assert_eq!(
12417            decide_action(&t, &done_q, &PHRASES_EN, never),
12418            ActionDecision::Skip
12419        );
12420
12421        // A plain answer (no action for that label) does nothing.
12422        let mut plain = action_question("r1", ask::ChoiceAction::Done);
12423        plain.actions.clear();
12424        assert_eq!(
12425            decide_action(&held_task_with("r1"), &plain, &PHRASES_EN, never),
12426            ActionDecision::Skip
12427        );
12428        // A running task is left alone.
12429        let mut running = held_task_with("r1");
12430        running.status = TaskStatus::Running;
12431        assert_eq!(
12432            decide_action(
12433                &running,
12434                &action_question("r1", ask::ChoiceAction::Done),
12435                &PHRASES_EN,
12436                never
12437            ),
12438            ActionDecision::Skip
12439        );
12440    }
12441
12442    #[test]
12443    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
12444        crate::run::pin_test_home();
12445        for legacy in [false, true] {
12446            let dir = tempfile::tempdir().unwrap();
12447            let queue = Queue::at(dir.path().join("queue"));
12448            let questions = Questions::at(dir.path().join("questions"));
12449            let run = "20260101-000000-hold";
12450            let mut task = held_task_with(run);
12451            task.status = TaskStatus::Parked;
12452            let mut q = ask::Question::new(
12453                run.into(),
12454                land::APPROVAL_NODE.into(),
12455                "land".into(),
12456                "Repair?".into(),
12457                String::new(),
12458                vec![land::REPAIR.into()],
12459            );
12460            q.actions.insert(land::REPAIR.into(), resume_action(run));
12461            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
12462            // Deterministically order the answer before the actual manual hold.
12463            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
12464            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
12465            questions.put(&mut q).unwrap();
12466            task.hold_manual(Some("Keep this PR paused".into()));
12467            if legacy {
12468                task.hold_source = None;
12469            }
12470            queue.put(&mut task).unwrap();
12471
12472            apply_task_choice_actions(&queue, &questions, dir.path());
12473            let after = queue.get(&task.id).unwrap();
12474            assert!(after.operator_held());
12475            assert_eq!(after.hold_source, task.hold_source);
12476            assert_eq!(after.operator_decided_at, task.operator_decided_at);
12477            assert_eq!(after.runs, task.runs);
12478            assert_eq!(after.instruction, task.instruction);
12479            assert!(after.resume_override.is_none());
12480            assert!(after.action_applied(&q.id));
12481            let reason = after.hold_reason.as_deref().unwrap();
12482            assert!(reason.starts_with("Keep this PR paused"));
12483            assert!(reason.contains("later operator decision"));
12484            assert!(reason.contains(&format!("magi task release {}", task.id)));
12485
12486            for recovery in [
12487                crate::conduct::Recovery::Review,
12488                crate::conduct::Recovery::Requeue,
12489            ] {
12490                crate::conduct::apply(
12491                    &queue,
12492                    &questions,
12493                    &crate::conduct::Verdict {
12494                        decisions: vec![crate::conduct::Decision {
12495                            id: task.id.clone(),
12496                            recovery: Some(recovery),
12497                            ..Default::default()
12498                        }],
12499                    },
12500                )
12501                .unwrap();
12502            }
12503            // Reconciliation is idempotent, and automatic recovery cannot
12504            // reopen this owner after it observes the rejected repair answer.
12505            apply_task_choice_actions(&queue, &questions, dir.path());
12506            let still_held = queue.get(&task.id).unwrap();
12507            assert!(still_held.operator_held());
12508            assert_eq!(still_held.hold_reason, after.hold_reason);
12509            assert_eq!(still_held.runs, task.runs);
12510            assert!(still_held.review_branch.is_none());
12511            assert!(!still_held.fresh_start);
12512            assert!(queue.next_runnable().is_none());
12513        }
12514    }
12515
12516    #[test]
12517    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
12518        for held in [false, true] {
12519            for retry in [false, true] {
12520                let dir = tempfile::tempdir().unwrap();
12521                let queue = Queue::at(dir.path().join("queue"));
12522                let questions = Questions::at(dir.path().join("questions"));
12523                let home = dir.path().join("home");
12524                let mut t = task();
12525                if held {
12526                    t.hold_machine(Some("driver state unknown".into()));
12527                }
12528                queue.put(&mut t).unwrap();
12529                let verdict = serde_json::from_value(serde_json::json!({
12530                    "decisions": [{
12531                        "id": t.id,
12532                        "question": "Driver state unknown; retry the checks or hold?",
12533                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
12534                        "actions": {
12535                            "daemon: recheck and retry": {"do": "requeue"},
12536                            "daemon: hold the task": {"do": "hold"}
12537                        }
12538                    }]
12539                }))
12540                .unwrap();
12541                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
12542                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12543                let mut q = questions.list().pop().unwrap();
12544                let choice = if retry {
12545                    "daemon: recheck and retry"
12546                } else {
12547                    "daemon: hold the task"
12548                };
12549                assert_eq!(q.actions.len(), 2);
12550                q.answer(ask::Answer::Choice(choice.into())).unwrap();
12551                questions.put(&mut q).unwrap();
12552
12553                // A Web answer does not remove the deputy's fresh lease.
12554                questions.beat(&q.id, ask::WaiterKind::Deputy);
12555                for _ in 0..2 {
12556                    resolve_blockers(&queue, &questions);
12557                    apply_task_choice_actions(&queue, &questions, &home);
12558                    let waiting = queue.get(&t.id).unwrap();
12559                    assert_eq!(waiting.status, TaskStatus::Blocked);
12560                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
12561                    assert!(waiting.answers.is_empty());
12562                    assert!(!waiting.action_applied(&q.id));
12563                    assert!(runnable(&queue).is_empty());
12564                    let free = Arc::new(tokio::sync::Semaphore::new(1));
12565                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_none());
12566                }
12567                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12568
12569                // Releasing the blocker and applying the operation share one save.
12570                resolve_blockers(&queue, &questions);
12571                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
12572                apply_task_choice_actions(&queue, &questions, &home);
12573                let after = queue.get(&t.id).unwrap();
12574                assert_eq!(
12575                    after.status,
12576                    if retry {
12577                        TaskStatus::Queued
12578                    } else {
12579                        TaskStatus::Held
12580                    }
12581                );
12582                assert!(after.action_applied(&q.id));
12583                assert_eq!(after.operator_held(), !retry);
12584                assert_eq!(after.answers.len(), 1);
12585
12586                // A later operator decision must not replay this answer.
12587                let mut changed = after;
12588                if retry {
12589                    changed.hold_manual(Some("later hold".into()));
12590                } else {
12591                    changed.release_operator("test", None);
12592                }
12593                let expected = changed.status;
12594                queue.put(&mut changed).unwrap();
12595                apply_task_choice_actions(&queue, &questions, &home);
12596                assert_eq!(queue.get(&t.id).unwrap().status, expected);
12597            }
12598        }
12599    }
12600
12601    #[test]
12602    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
12603        let dir = tempfile::tempdir().unwrap();
12604        let queue = Queue::at(dir.path().join("queue"));
12605        let questions = Questions::at(dir.path().join("questions"));
12606        let home = dir.path().join("home");
12607        let mut state = run_state(RunStatus::Blocked);
12608        state.id = "20260101-000000-act1".to_owned();
12609        state.save_under(&home).unwrap();
12610
12611        let mut t = held_task_with(&state.id);
12612        queue.put(&mut t).unwrap();
12613        let mut q = action_question(&state.id, resume_action(&state.id));
12614        questions.put(&mut q).unwrap();
12615
12616        apply_task_choice_actions(&queue, &questions, &home);
12617        let after = queue.get(&t.id).unwrap();
12618        assert_eq!(after.status, TaskStatus::Queued);
12619        assert!(!after.fresh_start);
12620        assert!(after.action_applied(&q.id));
12621        let pin = after.resume_override.clone().unwrap();
12622        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
12623        assert!(pin.forced);
12624
12625        // Held again later: the same answer does not release it a second time.
12626        let mut again = queue.get(&t.id).unwrap();
12627        again.hold_machine(Some("later".into()));
12628        queue.put(&mut again).unwrap();
12629        apply_task_choice_actions(&queue, &questions, &home);
12630        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12631    }
12632
12633    #[test]
12634    fn a_delivered_answer_is_still_acted_on_exactly_once() {
12635        let dir = tempfile::tempdir().unwrap();
12636        let queue = Queue::at(dir.path().join("queue"));
12637        let questions = Questions::at(dir.path().join("questions"));
12638        let home = dir.path().join("home");
12639        let mut state = run_state(RunStatus::Blocked);
12640        state.id = "20260101-000000-act2".to_owned();
12641        state.save_under(&home).unwrap();
12642
12643        let mut t = held_task_with(&state.id);
12644        queue.put(&mut t).unwrap();
12645        let mut q = action_question(&state.id, resume_action(&state.id));
12646        q.answer_delivered = true;
12647        questions.put(&mut q).unwrap();
12648
12649        // Delivered, and the agent then died: the task is still held, so the
12650        // chosen action applies.
12651        apply_task_choice_actions(&queue, &questions, &home);
12652        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12653        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
12654
12655        // Held again: the same answer does nothing a second time.
12656        let mut again = queue.get(&t.id).unwrap();
12657        again.hold_machine(Some("later".into()));
12658        queue.put(&mut again).unwrap();
12659        apply_task_choice_actions(&queue, &questions, &home);
12660        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12661    }
12662
12663    #[test]
12664    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
12665        let dir = tempfile::tempdir().unwrap();
12666        let queue = Queue::at(dir.path().join("queue"));
12667        let questions = Questions::at(dir.path().join("questions"));
12668        let home = dir.path().join("home");
12669        let mut state = run_state(RunStatus::Blocked);
12670        state.id = "20260101-000000-act3".to_owned();
12671        state.save_under(&home).unwrap();
12672        let mut t = held_task_with(&state.id);
12673        queue.put(&mut t).unwrap();
12674        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
12675        questions.put(&mut q).unwrap();
12676
12677        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
12678        apply_task_choice_actions(&queue, &questions, &home);
12679        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12680
12681        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
12682        apply_task_choice_actions(&queue, &questions, &home);
12683        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12684    }
12685
12686    #[test]
12687    fn action_standing_tells_the_reasons_apart() {
12688        let mut t = held_task_with("r1");
12689        let q = action_question("r1", ask::ChoiceAction::Requeue);
12690        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
12691        let mut plain = q.clone();
12692        plain.actions.clear();
12693        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
12694
12695        // Applied wins over everything, even a running task.
12696        t.mark_action_applied(&q.id);
12697        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
12698
12699        // A newer attempt running: the old question is Stale, not Busy.
12700        let mut t = held_task_with("r1");
12701        t.start("r2".to_owned());
12702        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
12703        // The same question about the latest run just waits.
12704        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
12705        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
12706        t.status = TaskStatus::Blocked;
12707        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
12708
12709        // A conductor question is keyed by the task, never stale.
12710        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
12711        c.node = crate::conduct::NODE.to_owned();
12712        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
12713        assert!(!ActionStanding::Busy.daemon_owns());
12714    }
12715
12716    #[test]
12717    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
12718        let dir = tempfile::tempdir().unwrap();
12719        let queue = Queue::at(dir.path().join("queue"));
12720        let questions = Questions::at(dir.path().join("questions"));
12721        let home = dir.path().join("home");
12722        let mut state = run_state(RunStatus::Blocked);
12723        state.id = "20260101-000000-act4".to_owned();
12724        state.save_under(&home).unwrap();
12725        let mut t = held_task_with(&state.id);
12726        t.status = TaskStatus::Running;
12727        queue.put(&mut t).unwrap();
12728        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
12729        q.cwd = Some(dir.path().display().to_string());
12730        questions.put(&mut q).unwrap();
12731
12732        // While the task runs the daemon will not act, so the waiter still
12733        // delivers the word to the dead asker's seat ...
12734        let running = queue.get(&t.id).unwrap();
12735        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
12736        assert!(matches!(
12737            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
12738            crate::waiter::Action::Deliver(_)
12739        ));
12740        // ... and the daemon waits while the task runs, then applies once.
12741        apply_task_choice_actions(&queue, &questions, &home);
12742        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
12743        let mut back = queue.get(&t.id).unwrap();
12744        back.hold_machine(Some("later".into()));
12745        queue.put(&mut back).unwrap();
12746        apply_task_choice_actions(&queue, &questions, &home);
12747        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
12748        let mut again = queue.get(&t.id).unwrap();
12749        again.hold_machine(Some("again".into()));
12750        queue.put(&mut again).unwrap();
12751        apply_task_choice_actions(&queue, &questions, &home);
12752        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12753    }
12754}