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::{BuildCache, Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{CompletionActor, CompletionContext, 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    /// Last completed candidate scan that started no tasks; absent otherwise.
137    #[serde(default)]
138    pub dispatch_wait: Option<DispatchWait>,
139    /// Effective startup capabilities of the question recovery loops.
140    #[serde(default)]
141    pub question_recovery: Option<crate::question_delivery::Recovery>,
142    /// Independent-worker control protocol supported by this scheduler.
143    #[serde(default)]
144    pub worker_protocol: Option<u32>,
145}
146
147impl Status {
148    /// A fresh, idle status for this process.
149    #[must_use]
150    pub fn new() -> Self {
151        let now = Timestamp::now();
152        Self {
153            schema: SCHEMA,
154            pid: std::process::id(),
155            started_at: now,
156            updated_at: now,
157            idle: true,
158            current: Vec::new(),
159            completed: 0,
160            polls: 0,
161            dispatch_wait: None,
162            question_recovery: None,
163            worker_protocol: Some(1),
164        }
165    }
166}
167
168impl Default for Status {
169    fn default() -> Self {
170        Self::new()
171    }
172}
173
174/// How the loop should behave.
175#[derive(Debug, Clone, Serialize, Deserialize)]
176#[serde(default)]
177pub struct Opts {
178    /// Repository used by tasks that name none.
179    pub repo: PathBuf,
180    /// Explicit `magi.toml`, instead of the discovered layer stack.
181    pub config: Option<PathBuf>,
182    /// Queue poll interval.
183    pub poll: Duration,
184    /// Attempts a task gets before it is held for a human.
185    pub max_attempts: usize,
186    /// Drain what is runnable now, then return, instead of waiting for more.
187    pub once: bool,
188    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
189    pub merge: Option<String>,
190    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
191    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
192    /// `None` resolves to [`crate::run::default_worktree_root`] - the
193    /// operator's real `~/wt/<repo>` - the same way a run with no
194    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
195    /// that does not own that directory (a test, an embedding that manages
196    /// worktrees itself) must set this, or every idle tick reclaims worktrees
197    /// out from under whoever actually does.
198    pub worktrees_root: Option<PathBuf>,
199}
200
201impl Default for Opts {
202    fn default() -> Self {
203        Self {
204            repo: PathBuf::from("."),
205            config: None,
206            poll: POLL,
207            max_attempts: 2,
208            once: false,
209            merge: None,
210            worktrees_root: None,
211        }
212    }
213}
214
215impl Opts {
216    fn absolute(&self) -> Result<Self> {
217        let mut opts = self.clone();
218        opts.repo = std::path::absolute(&opts.repo)?;
219        opts.config = opts
220            .config
221            .as_deref()
222            .map(std::path::absolute)
223            .transpose()?;
224        opts.worktrees_root = opts
225            .worktrees_root
226            .as_deref()
227            .map(std::path::absolute)
228            .transpose()?;
229        Ok(opts)
230    }
231}
232
233/// How many runs a plain `usize` from config may drive concurrently, floored
234/// at one. A `0` in a config file would otherwise stall the loop entirely -
235/// no runnable task could ever start - which is never what an operator who
236/// wrote `0` meant.
237fn max_concurrent(n: usize) -> usize {
238    n.max(1)
239}
240
241/// Where the status file lives.
242#[must_use]
243pub fn status_path() -> PathBuf {
244    crate::run::home().join("daemon.json")
245}
246
247/// Publish the status file for this process.
248pub fn write_status(status: &Status) -> Result<()> {
249    write_status_to(&status_path(), status)
250}
251
252/// Publish a status to an explicit path.
253///
254/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
255/// on every health poll and must never see a half-written one.
256pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
257    if let Some(parent) = path.parent() {
258        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
259    }
260    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
261    let tmp = path.with_extension("json.tmp");
262    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
263    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
264    Ok(())
265}
266
267/// Delete the status file. Called on the way out so a clean exit reads as
268/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
269pub fn clear_status() {
270    clear_status_at(&status_path());
271}
272
273/// Delete a status file at an explicit path, so the loop's teardown and
274/// [`clear_status`] cannot drift apart: the loop is handed the path it
275/// published to, and a test can watch a temp file disappear.
276fn clear_status_at(path: &Path) {
277    let _ = std::fs::remove_file(path);
278}
279
280/// A cooperative stop, shared with whoever asked the loop to run.
281///
282/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
283/// Ctrl-C listener and the web UI keep others, and every clone points at the
284/// same flag. There is no channel because there is nothing to send — the only
285/// message is "stop", it is idempotent, and a flag cannot be missed by a
286/// receiver that was not listening yet.
287///
288/// A stop ends scheduler dispatch promptly. Its busy snapshot is observational:
289/// detached task workers keep their own lifetimes and ownership after this
290/// handle's scheduler exits.
291#[derive(Debug, Clone, Default)]
292pub struct Stop {
293    /// Set once, never cleared: a stop is not something an operator takes back
294    /// half way through, and a clearable flag would let a start racing a stop
295    /// resurrect a loop that is already unwinding.
296    stopped: Arc<AtomicBool>,
297    /// Live task workers observed by the scheduler's latest dispatch snapshot.
298    busy: Arc<std::sync::atomic::AtomicUsize>,
299    /// Wakes the idle wait. Without this a stop would not be seen until the
300    /// poll interval elapsed, and an operator tapping stop on a phone would
301    /// watch a button do nothing for five seconds.
302    wake: Arc<Notify>,
303    /// Handed to the run in flight, so a stop can also mean "park at the next
304    /// node boundary" instead of "finish the whole competition first".
305    pause: crate::graph::Pause,
306}
307
308impl Stop {
309    /// A stop nobody has asked for yet.
310    #[must_use]
311    pub fn new() -> Self {
312        Self::default()
313    }
314
315    /// Ask the loop to stop. Idempotent, and safe to call before the loop
316    /// starts: the flag is checked before the first poll.
317    pub fn stop(&self) {
318        self.stopped.store(true, Ordering::SeqCst);
319        // `notify_one` rather than `notify_waiters` because the loop may not be
320        // parked yet: this stores a permit, so a wait that registers a moment
321        // later returns at once instead of sleeping out the whole interval.
322        self.wake.notify_one();
323    }
324
325    /// Has a stop been asked for?
326    #[must_use]
327    pub fn stopped(&self) -> bool {
328        self.stopped.load(Ordering::SeqCst)
329    }
330
331    /// Whether a requested scheduler retirement still has an active snapshot.
332    /// Workers continue independently after the scheduler has retired.
333    #[must_use]
334    pub fn finishing(&self) -> bool {
335        self.stopped() && self.busy_now()
336    }
337
338    /// Ask the loop to stop *and* the run in flight to park at its next node
339    /// boundary.
340    ///
341    /// Unlike plain stop, explicit park asks workers to checkpoint at their
342    /// existing safe boundaries. Binary replacement never needs a park.
343    pub fn park(&self, cause: crate::run::ParkCause) {
344        self.pause.park_for(cause);
345        self.stop();
346    }
347
348    /// Has a park been asked for?
349    #[must_use]
350    pub fn parking(&self) -> bool {
351        self.pause.parked()
352    }
353
354    /// The pause handle to give a runner.
355    #[must_use]
356    pub fn pause(&self) -> crate::graph::Pause {
357        self.pause.clone()
358    }
359
360    /// Whether the scheduler's latest snapshot contains active task workers.
361    #[must_use]
362    pub fn busy_now(&self) -> bool {
363        self.busy.load(Ordering::SeqCst) > 0
364    }
365
366    /// Wait out one poll interval, returning early once a stop is asked for.
367    async fn idle(&self, poll: Duration) {
368        tokio::select! {
369            () = tokio::time::sleep(poll) => {}
370            () = self.wake.notified() => {}
371        }
372    }
373}
374
375/// The daemon's published state, read permissively.
376///
377/// This mirrors [`Status`], but is a separate declaration on purpose: every
378/// field defaults, so a status file from an older or newer magi still yields
379/// a usable reading — one this build has never heard of — instead of a parse
380/// error that hides the daemon entirely.
381#[derive(Debug, Clone, Default, Deserialize)]
382#[serde(default)]
383pub struct Reading {
384    /// Format version the daemon claims.
385    pub schema: u32,
386    /// Daemon process id, for an operator who wants to stop it.
387    pub pid: Option<u32>,
388    /// When that process started.
389    pub started_at: Option<Timestamp>,
390    /// Last heartbeat. Absent means the file is unusable, hence not running.
391    pub updated_at: Option<Timestamp>,
392    /// True when the queue had nothing runnable at the last poll.
393    pub idle: bool,
394    /// What the daemon is working on. Empty means idle; more than one entry
395    /// means more than one run is in flight at once.
396    ///
397    /// `deserialize_with` rather than the plain derive: a daemon started
398    /// before this field became a list is still out there writing the old
399    /// shape — a single `{"task":...,"run":...}` object, or its absence —
400    /// on every heartbeat until it is restarted, and a live process reading
401    /// that file during the rollout must still see it as running rather than
402    /// as absent. A bare type change here would fail the whole struct's
403    /// deserialization on a type mismatch, defeating the permissiveness this
404    /// type exists for.
405    #[serde(deserialize_with = "de_current")]
406    pub current: Vec<Current>,
407    /// Tasks this daemon process has finished.
408    pub completed: u64,
409    /// Queue polls this daemon process has made.
410    pub polls: u64,
411    /// Last no-start scan, retaining unknown reason keys from newer writers.
412    pub dispatch_wait: Option<DispatchWait>,
413    /// Effective startup capabilities of the question recovery loops.
414    #[serde(default)]
415    pub question_recovery: Option<crate::question_delivery::Recovery>,
416    /// Independent-worker control protocol, absent on legacy embedded loops.
417    pub worker_protocol: Option<u32>,
418}
419
420/// Accept the old single-`Current`-or-absent shape as well as the current
421/// list, so a reader never has to know which build wrote the file.
422fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
423where
424    D: serde::Deserializer<'de>,
425{
426    #[derive(Deserialize)]
427    #[serde(untagged)]
428    enum Shape {
429        Many(Vec<Current>),
430        One(Current),
431    }
432    Ok(
433        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
434            Shape::Many(v) => v,
435            Shape::One(c) => vec![c],
436        }),
437    )
438}
439
440impl Reading {
441    /// Seconds since the last heartbeat, or `None` when there has never been
442    /// one.
443    #[must_use]
444    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
445        self.updated_at
446            .map(|at| (now.as_second() - at.as_second()).max(0))
447    }
448
449    /// Whether the loop counts as running: a heartbeat no older than
450    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
451    /// progress hours after the daemon that owned it was killed.
452    #[must_use]
453    pub fn running(&self, now: Timestamp) -> bool {
454        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
455    }
456}
457
458/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
459/// usable there.
460///
461/// Missing, half-written and unparseable all collapse to `None`, because the
462/// only question a reader asks is whether a daemon is alive, and a file it
463/// cannot read is not evidence that one is.
464#[must_use]
465pub fn read_status(home: &Path) -> Option<Reading> {
466    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
467    serde_json::from_str(&body).ok()
468}
469
470/// Read-only evidence of runs owned by a live daemon or independent worker.
471///
472/// CLI, sandboxed conversation controls and Web cleanup share this observation.
473/// A stale daemon heartbeat does not invalidate a worker's OS-held lease.
474/// Starting reservations and unknown worker state remain protected; observing
475/// them never creates, reconciles or archives files in the worker store.
476/// Callers interested in one identity use [`is_working_on`] or
477/// [`is_working_on_task`].
478#[must_use]
479pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
480    let mut current = read_status(home)
481        .filter(|reading| reading.running(now))
482        .map(|reading| reading.current)
483        .unwrap_or_default();
484    let workers = crate::worker::observe_active(home).and_then(|jobs| {
485        jobs.into_iter()
486            .filter(|job| job.kind == "task")
487            .map(|job| {
488                let request: TaskWorker = serde_json::from_value(job.payload)?;
489                let run = Queue::at(request.queue)
490                    .get(&request.task)
491                    .ok()
492                    .and_then(|task| task.execution_runs().last().cloned())
493                    .unwrap_or_default();
494                Ok(Current {
495                    worker: Some(job.id),
496                    task: request.task,
497                    run,
498                })
499            })
500            .collect::<Result<Vec<_>>>()
501    });
502    match workers {
503        Ok(workers) => {
504            for worker in workers {
505                if !current.iter().any(|claim| {
506                    claim.task == worker.task
507                        && claim.run == worker.run
508                        && claim.worker == worker.worker
509                }) {
510                    current.push(worker);
511                }
512            }
513        }
514        Err(error) => {
515            // This API gates destructive cleanup. Unknown worker ownership
516            // protects every known task/run instead of pretending it is idle.
517            tracing::error!("cannot determine active workers: {error:#}");
518            current.extend(
519                Queue::at(home.join("queue"))
520                    .list()
521                    .into_iter()
522                    .map(|task| Current {
523                        worker: None,
524                        task: task.id.clone(),
525                        run: task.execution_runs().last().cloned().unwrap_or_default(),
526                    }),
527            );
528            current.extend(
529                crate::run::list_ids_in(&home.join("runs"))
530                    .into_iter()
531                    .map(|run| Current {
532                        worker: None,
533                        task: String::new(),
534                        run,
535                    }),
536            );
537        }
538    }
539    current
540}
541
542/// Whether a live daemon is working on this run at this moment.
543#[must_use]
544pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
545    current_work(home, now).iter().any(|c| c.run == run)
546}
547
548/// Admission may ignore only this process's confirmed worker reservation.
549/// Keep anonymous/legacy daemon claims and every other worker, even for the
550/// same task. The run's execution lease and process identity are checked by
551/// the caller under the owner lock as well.
552pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
553    // A helper or test may inherit an identity from a different run store.
554    // That identity grants no exception here; retain all ownership evidence.
555    let same_home = std::env::var_os("MAGI_WORKER_HOME")
556        .is_some_and(|worker_home| Path::new(&worker_home) == home);
557    let caller = if same_home {
558        crate::worker::current_job(home)?
559    } else {
560        None
561    }
562    .filter(|job| {
563        job.kind == "task"
564            && job.status == crate::worker::Status::Running
565            && job.pid == Some(std::process::id())
566    });
567    Ok(other_claims_run(
568        &current_work(home, now),
569        run,
570        caller.as_ref().map(|job| job.id.as_str()),
571    ))
572}
573
574fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
575    claims
576        .iter()
577        .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
578}
579
580/// Whether a live daemon is working on a run whose short id is this one.
581///
582/// For a worktree that has no run record to compare against at all -
583/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
584/// id is not available to hand to [`is_working_on`]. The short id is: a run's
585/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
586/// and it is exactly the gap between the daemon claiming a task and
587/// `RunState::new` saving the first `run.json` that this exists to protect -
588/// a run genuinely in flight but invisible to a scan of `runs/`.
589#[must_use]
590pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
591    current_work(home, now)
592        .iter()
593        .any(|c| crate::run::short_of(&c.run) == short)
594}
595
596/// Whether a live daemon is working on this task at this moment.
597#[must_use]
598pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
599    current_work(home, now).iter().any(|c| c.task == task)
600}
601
602/// Remove claim files whose owner is provably dead, or that have simply
603/// outlived `older_than`, and return the task ids swept.
604///
605/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
606/// destructor, and the orphaned `.lock` file would make its task permanently
607/// unclaimable — the backlog would stop for good at exactly the task that was
608/// in flight when the machine went down.
609///
610/// The pid recorded in the lock is the authority whenever it can be read at
611/// all; age is only a fallback for when it cannot be.
612///
613/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
614///   full stop — dead sweeps the lock immediately, regardless of age; alive
615///   protects it, regardless of age. This is what lets a lock be reclaimed in
616///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
617///   before this daemon even started, next to a `queued` task, no longer has
618///   to sit for six hours before anything notices its owner is gone.
619/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
620///   falls back to `older_than`, since there is nothing else to check.
621///
622/// Age must never override a *positive* liveness confirmation. `sweep`
623/// polls concurrently with independently running task workers. A worker may
624/// legitimately run longer than `older_than`; its live pid must still protect
625/// its claim. Age alone must never turn that claim into a second task attempt,
626/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
627/// to a second attempt — two `Runner`s writing the same `run.json` and the
628/// same worktree at once. `pid_alive` answering "alive" for anything it
629/// cannot determine (a live process, a pid this build cannot check, one
630/// under another account) is exactly what keeps that path from ever
631/// firing on a guess.
632///
633/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
634/// output unreadable must not be license to guess, and the risk of an
635/// unparseable lock outliving a genuinely dead owner is bounded by an order
636/// of magnitude above any plausible run rather than by a positive check.
637///
638/// Runs on every poll, not only at startup — a daemon up for days must keep
639/// noticing a lock some other, now-dead, daemon left behind just as readily
640/// as one it trips over on the way up.
641pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
642    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
643}
644
645/// [`sweep_stale_claims`] with its process-query boundary supplied by the
646/// caller. This keeps the lock policy testable where process listing is
647/// unavailable, while production still uses the platform query above.
648fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
649where
650    F: Fn(u32) -> bool,
651{
652    let this_process = std::process::id();
653    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
654        .into_iter()
655        .flatten()
656        .flatten()
657        .map(|e| e.path())
658        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
659        .filter(|p| {
660            match std::fs::read_to_string(p)
661                .ok()
662                .and_then(|body| body.trim().parse::<u32>().ok())
663            {
664                // This process wrote it and is asking the question right
665                // now, so it is definitionally still alive - settled without
666                // spawning a helper process at all.
667                Some(pid) if pid == this_process => false,
668                Some(pid) => !pid_alive(pid),
669                None => p
670                    .metadata()
671                    .and_then(|m| m.modified())
672                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
673                    .is_ok_and(|age| age >= older_than),
674            }
675        })
676        .filter(|p| std::fs::remove_file(p).is_ok())
677        .filter_map(|p| {
678            p.file_stem()
679                .and_then(|s| s.to_str())
680                .map(std::borrow::ToOwned::to_owned)
681        })
682        .collect();
683    swept.sort_unstable();
684    swept
685}
686
687/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
688/// no live daemon's heartbeat naming it? Deterministic — no model call, and
689/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
690/// shown.
691fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
692    task.status == TaskStatus::Running
693        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
694        && !is_working_on_task(home, &task.id, now)
695}
696
697/// Every task [`is_stalled`] right now — "止まったタスク" in
698/// `crate::conduct`'s vocabulary.
699fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
700    queue
701        .list()
702        .into_iter()
703        .filter(|t| is_stalled(t, home, now))
704        .collect()
705}
706
707/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
708/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
709/// `Failed`-and-so-also-runnable: a task that already attempted and lost
710/// belongs in [`finished_tasks`], where the question is a recovery, not a
711/// dependency.
712fn queued_tasks(queue: &Queue) -> Vec<Task> {
713    queue
714        .list()
715        .into_iter()
716        .filter(|t| t.status == TaskStatus::Queued)
717        .collect()
718}
719
720/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
721/// タスク" in `crate::conduct`'s vocabulary.
722fn finished_tasks(queue: &Queue) -> Vec<Task> {
723    queue
724        .list()
725        .into_iter()
726        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
727        .collect()
728}
729
730/// Deterministically resolve `Task::blocked_by`: a dependency task that
731/// reached `Done`, or a question that was answered, is removed — no model
732/// involved, on every poll. An answered question's content is copied onto
733/// the task ([`Task::record_answer`]) before its id is dropped, so it
734/// reaches the next `crate::conduct` prompt and the next run's instruction
735/// (see [`instruction_for`]) rather than only clearing the block.
736///
737/// A `blocked_by` id that names neither an existing task nor an existing
738/// question - `magi task rm` (or an operator by hand) deleted it while this
739/// task was still waiting - is caught before any of that: it can never
740/// become `Done` or `Answered`, so the ordinary loop below would otherwise
741/// leave the task `blocked` forever with nothing to notice. Such a task is
742/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
743/// which puts it in front of `crate::triage::run_once`'s own walk the next
744/// time it runs - see that module's doc for why the choice is "ask a human",
745/// never "assume the missing dependency was satisfied and unblock anyway".
746fn resolve_blockers(queue: &Queue, questions: &Questions) {
747    for listed in queue.list() {
748        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
749            continue;
750        }
751        let Ok(_claim) = queue.claim(&listed.id) else {
752            continue;
753        };
754        let Ok(mut task) = queue.get(&listed.id) else {
755            continue;
756        };
757        if task.status != TaskStatus::Blocked {
758            continue;
759        }
760        // A dependency deleted on purpose is released, not held - and before
761        // the missing check, so a pass that races the delete (or a claim that
762        // made `Queue::remove` skip this task) settles it quietly.
763        let deleted = queue.apply_deleted_blockers(&mut task, questions);
764        if !deleted.is_empty() {
765            record(queue, &mut task);
766            for id in &deleted {
767                queue.note_dependency_deleted(&task, id);
768            }
769            if task.status != TaskStatus::Blocked {
770                continue;
771            }
772        }
773        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
774        if !missing.is_empty() {
775            let language = language_of(&task, Path::new("."));
776            let mut cause = missing.clone();
777            cause.sort();
778            cause.dedup();
779            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
780            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
781                &task.blocked_by,
782                &missing,
783                &language,
784            )));
785            record(queue, &mut task);
786            continue;
787        }
788        // A conductor question nobody answered in time is retired by the
789        // waiter, and nothing else would ever move the task it blocks.
790        if let Some(q) = task.blocked_by.iter().find_map(|id| {
791            let crate::queue::Dependency::Question(full) =
792                crate::queue::dependency(queue, questions, id)
793            else {
794                return None;
795            };
796            questions.get_for_effects(&full).ok().filter(|q| {
797                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
798            })
799        }) {
800            let language = language_of(&task, Path::new("."));
801            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
802            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
803            record(queue, &mut task);
804            continue;
805        }
806        let mut changed = false;
807        for id in task.blocked_by.clone() {
808            let resolved = crate::queue::dependency(queue, questions, &id);
809            if let crate::queue::Dependency::Task(full) = &resolved {
810                if queue
811                    .get(full)
812                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
813                {
814                    task.unblock(&id);
815                    changed = true;
816                }
817                continue;
818            }
819            if let crate::queue::Dependency::Question(full) = resolved
820                && let Ok(q) = questions.get_for_effects(&full)
821                && q.status == ask::QuestionStatus::Answered
822            {
823                // The action sweep releases conductor blockers atomically
824                // with their selected operation. A fresh deputy lease must
825                // never leave an answered hold temporarily runnable.
826                if q.node == crate::conduct::NODE
827                    && q.chosen_action().is_some()
828                    && !task.action_applied(&q.id)
829                {
830                    continue;
831                }
832                let answer = match &q.answer {
833                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
834                    None => String::new(),
835                };
836                task.record_answer(q.summary.clone(), answer);
837                task.unblock(&id);
838                changed = true;
839            }
840        }
841        if changed {
842            record(queue, &mut task);
843        }
844    }
845}
846
847/// The `hold_reason` of a task whose conductor question went unanswered.
848fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
849    if crate::lang::is_japanese(language) {
850        format!(
851            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
852            q.short(),
853            q.summary
854        )
855    } else {
856        format!(
857            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
858            q.short(),
859            q.summary
860        )
861    }
862}
863
864/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
865/// for several unrelated reasons, and the waiter must not read them alike.
866#[derive(Debug, Clone, Copy, PartialEq, Eq)]
867pub(crate) enum ActionStanding {
868    /// The answer carries no action: the waiter delivers it as before.
869    NoAction,
870    /// The daemon will apply it (not applied, task idle, current attempt).
871    Pending,
872    /// Already applied (`Task::actions_applied`): the daemon has acted, so
873    /// delivering the word to the old seat would run it beside the new work.
874    Applied,
875    /// The question is about an earlier attempt than the task's latest.
876    Stale,
877    /// The task is running / blocked / done: the daemon defers for now.
878    Busy,
879}
880
881impl ActionStanding {
882    /// The daemon has acted or will act: the waiter must not deliver.
883    pub(crate) fn daemon_owns(self) -> bool {
884        matches!(self, Self::Pending | Self::Applied | Self::Stale)
885    }
886}
887
888/// Classify `q`'s chosen action against `task`. `Stale` is judged before
889/// `Busy`: a question about an earlier attempt must be stopped even while a
890/// newer competition is running.
891pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
892    if task.stale_question(q) {
893        ActionStanding::Stale
894    } else if q.chosen_action().is_none() {
895        ActionStanding::NoAction
896    } else if task.action_applied(&q.id) {
897        ActionStanding::Applied
898    } else if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
899        ActionStanding::Stale
900    } else if matches!(
901        task.status,
902        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
903    ) {
904        ActionStanding::Busy
905    } else {
906        ActionStanding::Pending
907    }
908}
909
910/// What [`decide_action`] concluded about one answered question.
911#[derive(Debug, Clone, PartialEq, Eq)]
912enum ActionDecision {
913    /// Nothing to do now (no action, already applied, or the task is busy).
914    Skip,
915    /// Continue the named run instead of competing again.
916    Resume(String),
917    /// Requeue as a fresh competition.
918    Requeue,
919    /// Hold the task by explicit operator choice.
920    Hold,
921    /// Close the task as done.
922    Done,
923    /// The question is about an earlier attempt than the task's latest; it
924    /// is recorded as handled and changes nothing.
925    Stale,
926    /// The action cannot be carried out; hold the task and say why. Never
927    /// falls back to something else, because the operator chose this one.
928    Refuse(String),
929}
930
931/// Decide what the choice answered on `q` means for `task`. `load` reads a
932/// run's state, as with [`unfinished_run_with`]. `home` must name that same
933/// store for driver leases and question checkpoints.
934///
935/// `Resume` only fires on the task's *latest* run, and only while that run
936/// could actually make progress ([`RunStatus::resumable`], not released, review
937/// budget left); an answer naming anything else is refused rather than
938/// reinterpreted as a fresh competition.
939fn decide_action<F>(
940    home: &Path,
941    task: &Task,
942    q: &ask::Question,
943    p: &Phrases,
944    load: F,
945) -> ActionDecision
946where
947    F: FnOnce(&str) -> Result<RunState>,
948{
949    if task.stale_question(q) {
950        return ActionDecision::Stale;
951    }
952    let Some(action) = q.chosen_action() else {
953        return ActionDecision::Skip;
954    };
955    if task.action_applied(&q.id)
956        || matches!(
957            task.status,
958            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
959        )
960    {
961        return ActionDecision::Skip;
962    }
963    // A question about an earlier attempt must not act on a newer one. A
964    // conductor question is keyed by the task id, not a run, so it is exempt.
965    if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
966        return ActionDecision::Stale;
967    }
968    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
969    let stopping = q.node == land::APPROVAL_NODE
970        && q.resolution()
971            .as_deref()
972            .is_some_and(crate::merge_decision::stops);
973    // An answer is the owner's decision as of when it was given: a manual hold
974    // placed before it (even after the question was asked) was seen and
975    // overruled by it, while a hold or release after it supersedes it.
976    let decision_at = q.answered_at.unwrap_or(q.asked_at);
977    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
978        return if repair || stopping {
979            ActionDecision::Refuse(format!(
980                "{} 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 {}`",
981                if repair { "repair" } else { "stop" },
982                q.id,
983                q.run,
984                task.id
985            ))
986        } else {
987            ActionDecision::Stale
988        };
989    }
990    match action {
991        a if a.maintenance() => ActionDecision::Skip,
992        ask::ChoiceAction::RecoverBase { .. }
993        | ask::ChoiceAction::ResumeRun { .. }
994        | ask::ChoiceAction::ReleaseTask { .. }
995        | ask::ChoiceAction::RerunChecks { .. }
996        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
997        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
998        ask::ChoiceAction::Hold => ActionDecision::Hold,
999        ask::ChoiceAction::Done => ActionDecision::Done,
1000        ask::ChoiceAction::Resume { run } => {
1001            if task.execution_runs().last() != Some(run) {
1002                return ActionDecision::Refuse((p.resume_not_latest)(
1003                    q.short(),
1004                    ask::short_id(run),
1005                ));
1006            }
1007            match load(run) {
1008                Ok(s) if stopping => {
1009                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1010                        || !s
1011                            .land_approval
1012                            .as_ref()
1013                            .is_some_and(|binding| binding.question == q.id)
1014                    {
1015                        ActionDecision::Stale
1016                    } else if s.liveness_under(home, false) == Liveness::Live {
1017                        ActionDecision::Skip
1018                    } else if s.status == RunStatus::Landing
1019                        && !s.released()
1020                        && s.retired_to.is_none()
1021                    {
1022                        ActionDecision::Resume(run.clone())
1023                    } else {
1024                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1025                    }
1026                }
1027                Ok(s)
1028                    if q.node == land::APPROVAL_NODE
1029                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1030                {
1031                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1032                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1033                    {
1034                        // A live/manual driver already consumed or superseded
1035                        // this answer. Do not hold its fresh approval wait.
1036                        ActionDecision::Stale
1037                    } else if s.liveness_under(home, false) == Liveness::Live {
1038                        ActionDecision::Skip
1039                    } else if s.status != RunStatus::Landing
1040                        || s.released()
1041                        || s.reviews.is_empty()
1042                        || !implementers_match(task, &s)
1043                        || !s
1044                            .land_approval
1045                            .as_ref()
1046                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1047                    {
1048                        ActionDecision::Refuse(format!(
1049                            "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",
1050                            q.id, run, run
1051                        ))
1052                    } else {
1053                        ActionDecision::Resume(run.clone())
1054                    }
1055                }
1056                Ok(s) if s.liveness_under(home, false) == Liveness::Live => {
1057                    ActionDecision::Refuse("run already has a live driver".into())
1058                }
1059                Ok(s) => match crate::handover::resume_refusal_under(&s, Some(home)) {
1060                    None => ActionDecision::Resume(run.clone()),
1061                    Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1062                        q.short(),
1063                        ask::short_id(run),
1064                        &reason.diagnostic(&s),
1065                    )),
1066                },
1067                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1068                    q.short(),
1069                    ask::short_id(run),
1070                    &format!("{e:#}"),
1071                )),
1072            }
1073        }
1074    }
1075}
1076
1077/// The fixed prose the daemon writes into [`Task::last_error`] and
1078/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1079/// `triage::Wording` and `land::Words`: only English and Japanese are
1080/// translated, anything else falls back to English.
1081///
1082/// Rendered when the reason is *generated*, so a reason keeps the language it
1083/// was written in if the setting changes later. The notification frame
1084/// (`Task <id> is held:`) is not here and stays English.
1085///
1086/// Deliberately **not** translated, because other code reads them back by
1087/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1088/// and `gate red`. IDs, node names, paths and external error text are embedded
1089/// as they are.
1090struct Phrases {
1091    /// `{}` = status label, then the detail.
1092    graph_stopped: fn(&str, &str) -> String,
1093    quorum_lost: &'static str,
1094    /// Followed by the seats' names.
1095    quota_took_out: &'static str,
1096    /// Followed by the status label.
1097    run_ended: &'static str,
1098    /// Followed by the question's short id.
1099    waiting_for_answer: &'static str,
1100    recovered_running: &'static str,
1101    no_run_to_recover: &'static str,
1102    could_not_start: &'static str,
1103    resume_not_latest: fn(&str, &str) -> String,
1104    resume_cannot_progress: fn(&str, &str, &str) -> String,
1105    resume_unreadable: fn(&str, &str, &str) -> String,
1106    /// A takeover refusal: the operator-facing text. English is the error's own
1107    /// `Display`; a translation keeps the machine detail apart in parentheses.
1108    handover_refused: fn(&crate::handover::Refused) -> String,
1109    /// Appended to a refused handover's hold reason (leading space included).
1110    handover_hint: &'static str,
1111    /// (seats that never answered, review rounds) for the review loop's
1112    /// "refusing to call it clean" stop.
1113    reviewers_never_answered: fn(usize, usize) -> String,
1114}
1115
1116const PHRASES_EN: Phrases = Phrases {
1117    graph_stopped: |status, detail| {
1118        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1119    },
1120    quorum_lost: "the judging panel lost its quorum",
1121    quota_took_out: "; quota took out ",
1122    run_ended: "run ended ",
1123    waiting_for_answer: " - waiting for operator answer to question ",
1124    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1125    no_run_to_recover: "task was `running` with no live daemon and no readable \
1126                        run to recover; held for a human to check what happened",
1127    could_not_start: "could not start the run: ",
1128    resume_not_latest: |q, run| {
1129        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1130    },
1131    resume_cannot_progress: |q, run, reason| {
1132        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1133    },
1134    resume_unreadable: |q, run, e| {
1135        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1136    },
1137    handover_refused: |r| r.to_string(),
1138    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1139    reviewers_never_answered: |missing, rounds| {
1140        format!(
1141            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1142             refusing to call it clean"
1143        )
1144    },
1145};
1146
1147const PHRASES_JA: Phrases = Phrases {
1148    graph_stopped: |status, detail| {
1149        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1150    },
1151    quorum_lost: "審査パネルが定足数を失いました",
1152    quota_took_out: "。クォータで脱落: ",
1153    run_ended: "run 終了: ",
1154    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1155    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1156    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1157                        何が起きたか人が確認するため保留にしました",
1158    could_not_start: "run を開始できませんでした: ",
1159    resume_not_latest: |q, run| {
1160        format!(
1161            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1162        )
1163    },
1164    resume_cannot_progress: |q, run, reason| {
1165        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1166    },
1167    resume_unreadable: |q, run, e| {
1168        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1169    },
1170    handover_refused: |r| {
1171        use crate::handover::Refused;
1172        match r {
1173            Refused::Foreign { branch, path, why } => format!(
1174                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1175                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1176                 から、やり直してください(詳細: {why})"
1177            ),
1178            Refused::Unsafe { branch, path, why } => format!(
1179                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1180                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1181                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1182            ),
1183            Refused::ReleaseFailed { branch, path, run } => format!(
1184                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1185                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1186                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1187            ),
1188        }
1189    },
1190    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1191    reviewers_never_answered: |missing, rounds| {
1192        format!(
1193            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1194             クリーンとは認めません"
1195        )
1196    },
1197};
1198
1199fn phrases(language: &str) -> &'static Phrases {
1200    if crate::lang::is_japanese(language) {
1201        &PHRASES_JA
1202    } else {
1203        &PHRASES_EN
1204    }
1205}
1206
1207/// The language of the repository a task belongs to, read best-effort for the
1208/// paths that have no run (and so no config of their own) to ask. An unreadable
1209/// config is English, not an error: a hold reason must still get written.
1210fn language_of(task: &Task, fallback: &Path) -> String {
1211    crate::lang::of_repo(&repo_for(task, fallback))
1212}
1213
1214/// The task an answered question speaks for: the one whose runs include the
1215/// question's run, or - for a conductor question, filed under the task's own
1216/// id - the task with that id.
1217pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1218    if q.node == crate::conduct::NODE {
1219        return tasks.iter().find(|t| t.id == q.run);
1220    }
1221    tasks.iter().find(|t| t.runs.contains(&q.run))
1222}
1223
1224/// Legacy conductor prose never becomes a maintenance command by inference.
1225/// Replace unsupported open labels under the question lock before dispatch.
1226fn repair_choice_offers(questions: &Questions) {
1227    let ownership = crate::task_chat::InquiryOwnership::default();
1228    for q in questions
1229        .list_for_effects_in(&ownership)
1230        .into_iter()
1231        .filter(|q| {
1232            q.status.open()
1233                && q.node == crate::conduct::NODE
1234                && q.choices
1235                    .iter()
1236                    .any(|c| crate::choice_effect::describe(q, c).is_none())
1237        })
1238    {
1239        let _ = questions.update_in(&q.id, &ownership, |current| {
1240            if current.status.open() {
1241                crate::choice_effect::executable_conductor(current);
1242                if let Some(deputy) = &mut current.deputy {
1243                    deputy.brief = crate::deputy::brief(
1244                        &current.run,
1245                        &current.detail,
1246                        &current.choices,
1247                        &current.actions,
1248                    );
1249                }
1250            }
1251            Ok(())
1252        });
1253    }
1254}
1255
1256/// Apply answered typed choices. Only the daemon calls this in production;
1257/// deputies settle the question and never execute its actions.
1258pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1259    apply_maintenance_choices(queue, questions, home).await;
1260    apply_task_choice_actions(queue, questions, home);
1261}
1262
1263/// Apply bounded maintenance effects independently of question ownership: a
1264/// release watcher need not have a queue task, and a predecessor is another run.
1265async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1266    let ownership = crate::task_chat::InquiryOwnership::default();
1267    for q in questions.list_for_effects_in(&ownership) {
1268        // Read again under the same fence used by explicit settlement.
1269        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1270            continue;
1271        };
1272        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1273            continue;
1274        };
1275        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1276            continue;
1277        };
1278        // Receipt paths use question IDs, whose format is independent of run
1279        // IDs. Apply the question store's filename safety rule to both eras.
1280        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1281            continue;
1282        }
1283        if queue.list().iter().any(|task| {
1284            (task.id == q.run
1285                || task.runs.contains(&q.run)
1286                || q.routed_task.as_deref() == Some(&task.id))
1287                && task.stale_question(&q)
1288        }) {
1289            continue;
1290        }
1291        if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1292            let tasks = queue.list();
1293            let owner = crate::task_chat::task_of(&q, &tasks);
1294            if let Some(owner) = owner
1295                && q.routed_task
1296                    .as_deref()
1297                    .is_none_or(|routed| routed == owner)
1298            {
1299                let result = crate::base_recovery_control::recover(
1300                    queue,
1301                    home,
1302                    crate::base_recovery_control::Request {
1303                        run: run.clone(),
1304                        head: stop.head.clone(),
1305                        actor: "decisions".into(),
1306                        request: q.id.clone(),
1307                        decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1308                        expected_stop: Some((stop.clone(), *episode)),
1309                    },
1310                )
1311                .await;
1312                if let Err(error) = result {
1313                    tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1314                    notices::raise_in(home, Notice::warn(
1315                        &format!("base-recovery:{}", q.id),
1316                        format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1317                    ).link(Link::Run { id: run.clone() }));
1318                }
1319            }
1320            continue;
1321        }
1322        let dir = home.join("choice-actions");
1323        if std::fs::create_dir_all(&dir).is_err() {
1324            continue;
1325        }
1326        let Ok(lock) = std::fs::OpenOptions::new()
1327            .create(true)
1328            .truncate(false)
1329            .write(true)
1330            .open(dir.join(format!("{}.lock", q.id)))
1331        else {
1332            continue;
1333        };
1334        if crate::pr_head::try_lock_file(&lock).is_err() {
1335            continue;
1336        }
1337        let fresh = !home
1338            .join("choice-actions")
1339            .join(format!("{}.json", q.id))
1340            .exists();
1341        let result = async {
1342            let receipt = dir.join(format!("{}.json", q.id));
1343            if receipt.exists() {
1344                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1345                anyhow::ensure!(
1346                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1347                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1348                );
1349                return Ok::<_, anyhow::Error>(());
1350            }
1351            // Never retry an uncertain external effect. The receipt is written
1352            // before calling gh, exactly like release_watch's rerun record.
1353            let record = |status: &str| -> anyhow::Result<()> {
1354                let tmp = receipt.with_extension("tmp");
1355                std::fs::write(
1356                    &tmp,
1357                    serde_json::to_vec(&serde_json::json!({
1358                        "action": action, "status": status,
1359                    }))?,
1360                )?;
1361                std::fs::rename(tmp, &receipt)?;
1362                Ok(())
1363            };
1364            let applied = async {
1365                match action {
1366                    ask::ChoiceAction::ResumeRun { run } => {
1367                        crate::resume::validate(home, run)?;
1368                        record("started")?;
1369                        let decided = q.answered_at.unwrap_or(q.asked_at);
1370                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1371                            crate::resume::validate_unqueued(home, run)?;
1372                            crate::resume::start(home, run.clone()).await?;
1373                        }
1374                    }
1375                    ask::ChoiceAction::ReleaseTask {
1376                        task,
1377                        held_at,
1378                        reason,
1379                    } => {
1380                        anyhow::ensure!(
1381                            queue.resolve_id(task)? == *task,
1382                            "task action requires an exact task ID"
1383                        );
1384                        let _claim = queue.claim(task)?;
1385                        let mut task = queue.get(task)?;
1386                        if task.action_applied(&q.id) {
1387                            return Ok(());
1388                        }
1389                        // Filing this conductor question temporarily wraps the
1390                        // original hold in a Blocked state. Restore only that
1391                        // exact blocker on the local copy before checking the
1392                        // hold binding; unrelated waits never authorize release.
1393                        if q.node == crate::conduct::NODE
1394                            && q.run == task.id
1395                            && task.status == TaskStatus::Blocked
1396                            && task.blocked_from == Some(TaskStatus::Held)
1397                            && task.blocked_by.as_slice() == [q.id.as_str()]
1398                        {
1399                            task.unblock(&q.id);
1400                        }
1401                        anyhow::ensure!(
1402                            task.status == TaskStatus::Held
1403                                && task.held_at == Some(*held_at)
1404                                && task.hold_reason.as_deref() == reason.as_deref()
1405                                && task
1406                                    .operator_decided_at
1407                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1408                            "task no longer has the hold this question names"
1409                        );
1410                        task.release_operator("choice", Some(&q.id));
1411                        task.mark_action_applied(&q.id);
1412                        queue.put(&mut task)?;
1413                    }
1414                    ask::ChoiceAction::AbandonRun { run } => {
1415                        record("started")?;
1416                        crate::driver::abandon_proven_dead(home, run)?;
1417                    }
1418                    ask::ChoiceAction::RerunChecks {
1419                        repo,
1420                        pr,
1421                        head,
1422                        runs,
1423                    } => {
1424                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1425                            .await?;
1426                    }
1427                    _ => unreachable!(),
1428                }
1429                Ok::<_, anyhow::Error>(())
1430            }
1431            .await;
1432            match applied {
1433                Ok(()) => record("applied"),
1434                Err(e) => {
1435                    record(&format!("refused or failed: {e:#}"))?;
1436                    Err(e)
1437                }
1438            }
1439        }
1440        .await;
1441        // Retire the originating blocker as well as the target operation.
1442        // A foreign resume leaves its issuer held instead of competing beside
1443        // the execution just started. Other successful maintenance lets the
1444        // original task retry its normal, guarded path.
1445        if home
1446            .join("choice-actions")
1447            .join(format!("{}.json", q.id))
1448            .exists()
1449            && let Some(listed) = task_of_question(&queue.list(), &q)
1450            && !listed.action_applied(&q.id)
1451            && let Ok(_claim) = queue.claim(&listed.id)
1452            && let Ok(mut origin) = queue.get(&listed.id)
1453        {
1454            if !origin.operator_held()
1455                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1456                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1457            {
1458                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1459                    origin.hold_machine(Some(format!(
1460                        "Maintenance choice {} settled; inspect its target before releasing this task",
1461                        q.id
1462                    )));
1463                } else {
1464                    origin.unblock(&q.id);
1465                }
1466            }
1467            origin.mark_action_applied(&q.id);
1468            let _ = queue.put(&mut origin);
1469        }
1470        if let Err(e) = result
1471            && fresh
1472        {
1473            notices::raise_in(
1474                home,
1475                Notice::warn(
1476                    &format!("action:{}", q.id),
1477                    format!("Choice action {} was not completed: {e:#}", q.id),
1478                )
1479                .link(if q.run_names_task() {
1480                    Link::Task { id: q.run.clone() }
1481                } else {
1482                    Link::Run { id: q.run.clone() }
1483                }),
1484            );
1485        }
1486    }
1487}
1488
1489/// Rerun the named failed workflow runs of a pull request, each at most once
1490/// per `request` (a question id, or a chat operation identity). The head,
1491/// lifecycle and failed state are re-read from the forge first; `started` is
1492/// called once those checks pass and before the first external call, and the
1493/// ledger entry is written before every `gh` call, so an uncertain result is
1494/// never repeated automatically.
1495pub(crate) async fn rerun_checks_once(
1496    home: &Path,
1497    request: &str,
1498    repo: &Path,
1499    pr: &str,
1500    head: &str,
1501    runs: &[String],
1502    started: impl FnOnce() -> anyhow::Result<()>,
1503) -> anyhow::Result<()> {
1504    use crate::release_watch::{GhForge, ReleaseForge};
1505    anyhow::ensure!(
1506        !runs.is_empty()
1507            && runs.len() <= 20
1508            && runs
1509                .iter()
1510                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1511            && !pr.starts_with('-'),
1512        "invalid rerun targets"
1513    );
1514    let snap = GhForge.snapshot(repo, pr).await?;
1515    anyhow::ensure!(
1516        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1517        "pull request head or lifecycle changed"
1518    );
1519    anyhow::ensure!(
1520        runs.iter().all(|r| snap
1521            .checks
1522            .iter()
1523            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1524        "named workflow is no longer failed on this pull request"
1525    );
1526    started()?;
1527    let dir = home.join("choice-actions");
1528    std::fs::create_dir_all(&dir)?;
1529    let rerun_lock = std::fs::OpenOptions::new()
1530        .create(true)
1531        .truncate(false)
1532        .write(true)
1533        .open(dir.join("reruns.lock"))?;
1534    crate::pr_head::try_lock_file(&rerun_lock)?;
1535    let ledger = dir.join("reruns.json");
1536    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1537        serde_json::from_slice(&std::fs::read(&ledger)?)?
1538    } else {
1539        Default::default()
1540    };
1541    for run in runs {
1542        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1543        if !recorded.insert(key) {
1544            continue;
1545        }
1546        let tmp = ledger.with_extension("tmp");
1547        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1548        std::fs::rename(tmp, &ledger)?;
1549        GhForge.rerun(repo, run).await?;
1550    }
1551    Ok(())
1552}
1553
1554/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1555///
1556/// Runs on every poll before the conductor looks at the queue. The task is
1557/// re-read under its claim, so a task somebody completed or held by hand in
1558/// the meantime is judged on what it is now. `Resume` releases the task and
1559/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1560/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1561/// ordinary `unfinished_run` logic resumes that same run.
1562pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1563    let tasks = queue.list();
1564    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1565    for q in questions.list_for_effects_in(&ownership) {
1566        // Read again under the same fence used by explicit settlement.
1567        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1568            continue;
1569        };
1570        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1571            continue;
1572        };
1573        // Dismissal is committed by the question writer, never a resume.
1574        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1575            continue;
1576        }
1577        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1578            continue;
1579        }
1580        let Some(listed) = task_of_question(&tasks, &q) else {
1581            if q.node == land::APPROVAL_NODE
1582                && q.resolution().as_deref().is_some_and(|choice| {
1583                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1584                })
1585            {
1586                notices::raise_in(
1587                    home,
1588                    Notice::warn(
1589                        &format!("repair-owner:{}", q.id),
1590                        format!(
1591                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1592                            q.run, q.run
1593                        ),
1594                    ).link(Link::Run { id: q.run.clone() }),
1595                );
1596            }
1597            continue;
1598        };
1599        if listed.action_applied(&q.id) {
1600            continue;
1601        }
1602        let Ok(_claim) = queue.claim(&listed.id) else {
1603            continue;
1604        };
1605        let Ok(mut task) = queue.get(&listed.id) else {
1606            continue;
1607        };
1608        // Work only on this local copy until the action can be committed.
1609        // In particular, a fresh lease below leaves the persisted task blocked.
1610        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1611            let blockers: Vec<_> = task
1612                .blocked_by
1613                .iter()
1614                .filter(|id| {
1615                    crate::queue::dependency(queue, questions, id)
1616                        == crate::queue::Dependency::Question(q.id.clone())
1617                })
1618                .cloned()
1619                .collect();
1620            if !blockers.is_empty() {
1621                for id in blockers {
1622                    task.unblock(&id);
1623                }
1624                let answer = match &q.answer {
1625                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1626                    None => String::new(),
1627                };
1628                task.record_answer(q.summary.clone(), answer);
1629            }
1630        }
1631        let language = language_of(&task, Path::new("."));
1632        let mut decision = decide_action(home, &task, &q, phrases(&language), |id| {
1633            RunState::load_under(id, home)
1634        });
1635        let completion = if matches!(decision, ActionDecision::Done) {
1636            match crate::task_completion::prepare_close(
1637                &task,
1638                home,
1639                CompletionActor::DaemonSettle,
1640                Some(format!(
1641                    "Question {}: {} — {}",
1642                    q.id,
1643                    q.summary,
1644                    q.resolution().unwrap_or_default()
1645                )),
1646                false,
1647            ) {
1648                Ok(context) => Some(context),
1649                Err(error) => {
1650                    decision = ActionDecision::Refuse(error.to_string());
1651                    None
1652                }
1653            }
1654        } else {
1655            None
1656        };
1657        let ran = matches!(
1658            decision,
1659            ActionDecision::Resume(_)
1660                | ActionDecision::Requeue
1661                | ActionDecision::Hold
1662                | ActionDecision::Done
1663        );
1664        if ran && asker_may_still_read(questions, &q, home) {
1665            // The asking process or its seat can still take the word; act
1666            // once it has gone quiet. Bound on the remaining window: the
1667            // check is not atomic with the write below, so an asker that
1668            // takes the word in between (at most one poll, never more than
1669            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1670            // and `Task::actions_applied` under the claim keeps the action to
1671            // one application. The waiter does not deliver an answer that
1672            // carries an action (`waiter::decide_owned`), so it cannot race.
1673            continue;
1674        }
1675        let done = matches!(decision, ActionDecision::Done);
1676        // Resume owes an execution pass; only these task-local effects finish
1677        // in this write. Stale/refused actions never acquire an effect receipt.
1678        let completed = matches!(
1679            decision,
1680            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1681        );
1682        match decision {
1683            ActionDecision::Skip => continue,
1684            ActionDecision::Resume(run) => {
1685                task.release_operator("choice", Some(&q.id));
1686                task.resume_override = Some(crate::queue::OperatorResume {
1687                    question_id: q.id.clone(),
1688                    at: Timestamp::now(),
1689                    conductor_rehold: None,
1690                    forced: true,
1691                    pinned_run: Some(run),
1692                });
1693            }
1694            ActionDecision::Stale => {}
1695            ActionDecision::Requeue => {
1696                task.release_operator("choice-requeue", Some(&q.id));
1697                task.requeue();
1698            }
1699            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1700            ActionDecision::Done => {
1701                task.succeed(completion.expect("done passed completion admission"));
1702            }
1703            ActionDecision::Refuse(why) => {
1704                let _ =
1705                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1706                if task.operator_held() {
1707                    // A rejected answer does not release the operator's hold
1708                    // or reclassify it as recoverable by the conductor.
1709                    task.hold_reason = Some(match task.hold_reason.take() {
1710                        Some(reason) => format!("{reason}\n\n{why}"),
1711                        None => why,
1712                    });
1713                } else {
1714                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1715                    task.hold_machine(Some(why));
1716                }
1717                notices::raise(
1718                    Notice::warn(
1719                        &format!("action:{}", q.id),
1720                        "An answered task action could not be applied; the task stays held.",
1721                    )
1722                    .link(Link::Task {
1723                        id: task.id.clone(),
1724                    }),
1725                );
1726            }
1727        }
1728        task.mark_action_applied(&q.id);
1729        if completed {
1730            task.decision_effects.insert(
1731                q.id.clone(),
1732                format!("decision: {}", q.resolution().expect("answered action")),
1733            );
1734        }
1735        // The applied id travels with the transition, so a failed save loses
1736        // neither and the answer is acted on at the next poll.
1737        record(queue, &mut task);
1738        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1739            supersede_prior_runs(&task, home);
1740        }
1741        // Delivery is only a note of who has read the answer; the task's own
1742        // mark above is the authority. Best effort.
1743        let _ = questions.update_in(&q.id, &ownership, |r| {
1744            r.answer_delivered = true;
1745            Ok(())
1746        });
1747    }
1748}
1749
1750/// Whether something may still read the answer to `q`: a fresh lease, or the
1751/// asking seat still listed as active in its run (its CLI can outlive the
1752/// `magi ask` that was killed).
1753fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1754    let now = Timestamp::now();
1755    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1756        return true;
1757    }
1758    q.node != crate::conduct::NODE
1759        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1760            s.seats_active()
1761                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1762        })
1763}
1764
1765/// Retire an unanswered conductor question after its task no longer refers to
1766/// it. Conductor questions use the task id in `Question::run`, so run-based
1767/// cleanup cannot observe a manual release or completion.
1768///
1769/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1770/// own question also carries a `run`, and a run id that happens to collide
1771/// with some task's id is not this loop's business — only a conductor
1772/// question actually uses the task id that way. One `Questions::list()` scan
1773/// is taken up front and matched against the in-memory task set, rather than
1774/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1775fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1776    let tasks = queue.list();
1777    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1778    let by_id: std::collections::BTreeMap<&str, &Task> =
1779        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1780    let referenced: Vec<&str> = tasks
1781        .iter()
1782        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1783        .collect();
1784
1785    for mut question in questions.list_for_effects_in(&ownership) {
1786        if !question.status.open()
1787            || question.node != crate::conduct::NODE
1788            || questions.held_reply_in(&question.id, &ownership)
1789        {
1790            continue;
1791        }
1792        // Keep questions a task still names, including when the reference
1793        // moved to a dependent task.
1794        // Preserve even ambiguous references: retiring a possibly referenced
1795        // question is unsafe until the operator disambiguates it.
1796        if referenced
1797            .iter()
1798            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1799        {
1800            continue;
1801        }
1802        let Some(task) = by_id.get(question.run.as_str()) else {
1803            continue;
1804        };
1805        question.abandon(format!(
1806            "task {} no longer waits for this answer",
1807            task.short()
1808        ));
1809        if let Err(e) = questions.put_in(&mut question, &ownership) {
1810            tracing::warn!(
1811                "could not retire question {} for task {}: {e:#}",
1812                question.short(),
1813                task.short()
1814            );
1815        }
1816    }
1817}
1818
1819/// What a finished run tells the queue about the task it came from.
1820///
1821/// A struct rather than a fourth and fifth boolean argument: the two flags
1822/// answer different questions about the same run, and a call site passing
1823/// `(…, true, false)` is one transposition away from refunding attempts
1824/// forever.
1825#[derive(Debug, Clone, Copy)]
1826pub struct Verdict {
1827    /// Where the graph stopped.
1828    pub status: RunStatus,
1829    /// The run opened a pull request.
1830    pub left_pr: bool,
1831    /// At least one seat was lost to a rate limit.
1832    pub quota_hit: bool,
1833    /// The run parked at a node boundary because it was asked to.
1834    pub parked: bool,
1835    /// The run never produced a single candidate a judge could look at.
1836    ///
1837    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1838    /// still have another candidate worth judging, in which case the loss was
1839    /// not the reason nothing came of the run. This is `true` only when the
1840    /// implement wave ended with nothing viable at all.
1841    pub no_viable_candidates: bool,
1842}
1843
1844/// Record a finished run against the task it came from.
1845///
1846/// Kept pure and separate from the loop because this mapping *is* the retry
1847/// policy, and a policy that can only be exercised by spawning a graph is a
1848/// policy nobody checks. The table:
1849///
1850/// | run status                           | task becomes        | attempt spent |
1851/// |---------------------------------------|---------------------|---------------|
1852/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1853/// | `Merged`, `Ready`                      | `Done`               | yes          |
1854/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1855/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1856/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1857/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1858/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1859/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1860/// | `Blocked` with a PR                    | `Held`               | yes          |
1861/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1862/// | `VerifiedNoop`                          | `Held`               | yes          |
1863/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1864///
1865/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1866/// deliberately: every candidate agreeing there is nothing to write is not a
1867/// machine fact about a rate limit, it is an unverified claim about the
1868/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1869/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1870/// claim could be wrong (a misread instruction, a stale check), and closing
1871/// the task automatically on an implementer's say-so would be the exact
1872/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1873/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1874/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1875/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1876/// claim regardless of whether the one already-spent attempt is refunded, and
1877/// [`Task::release`] resets the count to zero anyway the moment a human looks
1878/// at the evidence and lets it run again.
1879///
1880/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1881/// twice, together. A quorum lost to rate limits is a property of the machine
1882/// and not of the task, so the attempt is refunded and a reset quota picks
1883/// the work up where it stopped — and that is just as true when every
1884/// implement seat lost the same race and `after_implement` bails with nothing
1885/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1886/// machine fact. The `no_viable_candidates` guard is what keeps that row
1887/// narrow: a `Failed` run that produced a real candidate which then lost for
1888/// some other reason still spends the attempt, exactly like the quorum lost
1889/// to judges that answered with the wrong shape is ordinary flakiness, and
1890/// refunding *that* takes the bound off the retry loop entirely: run e633
1891/// stalled with `quota: []` after two judges wrote unusable JSON, was
1892/// refunded, and the next attempt paid for a fresh hour-long implement wave
1893/// before it could fail the same way. `max_attempts` exists precisely so
1894/// that cannot repeat forever.
1895///
1896/// A non-terminal status means `execute` returned while the graph was still
1897/// mid-flight, which is a bug rather than a verdict; it is treated as a
1898/// failure so that a task cannot loop on it either.
1899///
1900/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1901/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1902pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1903    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN, None)
1904}
1905
1906/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1907fn settle_in(
1908    task: &mut Task,
1909    verdict: Verdict,
1910    detail: &str,
1911    max_attempts: usize,
1912    p: &Phrases,
1913    state: Option<&RunState>,
1914) {
1915    // A parked run is the operator's own doing, and its work is intact on
1916    // disk. The task goes back in line with its attempt refunded so the next
1917    // loop resumes the same run - which `one_task` prefers over competing
1918    // again - and so that swapping the binary a few times cannot exhaust a
1919    // budget meant for agents that actually misbehaved.
1920    if verdict.parked {
1921        task.park(detail);
1922        return;
1923    }
1924    let completion = |task: &Task| match state {
1925        Some(state) => CompletionContext::from_run(
1926            CompletionActor::DaemonSettle,
1927            Some(detail.to_owned()),
1928            task,
1929            state,
1930        ),
1931        None => CompletionContext::new(
1932            CompletionActor::DaemonSettle,
1933            Some(detail.to_owned()),
1934            &crate::run::home(),
1935            task,
1936        ),
1937    };
1938    match verdict.status {
1939        RunStatus::Merged | RunStatus::Ready
1940            if task.pr_recovery.as_ref().is_some_and(|s| {
1941                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1942            }) =>
1943        {
1944            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()));
1945        }
1946        RunStatus::Merged | RunStatus::Ready => task.succeed(completion(task)),
1947        RunStatus::AlreadyInBase => task.already_landed(detail, completion(task)),
1948        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1949        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1950            task.stall(detail)
1951        }
1952        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1953        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1954        RunStatus::Blocked => task.fail(detail, max_attempts),
1955        RunStatus::VerifiedNoop if state.is_none_or(RunState::all_candidates_verified_noop) => {
1956            task.handed_off(detail)
1957        }
1958        RunStatus::VerifiedNoop => task.fail(detail, max_attempts),
1959        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1960    }
1961}
1962
1963/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1964/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1965/// itself has actually finished *and* its own last attempt is provably why:
1966/// this loads that run and requires `Merged`/`Ready` before touching
1967/// anything earlier in `runs`, since `Task::succeed` can also be called
1968/// directly on a task whose last attempt never landed at all.
1969///
1970/// Called right after whatever call set `task.status` to
1971/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1972/// `reclaim`'s, but also every other place a task can be closed by hand
1973/// without the loop ever settling it itself: `magi task done`
1974/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1975/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1976/// GitHub merge, say, exactly the workflow this repository's own
1977/// "Landing a run's winner by hand" documents — is just as much "this task's
1978/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1979/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1980/// forever, which is the exact backlog this status exists to clear. `pub`
1981/// for those two out-of-module callers; everything else about this stays
1982/// internal bookkeeping.
1983///
1984/// A run something is still actually driving is left alone: a
1985/// task cannot be `Done` while one of its *own* attempts is still in flight,
1986/// so a live one at this point can only be an unrelated process — a manual
1987/// `--resume` of this old, now-moot run — and rewriting under it would just
1988/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1989/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1990/// pair `run_report`/`run_detail` use for the same question elsewhere:
1991/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1992/// --resume` invoked by hand outside it, which `liveness` also checks via
1993/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1994/// (already terminal in some other way, or itself mid-run) is left untouched
1995/// too.
1996///
1997/// Best-effort, like the rest of this module's bookkeeping: a load or save
1998/// failure here is a `tracing::warn`, not a failed settle, and the next time
1999/// this same task's completion is recorded — or a daemon restart replays
2000/// `reclaim_orphaned_running` — is another chance to catch up. There is no
2001/// separate reconciliation pass; if that gap ever matters in practice, one
2002/// can be added then.
2003///
2004/// `home` is a parameter, not the process-global [`crate::run::home`], for
2005/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
2006/// calls this with `ui.home`, which is `crate::run::home()` in a real
2007/// process but a fixture's own directory under test — falling through to
2008/// the global there would read and write through whichever home some other
2009/// test in the same binary happened to pin into that `OnceLock` first, not
2010/// the run this call actually means.
2011pub fn supersede_prior_runs(task: &Task, home: &Path) {
2012    if task
2013        .completion_history
2014        .last()
2015        .is_some_and(|event| event.discard)
2016    {
2017        return;
2018    }
2019    let now = Timestamp::now();
2020    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
2021    // right behind a `Merged`/`Ready` verdict) from one set directly by
2022    // `magi task done`/its web equivalent/the conductor on a task whose last
2023    // recorded attempt never actually landed - that requires reading the
2024    // run itself, which is exactly what this does before trusting anything
2025    // in `runs` is safe to relabel.
2026    let last_run_succeeded = task
2027        .runs
2028        .last()
2029        .and_then(|id| RunState::load_under(id, home).ok())
2030        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
2031    for id in task.superseded_attempts(last_run_succeeded) {
2032        let mut state = match RunState::load_under(id, home) {
2033            Ok(s) => s,
2034            Err(e) => {
2035                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
2036                continue;
2037            }
2038        };
2039        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
2040            continue;
2041        }
2042        let daemon_claims = is_working_on(home, id, now);
2043        if state.liveness(daemon_claims) == Liveness::Live {
2044            continue;
2045        }
2046        state.status = RunStatus::Superseded;
2047        if let Err(e) = state.save_under(home) {
2048            tracing::warn!("could not mark run {id} superseded: {e:#}");
2049        }
2050    }
2051}
2052
2053/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
2054/// finish the moment it was called, because one of its earlier attempts was
2055/// still live then - a `magi run --resume` invoked by hand on an old run,
2056/// most likely.
2057///
2058/// That skip is correct at the time (rewriting under a run something is
2059/// still actively saving would just be undone), but recording a completion
2060/// does not schedule another settlement, so without this nothing would look at it
2061/// again: if that manual process later ends anywhere other than
2062/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
2063/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
2064/// backlog this status exists to clear. Called on the same idle-only
2065/// cadence as [`janitor`], next to it rather than folded into it: this
2066/// walks `queue` and `janitor` never otherwise needs one.
2067///
2068/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
2069/// more than one attempt, every pass: each call is a handful of local file
2070/// reads bounded by that task's own attempt count, the same order of cost
2071/// [`clean::fold_due`] already pays scanning every run on disk on the same
2072/// cadence, and a task already fully resolved costs one failed liveness
2073/// check turned no-op the moment its lingering attempt is no longer live.
2074fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2075    for task in queue.list() {
2076        if task.status != TaskStatus::Done || task.runs.len() < 2 {
2077            continue;
2078        }
2079        supersede_prior_runs(&task, home);
2080    }
2081}
2082
2083/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
2084/// task ends up held.
2085///
2086/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
2087/// dead daemon never got back to) share this, so the two cannot drift into
2088/// disagreeing about which held tasks get a diagnostic.
2089fn settle_and_diagnose(
2090    task: &mut Task,
2091    verdict: Verdict,
2092    detail: &str,
2093    max_attempts: usize,
2094    state: &RunState,
2095) {
2096    let mut verdict = verdict;
2097    let mut detail = detail;
2098    if verdict.status == RunStatus::VerifiedNoop && !state.all_candidates_verified_noop() {
2099        // Never allow an inconsistent or unsupported `VerifiedNoop` run state
2100        // to bypass settlement into a no-change handoff, and never rewrite the
2101        // historical run record on disk: settle the task as an ordinary failure.
2102        verdict.status = RunStatus::Failed;
2103        verdict.quota_hit = false;
2104        detail = "no-change result lacks verified evidence";
2105    }
2106    let p = phrases(&state.config.graph.language);
2107    // Shared by normal completion and crash recovery, under the task claim.
2108    // No new attempt can own the task until the old driver has exited.
2109    if let Some(d) = &state.merge_decision {
2110        use crate::merge_decision as md;
2111        if task
2112            .execution_runs()
2113            .last()
2114            .is_some_and(|id| id != &state.id)
2115        {
2116            return;
2117        }
2118        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2119            task.succeed(CompletionContext::from_run(
2120                CompletionActor::DaemonSettle,
2121                Some(format!("Owner merge decision {}: {}", d.question, d.choice)),
2122                task,
2123                state,
2124            ));
2125        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2126            if state.liveness(false) != Liveness::Dead {
2127                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2128                return;
2129            }
2130            let replacement = md::Replacement {
2131                question: d.question.clone(),
2132                run: state.id.clone(),
2133                pr: d.target.pr.clone(),
2134                agent: agent.to_owned(),
2135                context: format!(
2136                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2137                    d.target.pr,
2138                    state.id,
2139                    serde_json::to_string(&state.reviews).unwrap_or_default()
2140                ),
2141            };
2142            task.requeue();
2143            task.pr_recovery = None;
2144            task.review_of = None;
2145            task.replacement = Some(replacement);
2146        } else {
2147            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2148                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2149            } 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())) }));
2150        }
2151        task.mark_action_applied(&d.question);
2152        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2153            task.decision_effects
2154                .insert(d.question.clone(), format!("decision: {}", d.choice));
2155        }
2156        if let Some(pass) = state.passes.last() {
2157            task.record_pass_at(
2158                &state.id,
2159                pass.index,
2160                Some(pass.started_at),
2161                task.attempts,
2162                None,
2163            );
2164        }
2165        return;
2166    }
2167    if let Some(replacement) = &task.replacement
2168        && !state.parked
2169        && state.resource_block.is_none()
2170        && (state.viable().is_empty()
2171            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2172    {
2173        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)));
2174        return;
2175    }
2176    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2177        let mut agents: Vec<_> = state
2178            .quota
2179            .iter()
2180            .filter(|q| {
2181                q.cause == crate::agent::QuotaCause::Authentication
2182                    && state
2183                        .passes
2184                        .last()
2185                        .is_none_or(|pass| q.at >= pass.started_at)
2186            })
2187            .map(|q| q.agent.as_str())
2188            .collect();
2189        agents.sort_unstable();
2190        agents.dedup();
2191        if !agents.is_empty() {
2192            task.stall(detail);
2193            task.notice_cause("agent-authentication", None, None);
2194            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2195            return;
2196        }
2197    }
2198    let attempts_before = task.attempts;
2199    // A run that stopped because a shared resource stayed busy was never a
2200    // failure of the task or of an agent. Earlier nodes may have run; only
2201    // the blocked operation lacks a result. The attempt is
2202    // refunded and the task is held by the machine, under a reason `triage`
2203    // can re-check, so the same run resumes with the same agents once the
2204    // resource is free. A park request still wins (it is the operator's).
2205    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2206        let disk_checked_at = task.disk_checked_at;
2207        task.notice_cause(
2208            &format!("resource:{}:{}", block.kind, block.node),
2209            None,
2210            None,
2211        );
2212        task.last_error = Some(detail.to_owned());
2213        task.diagnostic = None;
2214        task.attempts = task.attempts.saturating_sub(1);
2215        if block.kind == "agent authentication" {
2216            task.hold_machine(Some(format!(
2217                "[authentication] {}; no attempt was spent",
2218                block.detail
2219            )));
2220        } else if block.kind == "agent usage limit" {
2221            // Usage limits keep the existing cooldown-and-resume policy.
2222            if let Some(agent) = &state.config.graph.selected_implementer {
2223                task.hold_machine(Some(format!("[agent usage limit] Selected implementer `{agent}` is unavailable. No other implementer was dispatched; resume after usage is available. No attempt was spent.")));
2224            } else {
2225                task.status = TaskStatus::Failed;
2226                task.last_error = Some(block.detail.clone());
2227            }
2228        } else if block.kind == "disk pressure" {
2229            task.hold_machine(Some(format!(
2230                "{}{}",
2231                crate::disk::RUNNING_PRESSURE,
2232                block.detail
2233            )));
2234        } else {
2235            task.hold_machine(Some(format!(
2236                "{}{}; no attempt was spent; resume to retry the affected operation",
2237                crate::cache::RESOURCE_HOLD,
2238                block.description()
2239            )));
2240        }
2241        if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2242            && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2243        {
2244            task.mark_disk_capacity();
2245            task.disk_checked_at = disk_checked_at;
2246        }
2247        if let Some(pass) = state.passes.last() {
2248            task.record_pass_at(
2249                &state.id,
2250                pass.index,
2251                Some(pass.started_at),
2252                attempts_before,
2253                None,
2254            );
2255        }
2256        return;
2257    }
2258    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2259        state.parked
2260            && state.status == RunStatus::Landing
2261            && state
2262                .pr_pushed_head
2263                .as_ref()
2264                .is_none_or(|h| h == &hold.head)
2265            && task.execution_runs().last() == Some(&state.id)
2266    }) {
2267        // Settlement and crash recovery share this idempotency key. A later
2268        // explicit resume is a new pass and may refund its own attempt once.
2269        let pass = state.passes.last().map_or(0, |p| p.index);
2270        if !task
2271            .passes
2272            .iter()
2273            .any(|p| p.run == state.id && p.pass_index == pass)
2274        {
2275            task.attempts = task.attempts.saturating_sub(1);
2276        }
2277        task.hold_machine(Some(format!(
2278            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2279            hold.question
2280        )));
2281        task.last_error = Some(detail.to_owned());
2282        task.diagnostic = None;
2283        task.record_pass_at(
2284            &state.id,
2285            pass,
2286            state.passes.last().map(|p| p.started_at),
2287            attempts_before,
2288            Some(crate::run::ParkCause::Question),
2289        );
2290        return;
2291    }
2292    let unresolved = task.hold_notice_cause.clone();
2293    let head_e2e_stop = crate::head_e2e_stop::conclusive(state)
2294        .filter(|_| !verdict.parked && !verdict.quota_hit && task.pr_recovery.is_none());
2295    let mut reconsumed_head_e2e = false;
2296    if state.base_sync_blocked() {
2297        // No automatic retry may turn a retained sync stop into a new competition.
2298        task.hold_machine(Some(detail.to_owned()));
2299        task.last_error = Some(detail.to_owned());
2300    } else if !verdict.parked
2301        && task
2302            .pr_recovery
2303            .as_ref()
2304            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2305        && matches!(
2306            verdict.status,
2307            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2308        )
2309    {
2310        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2311            task.succeed(CompletionContext::from_run(
2312                CompletionActor::DaemonSettle,
2313                Some(detail.to_owned()),
2314                task,
2315                state,
2316            ));
2317        } else {
2318            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()));
2319        }
2320    } else if !verdict.parked
2321        && task.pr_recovery.is_some()
2322        && matches!(
2323            verdict.status,
2324            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2325        )
2326        && !verdict.quota_hit
2327    {
2328        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.")));
2329    } else if let Some(stop) = head_e2e_stop.clone() {
2330        // Conclusive current-head E2E red settles directly to one actionable
2331        // machine hold instead of cycling through runnable `Failed` passes.
2332        // Refund only when this pass provably reconsumed an earlier stop with
2333        // no new verification events, idempotently across reclaim/re-settle.
2334        if crate::head_e2e_stop::reconsumed_without_new_verification(state, &stop) {
2335            reconsumed_head_e2e = true;
2336            let pass = state.passes.last().map_or(0, |p| p.index);
2337            if !task
2338                .passes
2339                .iter()
2340                .any(|p| p.run == state.id && p.pass_index == pass)
2341            {
2342                task.attempts = task.attempts.saturating_sub(1);
2343            }
2344        }
2345        let reason = crate::head_e2e_stop::hold_reason(task, state, &stop, None);
2346        task.hold_head_e2e(stop, reason, detail.to_owned());
2347    } else {
2348        settle_in(task, verdict, detail, max_attempts, p, Some(state));
2349    }
2350    if !verdict.parked
2351        && !verdict.quota_hit
2352        && !reconsumed_head_e2e
2353        && matches!(
2354            verdict.status,
2355            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2356        )
2357    {
2358        task.recovery_failed(state);
2359    }
2360    if state.prep_failure.is_some() {
2361        // Minting a run whose candidates could not be prepared is not work
2362        // on a newly approved attempt. Keep the unresolved outcome anchor.
2363        task.hold_notice_cause = unresolved;
2364        task.startup_notice_cause("startup-candidates");
2365    }
2366    // Written here, where the refund (or not) is decided, so the history is a
2367    // fact and not a later guess from the run's status.
2368    if let Some(pass) = state.passes.last() {
2369        let parked = match &pass.end {
2370            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2371            _ => None,
2372        };
2373        task.record_pass_at(
2374            &state.id,
2375            pass.index,
2376            Some(pass.started_at),
2377            attempts_before,
2378            parked,
2379        );
2380    }
2381    if task.status == TaskStatus::Held {
2382        if state.base_sync_blocked() {
2383            task.base_sync_notice(state);
2384        } else if let Some(stop) = &head_e2e_stop {
2385            task.head_e2e_notice(stop);
2386        } else if state.prep_failure.is_none() {
2387            task.notice_cause(
2388                label(verdict.status),
2389                Some(&state.id),
2390                state.passes.last().map(|p| p.index),
2391            );
2392        }
2393        task.diagnostic = diagnostic(state);
2394        note_open_question(task, &state.id, p);
2395    }
2396}
2397
2398/// If `task` is held with a `magi ask` question still open on `run`, name the
2399/// question in [`Task::hold_reason`] rather than leaving the hold reading
2400/// only [`describe`]'s run summary.
2401///
2402/// This is the shape task 20260928-191407-05fd left underspecified: an
2403/// implementer settled a verified no-op and filed a question for the
2404/// operator, and the hold that followed said nothing about the question
2405/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2406/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2407/// marker) and must keep seeing it unchanged.
2408///
2409/// Best-effort: an unreadable question store must not stop a run from
2410/// settling, so this is a no-op rather than a propagated error when
2411/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2412fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2413    let Some(home) = crate::run::try_home() else {
2414        return;
2415    };
2416    let open = Questions::at(home.join("questions")).open_for(run);
2417    let Some(q) = open.first() else {
2418        return;
2419    };
2420    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2421    decisions.sort_unstable();
2422    task.notice_cause(
2423        &format!("questions:{}", decisions.join(",")),
2424        Some(run),
2425        None,
2426    );
2427    let base = task.hold_reason.clone().unwrap_or_default();
2428    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2429}
2430
2431/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2432/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2433/// by some other means entirely, like a manual `magi run` resume that
2434/// finishes the graph outside the queue's bookkeeping.
2435///
2436/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2437/// `settle` is separate from `attempt`: a task recovered this way must land
2438/// exactly where a live daemon would have put it — the same policy table,
2439/// not a second one that quietly drifts from it — and that is only checkable
2440/// without spawning a real run.
2441fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2442    if let Some(request) = task.sync_only.clone() {
2443        crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2444        return;
2445    }
2446    match last_run {
2447        Some(state) => {
2448            let verdict = Verdict {
2449                status: state.status,
2450                left_pr: state.pr.is_some(),
2451                quota_hit: state.quota.iter().any(|loss| {
2452                    state
2453                        .passes
2454                        .last()
2455                        .is_none_or(|pass| loss.at >= pass.started_at)
2456                }),
2457                parked: state.parked,
2458                no_viable_candidates: state.viable().is_empty(),
2459            };
2460            let detail = format!(
2461                "{}{}",
2462                phrases(&state.config.graph.language).recovered_running,
2463                describe(&state)
2464            );
2465            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2466        }
2467        None => {
2468            // No run, so no config of its own: `language` is the task's
2469            // repository's setting, read by the caller.
2470            let why = phrases(language).no_run_to_recover;
2471            task.last_error = Some(why.to_owned());
2472            // The phone shows `hold_reason`, so a task held by the machine
2473            // says why there too and not only in `last_error`.
2474            task.notice_cause("missing-run", None, None);
2475            task.hold_machine(Some(why.to_owned()));
2476        }
2477    }
2478}
2479
2480/// Find every task left at `running` that no live process is actually
2481/// driving, and settle each one against whatever its last run became.
2482///
2483/// # Why a claim is proof, not a guess
2484///
2485/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2486/// `running`, and the guard is held for the task's whole time in that status:
2487/// `attempt` does not return, and the loop does not move past the scope
2488/// holding the claim, until the run has settled. So a `running` task whose
2489/// lock is gone cannot have a live owner — this process or any other —
2490/// without needing a staleness threshold or a pid check the way
2491/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2492/// task that never got as far as `running` at all. Taking the claim here is
2493/// the whole test: it either fails, because something really does hold it
2494/// and the task is left alone, or it succeeds, which is the proof — and it is
2495/// kept for the rest of the decision so nothing else can start a competing
2496/// run while this one is being written.
2497///
2498/// Called on every poll, not only at startup, for the reason
2499/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2500/// keep noticing this, not only on the one morning it happened to restart.
2501fn reclaim_orphaned_running(
2502    queue: &Queue,
2503    max_attempts: usize,
2504    live_workers: &std::collections::BTreeSet<String>,
2505) -> Vec<String> {
2506    let mut reclaimed = Vec::new();
2507    for listed in queue.list() {
2508        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2509            continue;
2510        }
2511        let Ok(_claim) = queue.claim(&listed.id) else {
2512            continue;
2513        };
2514        // Re-read under the claim: a release or an edit landed by a human
2515        // between the listing above and the claim just taken must not be
2516        // clobbered by a decision based on the stale copy.
2517        let Ok(mut task) = queue.get(&listed.id) else {
2518            continue;
2519        };
2520        if task.status != TaskStatus::Running {
2521            continue;
2522        }
2523        let last_run = task
2524            .execution_runs()
2525            .last()
2526            .and_then(|id| RunState::load(id).ok());
2527        // `execute` normally abandons a run's own open questions the moment
2528        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2529        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2530        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2531        // with the question still `open`, because the process died before
2532        // reaching that call. `reclaim` itself stays pure on purpose (see its
2533        // own doc), so the same cleanup runs here instead, against the run
2534        // this reclaim is already reading. `settle_run` costs nothing when
2535        // `execute` already got there first.
2536        if let Some(state) = &last_run
2537            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2538        {
2539            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2540        }
2541        let language = if last_run.is_none() {
2542            language_of(&task, Path::new("."))
2543        } else {
2544            String::new()
2545        };
2546        reclaim(&mut task, last_run, max_attempts, &language);
2547        if task.status == TaskStatus::Done {
2548            supersede_prior_runs(&task, &crate::run::home());
2549        }
2550        record(queue, &mut task);
2551        reclaimed.push(task.id.clone());
2552    }
2553    reclaimed
2554}
2555
2556/// Find every run whose `run.json` is provably dead — every seat it still
2557/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2558/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2559/// not merely "no daemon claims it" — and fail it, clearing the leftover
2560/// active seats so the run stops reading as `implementing` (or whichever
2561/// node) forever.
2562///
2563/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2564/// `running`, using whatever `run.json` already says — but nothing in that
2565/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2566/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2567/// never got back to sits exactly where it was left: `active` full of seats
2568/// nobody will ever answer for, `status` stuck on whatever node was in
2569/// flight. `magi show` already tells an operator this in prose (`no live
2570/// daemon claims this run right now`); this is what makes that fact durable
2571/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2572/// stay stuck once nothing is driving it.
2573///
2574/// Runs on every poll, not only at startup, for the reason
2575/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2576/// daemon up for days must keep noticing a run some other, now-dead, daemon
2577/// left behind just as readily as one it trips over on the way up.
2578///
2579/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2580/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2581/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2582/// `runs` directory instead: `home` here is a parameter precisely so a test
2583/// can point it away from the operator's real history (see [`drive`]'s own
2584/// doc), and a scan that fell through to the global home anyway would walk
2585/// whichever directory some *other* process or test pinned into that
2586/// `OnceLock` first — mutating runs this call was never handed.
2587fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2588    reclaim_abandoned_runs_with(
2589        home,
2590        now,
2591        crate::proc::pid_status,
2592        crate::proc::process_started_at,
2593    )
2594}
2595
2596/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2597/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2598/// for the identical reason: this sweep's real damage (wiping a run's active
2599/// seats and failing it) has to be provable against an injected answer in a
2600/// test, not just the real process table.
2601fn reclaim_abandoned_runs_with<F, G>(
2602    home: &Path,
2603    now: Timestamp,
2604    query: F,
2605    identity: G,
2606) -> Vec<String>
2607where
2608    F: Fn(u32) -> Option<bool>,
2609    G: Fn(u32) -> Option<String>,
2610{
2611    let mut abandoned = Vec::new();
2612    for entry in std::fs::read_dir(home.join("runs"))
2613        .into_iter()
2614        .flatten()
2615        .flatten()
2616    {
2617        let id = entry.file_name().to_string_lossy().into_owned();
2618        if !crate::run::is_run_id(&id) {
2619            continue;
2620        }
2621        // Serialize the proof and save with claims and takeover: a new
2622        // execution must not be overwritten after the liveness observation.
2623        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2624            continue;
2625        };
2626        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2627        // that module's docs for why a run this cannot parse is left alone
2628        // rather than guessed at. A different schema number is not that: this
2629        // touches only `status` and `active`, never a field whose meaning a
2630        // schema bump changed, so an old record's values serve this exactly
2631        // as well as a current one's (see `clean::read_state`'s own doc for
2632        // the same reasoning applied to folding).
2633        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2634            continue;
2635        };
2636        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2637            continue;
2638        };
2639        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2640            continue;
2641        }
2642        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2643        // it", which is also the normal, healthy shape of a manual `magi
2644        // run` / `magi review` sharing this same home — this scan walks
2645        // every run on disk, not only ones this daemon itself started. Such
2646        // a run's active seats can legitimately sit past their own timeout
2647        // for a little while (the CLI finishing up, its result still being
2648        // collected) without the process driving it having died. `liveness`
2649        // is what actually tells the two apart, by corroborating
2650        // `driver_pid` against the process it names — see its own doc. Only
2651        // its strongest, provable answer licenses wiping this run's active
2652        // seats and failing it out from under whatever is still running it.
2653        let daemon_claims = is_working_on(home, &id, now);
2654        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2655            != crate::run::Liveness::Dead
2656        {
2657            continue;
2658        }
2659        state.abandon("daemon");
2660        if let Err(e) = state.save_under(home) {
2661            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2662            continue;
2663        }
2664        // This run never passes through `Runner::execute` again, so its end
2665        // is announced here.
2666        if let Some(notice) = notices::run_ended(&state) {
2667            notices::raise_in(home, notice);
2668        }
2669        // The seat that asked is gone for good now, exactly like any other
2670        // door `graph::Runner::settle_questions` closes the moment `status`
2671        // lands somewhere non-resumable - see that method's own doc. Nothing
2672        // else reaches this one before the next `janitor()` startup pass
2673        // (`clean::abandon_settled_questions`), and a daemon that stays up
2674        // for days must not leave an open question badging the operator
2675        // until it happens to restart.
2676        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2677            tracing::warn!("abandon questions for {id}: {e:#}");
2678        }
2679        abandoned.push(id);
2680    }
2681    abandoned
2682}
2683
2684#[derive(Debug, Clone, Serialize, Deserialize)]
2685struct TaskWorker {
2686    opts: Opts,
2687    queue: PathBuf,
2688    task: String,
2689    #[serde(default)]
2690    lane: PermitKind,
2691    #[serde(default)]
2692    standalone: bool,
2693}
2694
2695#[doc(hidden)]
2696pub struct TaskWorkerLease {
2697    pub job: crate::worker::Job,
2698    dir: PathBuf,
2699    lease: Option<crate::worker::Lease>,
2700}
2701
2702impl TaskWorkerLease {
2703    pub fn release_lease(&mut self) {
2704        self.lease = None;
2705    }
2706}
2707
2708impl Drop for TaskWorkerLease {
2709    fn drop(&mut self) {
2710        self.release_lease();
2711        let _ = std::fs::remove_dir_all(&self.dir);
2712    }
2713}
2714
2715/// Reserve a task worker without launching a process, for integration tests.
2716#[doc(hidden)]
2717pub fn live_task_fixture(home: &Path, task: &str) -> Result<TaskWorkerLease> {
2718    let request = TaskWorker {
2719        opts: Opts::default(),
2720        queue: home.join("queue"),
2721        task: task.to_owned(),
2722        lane: PermitKind::default(),
2723        standalone: true,
2724    };
2725    let (job, lease) = crate::worker::running_fixture(
2726        home,
2727        &format!("task:{task}"),
2728        serde_json::to_value(request)?,
2729    )?;
2730    Ok(TaskWorkerLease {
2731        dir: home.join("workers").join("jobs").join(&job.id),
2732        job,
2733        lease: Some(lease),
2734    })
2735}
2736
2737fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2738    Ok(crate::worker::active(home)?
2739        .into_iter()
2740        .filter(|job| job.kind == "task")
2741        .collect())
2742}
2743
2744fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2745    task_jobs(home)?
2746        .into_iter()
2747        .filter_map(
2748            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2749                Ok(request) if !request.standalone => Some(Ok(job)),
2750                Ok(_) => None,
2751                Err(error) => Some(Err(error.into())),
2752            },
2753        )
2754        .collect()
2755}
2756
2757/// Whether an independent scheduler can be controlled without its web parent.
2758#[must_use]
2759pub fn managed(home: &Path) -> bool {
2760    match crate::worker::active(home) {
2761        Err(error) => {
2762            tracing::error!("cannot determine scheduler ownership: {error:#}");
2763            true
2764        }
2765        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2766        Ok(_) => {
2767            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2768                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2769        }
2770    }
2771}
2772
2773/// Start a detached, singleton scheduler using this executable generation.
2774pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2775    anyhow::ensure!(
2776        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2777        "the scheduler is stopping; wait for retirement before starting it again"
2778    );
2779    crate::worker::spawn(
2780        home,
2781        "scheduler",
2782        "scheduler",
2783        serde_json::to_value(opts.absolute()?)?,
2784    )
2785    .await
2786}
2787
2788fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2789    home.join("worker-parks").join(format!("{}.json", job.id))
2790}
2791
2792fn request_task_park(
2793    home: &Path,
2794    job: &crate::worker::Job,
2795    cause: crate::run::ParkCause,
2796) -> Result<()> {
2797    let path = park_request_path(home, job);
2798    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2799    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2800    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2801}
2802
2803/// Stop dispatch immediately; only an explicit park reaches existing workers.
2804pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2805    if control == crate::worker::Control::Park {
2806        for job in owned_task_jobs(home)? {
2807            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2808        }
2809    }
2810    crate::worker::request(home, "scheduler", control)
2811}
2812
2813/// Resolve what a restart would replace without signalling the scheduler.
2814pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
2815    if let Some(job) = crate::worker::active(home)?
2816        .into_iter()
2817        .find(|job| job.kind == "scheduler")
2818    {
2819        return serde_json::from_value(job.payload)
2820            .context("read detached scheduler options")
2821            .map(Some);
2822    }
2823    if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2824        && crate::worker::try_lease(home, "scheduler")?.is_none()
2825    {
2826        let path = home.join("scheduler-options.json");
2827        let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2828        return serde_json::from_slice(&body)
2829            .context("decode detached scheduler options")
2830            .map(Some);
2831    }
2832    Ok(None)
2833}
2834
2835/// Replace the scheduler, leaving all active task and conversation jobs alone.
2836pub async fn restart_detached(home: &Path) -> Result<()> {
2837    let Some(opts) = scheduler_restart_options(home)? else {
2838        return Ok(());
2839    };
2840    request_control(home, crate::worker::Control::Stop)?;
2841    loop {
2842        let reserved = crate::worker::active(home)?
2843            .iter()
2844            .any(|job| job.kind == "scheduler");
2845        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2846            break;
2847        }
2848        tokio::time::sleep(Duration::from_millis(100)).await;
2849    }
2850    spawn_detached(home, &opts).await?;
2851    Ok(())
2852}
2853
2854/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2855pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2856    let opts: Opts = serde_json::from_value(payload)?;
2857    let _ = home;
2858    serve_until(opts, Stop::new()).await
2859}
2860
2861/// Execute and settle one task with the queue claim owned by this process.
2862pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2863    let request: TaskWorker = serde_json::from_value(payload)?;
2864    let queue = Queue::at(request.queue);
2865    let key = format!("task:{}", request.task);
2866    let job = task_jobs(home)?
2867        .into_iter()
2868        .find(|job| job.key == key)
2869        .context("task worker reservation is missing")?;
2870    let park_path = park_request_path(home, &job);
2871    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2872    // our durable reservation. Never execute before that ownership hand-off.
2873    let _claim = loop {
2874        match queue.claim(&request.task) {
2875            Ok(claim) => break claim,
2876            // Only contention (the claim file exists) is worth waiting out; an
2877            // I/O failure must end this worker instead of pinning its lane.
2878            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2879                return Err(e.context("claim the task for its worker"));
2880            }
2881            Err(_) => {
2882                sweep_stale_claims(&queue, STALE_CLAIM);
2883                tokio::time::sleep(Duration::from_millis(50)).await;
2884            }
2885        }
2886    };
2887    let mut task = queue.get(&request.task)?;
2888    if !task.status.runnable()
2889        || (!request.standalone
2890            && request.lane
2891                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2892    {
2893        return Ok(());
2894    }
2895    let stop = Stop::new();
2896    let watcher = {
2897        let home = home.to_path_buf();
2898        let stop = stop.clone();
2899        let park_path = park_path.clone();
2900        tokio::spawn(async move {
2901            loop {
2902                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2903                    let cause = std::fs::read(&park_path)
2904                        .ok()
2905                        .and_then(|body| serde_json::from_slice(&body).ok())
2906                        .unwrap_or(crate::run::ParkCause::Operator);
2907                    stop.park(cause);
2908                    return;
2909                }
2910                tokio::time::sleep(Duration::from_millis(200)).await;
2911            }
2912        })
2913    };
2914    let quota = if request.standalone {
2915        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2916    } else {
2917        let status = Arc::new(Mutex::new(Status::new()));
2918        Box::pin(attempt(
2919            &request.opts,
2920            &queue,
2921            &status,
2922            &stop,
2923            crate::graph::Pause::new(),
2924            &mut task,
2925        ))
2926        .await
2927    };
2928    watcher.abort();
2929    let _ = std::fs::remove_file(park_path);
2930    persist_cooldown(home, &quota).await?;
2931    Ok(())
2932}
2933
2934/// Launch the standalone task worker with a claim-to-reservation handoff.
2935/// Returns only after the worker owns a durable execution reservation.
2936pub async fn spawn_claimed(
2937    home: &Path,
2938    opts: &Opts,
2939    queue: &Queue,
2940    task: &Task,
2941    claim: crate::queue::Claim,
2942) -> Result<crate::worker::Job> {
2943    let request = TaskWorker {
2944        opts: opts.absolute()?,
2945        queue: std::path::absolute(queue.root())?,
2946        task: task.id.clone(),
2947        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2948        standalone: true,
2949    };
2950    let job = crate::worker::spawn(
2951        home,
2952        "task",
2953        &format!("task:{}", task.id),
2954        serde_json::to_value(request)?,
2955    )
2956    .await?;
2957    drop(claim);
2958    Ok(job)
2959}
2960
2961/// Transfer a standalone caller's claim only after the detached worker is live,
2962/// then follow that worker to its final (non-automatically-retrying) outcome.
2963pub async fn run_detached_claimed(
2964    opts: &Opts,
2965    queue: &Queue,
2966    task: &mut Task,
2967    claim: crate::queue::Claim,
2968) -> Result<()> {
2969    let home = crate::run::home();
2970    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2971    loop {
2972        // Reconcile execution leases even without a scheduler. A dead worker
2973        // must become a reported failure, never an infinite persisted wait.
2974        crate::worker::active(&home)?;
2975        let current = crate::worker::get(&home, &job.id)?;
2976        if matches!(
2977            current.status,
2978            crate::worker::Status::Finished | crate::worker::Status::Failed
2979        ) {
2980            *task = queue.get(&task.id)?;
2981            anyhow::ensure!(
2982                current.status != crate::worker::Status::Failed,
2983                "task worker failed: {}",
2984                current.result.as_deref().unwrap_or("unknown failure")
2985            );
2986            return Ok(());
2987        }
2988        tokio::time::sleep(Duration::from_millis(200)).await;
2989    }
2990}
2991
2992async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2993    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2994        let _lease = loop {
2995            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2996                break lease;
2997            }
2998            tokio::time::sleep(Duration::from_millis(10)).await;
2999        };
3000        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
3001            let path = home.join("task-quota-cooldown.json");
3002            let temporary = path.with_extension("json.tmp");
3003            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
3004            std::fs::rename(temporary, path)?;
3005        }
3006    }
3007    Ok(())
3008}
3009
3010fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
3011    match std::fs::read(home.join("task-quota-cooldown.json")) {
3012        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
3013        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
3014        Err(error) => Err(error.into()),
3015    }
3016}
3017
3018/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
3019///
3020/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
3021/// sets, so there is one loop body rather than two that drift apart the first
3022/// time the retry policy changes on only one of them.
3023pub async fn serve(opts: Opts) -> Result<()> {
3024    tracing::info!(
3025        "automatic update and restart requires magi web; standalone serve does not restart"
3026    );
3027    serve_until(opts, Stop::new()).await
3028}
3029
3030/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
3031///
3032/// A stop retires dispatch promptly, including while a worker launch is being
3033/// acknowledged. Already reserved workers own their attempts independently and
3034/// finish with their started executable. Explicit park additionally forwards
3035/// durable park requests; neither scheduler retirement nor update does so.
3036///
3037/// While the queue is empty the stop is honoured within one wakeup rather than
3038/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
3039/// caller that taps stop does not sit through the remainder of a sleep.
3040pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
3041    let opts = opts.absolute()?;
3042    let home = crate::run::home();
3043    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
3044        .context("another scheduler already owns this home")?;
3045    if let Some(reading) = read_status(&home)
3046        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
3047    {
3048        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
3049    }
3050    if !crate::worker::active(&home)?
3051        .iter()
3052        .any(|job| job.kind == "scheduler")
3053    {
3054        crate::worker::clear_control(&home, "scheduler")?;
3055    }
3056    std::fs::write(
3057        home.join("scheduler-options.json"),
3058        serde_json::to_vec(&opts)?,
3059    )?;
3060    let control = {
3061        let home = home.clone();
3062        let stop = stop.clone();
3063        tokio::spawn(async move {
3064            loop {
3065                match crate::worker::control(&home, "scheduler").ok().flatten() {
3066                    Some(crate::worker::Control::Park) => {
3067                        let _ = request_control(&home, crate::worker::Control::Park);
3068                        stop.park(crate::run::ParkCause::Operator);
3069                        break;
3070                    }
3071                    Some(crate::worker::Control::Stop) => {
3072                        stop.stop();
3073                        break;
3074                    }
3075                    None => {}
3076                }
3077                tokio::time::sleep(Duration::from_millis(100)).await;
3078            }
3079        })
3080    };
3081    let signal = {
3082        let stop = stop.clone();
3083        tokio::spawn(async move {
3084            if tokio::signal::ctrl_c().await.is_ok() {
3085                stop.stop();
3086                tracing::info!("scheduler shutdown requested; independent workers continue");
3087            }
3088        })
3089    };
3090
3091    let worktrees_root = opts
3092        .worktrees_root
3093        .clone()
3094        .unwrap_or_else(crate::run::default_worktree_root);
3095    let outcome = drive(
3096        &opts,
3097        &Queue::open(),
3098        &status_path(),
3099        &crate::run::home(),
3100        &worktrees_root,
3101        &stop,
3102    )
3103    .await;
3104
3105    signal.abort();
3106    control.abort();
3107    outcome
3108}
3109
3110/// The loop proper: setup, poll, teardown, with the queue and the status file
3111/// supplied rather than discovered.
3112///
3113/// All three of `home`, `worktrees_root` and the queue/status paths are
3114/// parameters rather than resolved here, for the same reason:
3115/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
3116/// so a unit test that pinned it would fight every other test in the binary,
3117/// and a loop that resolved its own worktree bay could only be exercised
3118/// against the operator's real `~/wt/<repo>` - publishing over a live
3119/// daemon's status file, claiming tasks out of a live backlog, and, since
3120/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
3121/// whatever the operator actually has on disk.
3122async fn drive(
3123    opts: &Opts,
3124    queue: &Queue,
3125    status_file: &Path,
3126    home: &Path,
3127    worktrees_root: &Path,
3128    stop: &Stop,
3129) -> Result<()> {
3130    // The status file is a *snapshot*, not a stream of events: a reader only
3131    // ever wants the latest values, and every tick rewrites the whole file
3132    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
3133    // while an mpsc channel would force the loop to re-send unchanged fields on
3134    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
3135    // for no gain. The lock is only ever held across a field assignment, never
3136    // across an await.
3137    let recovery_cfg = prepare(&opts.repo, opts).ok();
3138    let daemon_cfg = recovery_cfg
3139        .as_ref()
3140        .map(|c| c.daemon.clone())
3141        .unwrap_or_default();
3142    let reconciled = crate::driver::reconcile(home);
3143    if !reconciled.is_empty() {
3144        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3145    }
3146    let mut initial_status = Status::new();
3147    let owned = owned_task_jobs(home)?;
3148    initial_status.current = current_work(home, Timestamp::now())
3149        .into_iter()
3150        .filter(|current| {
3151            owned
3152                .iter()
3153                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3154        })
3155        .collect();
3156    initial_status.idle = initial_status.current.is_empty();
3157    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3158        recovery_cfg.as_ref(),
3159        daemon_cfg.max_deputies,
3160    ));
3161    let status = Arc::new(Mutex::new(initial_status));
3162    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3163    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3164
3165    // Read once at startup, not per task: how many runs this loop drives at
3166    // once is a property of the machine running it, not of whichever
3167    // repository a given task happens to name - see
3168    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
3169    // fact in the same sense the agent roster is.
3170    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3171
3172    tracing::info!(
3173        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3174        queue.root().display(),
3175        opts.poll.as_secs(),
3176        opts.max_attempts,
3177        concurrency,
3178        if daemon_cfg.pause_for_interrupts {
3179            ", interrupts enabled"
3180        } else {
3181            ""
3182        }
3183    );
3184
3185    let outcome = tokio::select! {
3186        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3187            max_concurrent: concurrency,
3188            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3189            recovery_cfg,
3190        }) => outcome,
3191        () = async {
3192            while !stop.stopped() {
3193                tokio::time::sleep(Duration::from_millis(25)).await;
3194            }
3195        } => {
3196            if stop.parking() {
3197                request_control(home, crate::worker::Control::Park)?;
3198            }
3199            Ok(())
3200        }
3201    };
3202
3203    stop.busy.store(0, Ordering::SeqCst);
3204    beat.abort();
3205    clear_status_at(status_file);
3206    outcome
3207}
3208
3209/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3210/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3211pub(crate) fn release_watch_settings_from_config(
3212    home: &Path,
3213    repo: &Path,
3214    cfg: &Config,
3215) -> (Vec<PathBuf>, u64) {
3216    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3217        .into_iter()
3218        .map(|r| r.path)
3219        .collect();
3220    // Repositories the daemon has worked in, wherever they live: a task may
3221    // name one outside `[repos] roots`, and its release PR must be watched too.
3222    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3223        .list()
3224        .into_iter()
3225        .map(|t| t.repo)
3226        .collect();
3227    let runs = home.join("runs");
3228    for id in crate::run::list_ids_in(&runs) {
3229        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3230            .ok()
3231            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3232            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3233        known.extend(repo);
3234    }
3235    for k in known {
3236        let k = k.canonicalize().unwrap_or(k);
3237        if k.join(".git").exists() && !paths.contains(&k) {
3238            paths.push(k);
3239        }
3240    }
3241    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3242    if !paths.contains(&own) {
3243        paths.push(own);
3244    }
3245    (paths, cfg.daemon.release_stall_minutes)
3246}
3247
3248/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3249const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3250
3251/// Refresh the status file on a fixed tick.
3252///
3253/// Separate from the loop because a run takes tens of minutes: a status file
3254/// written only between tasks would look stale for the whole of every run, and
3255/// a reader would report the daemon dead exactly while it was busiest.
3256async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3257    loop {
3258        tokio::time::sleep(HEARTBEAT).await;
3259        let snapshot = {
3260            let mut guard = lock(&status);
3261            guard.updated_at = Timestamp::now();
3262            guard.clone()
3263        };
3264        if let Err(e) = write_status_to(&path, &snapshot) {
3265            // A failed heartbeat must not take the daemon down: the loop is the
3266            // product, the status file is only the window onto it.
3267            tracing::warn!("could not refresh the daemon status file: {e:#}");
3268        }
3269    }
3270}
3271
3272/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3273/// if so, whether that wait is over.
3274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3275enum LandResume {
3276    /// The task's last run is not parked on a land approval; schedule it
3277    /// like any other candidate.
3278    NotLanding,
3279    /// Parked in `land`, waiting on a question nobody has answered yet.
3280    /// Left alone: attempting it now would only re-observe the same pull
3281    /// request and park again, spending a `gh` call on a decision that has
3282    /// not changed since the last time this was checked.
3283    StillWaiting,
3284    /// Parked in `land`, and the question is settled - answered or
3285    /// abandoned. Resuming this is the one kind of candidate that must not
3286    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3287    Ready,
3288}
3289
3290/// Classify a runnable candidate by whether it is parked on a land-merge
3291/// approval. Read-only - no claim taken, nothing written - so it is cheap
3292/// enough to call on every candidate, every poll.
3293fn land_resume_state(task: &Task) -> LandResume {
3294    if task.sync_only.is_some() {
3295        return LandResume::NotLanding;
3296    }
3297    let Some(run_id) = task.execution_runs().last() else {
3298        return LandResume::NotLanding;
3299    };
3300    let Ok(state) = RunState::load(run_id) else {
3301        return LandResume::NotLanding;
3302    };
3303    if !state.parked {
3304        return LandResume::NotLanding;
3305    }
3306    if state.status == RunStatus::Landing
3307        && state.land_approval.as_ref().is_some_and(|binding| {
3308            ask::Questions::open()
3309                .get_for_effects(&binding.question)
3310                .is_ok_and(|q| {
3311                    q.run == state.id
3312                        && q.resolution()
3313                            .as_deref()
3314                            .is_some_and(crate::merge_decision::stops)
3315                })
3316        })
3317    {
3318        return LandResume::Ready;
3319    }
3320    if !implementers_match(task, &state) {
3321        return LandResume::NotLanding;
3322    }
3323    // Parked in `land` on the merge approval, or at `merge` on the owner's
3324    // word about a title/body the posting gate withheld. Told apart by the
3325    // run's own record, not by a status both can share.
3326    let node = if state.status == RunStatus::Landing {
3327        land::APPROVAL_NODE
3328    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3329        crate::github_text::ASK_NODE
3330    } else {
3331        return LandResume::NotLanding;
3332    };
3333    let store = ask::Questions::open();
3334    let waiting = store
3335        .list_for_effects()
3336        .into_iter()
3337        .filter(|q| &q.run == run_id && q.node == node)
3338        .max_by(|a, b| a.id.cmp(&b.id));
3339    let Some(mut q) = waiting else {
3340        return LandResume::Ready;
3341    };
3342    if !q.status.open() {
3343        // Repair spends agent resources and must obey concurrency and quota
3344        // waits; only a merge/hold decision may use the decision-only lane.
3345        if q.resolution().as_deref() == Some(land::REPAIR) {
3346            return if state.liveness(false) == Liveness::Live {
3347                LandResume::StillWaiting
3348            } else {
3349                LandResume::NotLanding
3350            };
3351        }
3352        return LandResume::Ready;
3353    }
3354    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3355    // nobody ever answered; land's approval bypasses that wait entirely (see
3356    // `land::approval_gate`), so the same deadline has to be enforced here
3357    // instead, or `graph.answer_timeout` silently stops meaning anything for
3358    // a land approval and a run can sit `StillWaiting` forever with nobody
3359    // told to look at it.
3360    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3361    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3362    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3363        q.abandon(format!(
3364            "no answer within {}s of asking",
3365            timeout.as_secs().max(1)
3366        ));
3367        // If this can't be persisted, do not treat the wait as settled on a
3368        // guess: fall through and try again next poll.
3369        if store.put(&mut q).is_ok() {
3370            return LandResume::Ready;
3371        }
3372    }
3373    LandResume::StillWaiting
3374}
3375
3376/// How often the loop rechecks for new work while something it already
3377/// started is still running, rather than sleeping out the whole
3378/// [`Opts::poll`] interval.
3379///
3380/// Short on purpose: this is what lets a land-merge approval that comes back
3381/// while another task is mid-competition be noticed and resumed within a
3382/// fraction of a second, not within the next multi-second poll.
3383const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3384
3385/// How often [`poll`] rechecks the shared build cache against its cap at a
3386/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3387/// waiting for the queue to run dry.
3388///
3389/// A queue that never empties means the `janitor` call at the bottom of this
3390/// loop's fully-idle branch can go unreached for as long as the backlog
3391/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3392/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3393/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3394/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3395/// backlog of short tasks does not pay for that walk on every poll.
3396const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3397
3398/// State of [`poll`]'s own interrupt-scheduling sequence - see
3399/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3400/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3401/// both kept free of `Task`'s non-identity fields on purpose: every decision
3402/// here turns only on task ids and which ones are in flight, so the "never
3403/// more than one run at once" and "exactly one resume" invariants can be
3404/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3405/// queue - which is exactly the coverage this feature's first two attempts
3406/// were missing.
3407///
3408/// Persisted after every transition, so scheduler replacement preserves the
3409/// interrupt's exclusive turn and the interrupted task's priority resume.
3410#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3411enum Interrupt {
3412    /// No interrupt sequence in progress. Ordinary dispatch applies.
3413    Idle,
3414    /// `interrupt_task` is runnable and exactly one other run is in flight;
3415    /// `parked` names that one task's id. Dispatch is withheld from
3416    /// everyone, including `interrupt_task` itself, until it has left
3417    /// flight - only then is `interrupt_task` let through.
3418    ///
3419    /// `parked` is a `Vec` rather than a bare id for symmetry with
3420    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3421    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3422    /// when exactly one run is in flight, so it is guaranteed to hold
3423    /// exactly one entry in practice - see that branch's own doc for why
3424    /// more than one is deliberately never attempted.
3425    Parking {
3426        parked: Vec<String>,
3427        interrupt_task: String,
3428    },
3429    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3430    /// withheld from everyone until it leaves flight - merged, failed, held,
3431    /// it makes no difference - at which point the sequence moves to
3432    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3433    /// going straight to `Idle` would hand `parked` back to ordinary
3434    /// priority-order dispatch, where a higher-priority task filed in the
3435    /// meantime could start ahead of it.
3436    Running {
3437        parked: Vec<String>,
3438        interrupt_task: String,
3439    },
3440    /// `interrupt_task` left flight; `parked` still names the one run this
3441    /// sequence owes a resume. Dispatch is withheld from everyone except
3442    /// that task - see [`interrupt_gate`] - so the resume this feature
3443    /// promises is never raced by, or run alongside, an unrelated candidate.
3444    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3445    /// own doc on abandonment - the moment it is no longer runnable at all.
3446    Resuming { parked: Vec<String> },
3447}
3448
3449/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3450/// and `runnable` are read-only snapshots of this tick's reality, and the
3451/// only side effect the caller still owes the world is asking whichever
3452/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3453/// site.
3454///
3455/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3456/// accepted rather than a narrower type because that is what [`poll`] already
3457/// has on hand from [`runnable`], and building a second, smaller list on
3458/// every tick just to satisfy this signature would cost more than it proves.
3459///
3460/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3461/// back to a task they are waiting on no longer being [`runnable`] - held,
3462/// blocked, deleted, or finished by some other means entirely, all of which
3463/// an operator can do to a task sitting in the queue with no claim on it at
3464/// all, at any moment, interrupt sequence or not. Without this check the
3465/// sequence would wait forever for a dispatch that can never come, and
3466/// `interrupt_gate` would withhold every other task in the queue right along
3467/// with it - a single `magi task hold` on the wrong id turning into a
3468/// daemon that never dispatches anything again.
3469fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3470    match state {
3471        Interrupt::Idle => {
3472            // Not just "something to interrupt": exactly one thing. More
3473            // than one run in flight only happens above the default
3474            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3475            // one resume, never run alongside anything else" only because
3476            // it is only ever seeded with exactly one id - see
3477            // `Interrupt::Resuming`'s own doc on why releasing more than one
3478            // parked id back to ordinary dispatch cannot be made safe
3479            // against that same setting's own extra concurrency slots.
3480            // Waiting here for the herd to settle to one is the
3481            // simplification this feature's own constraints ask for rather
3482            // than a second concurrency model to reconcile with the first.
3483            if in_flight.len() != 1 {
3484                return Interrupt::Idle;
3485            }
3486            match runnable.iter().find(|t| t.interrupt) {
3487                Some(t) => Interrupt::Parking {
3488                    parked: in_flight.to_vec(),
3489                    interrupt_task: t.id.clone(),
3490                },
3491                None => Interrupt::Idle,
3492            }
3493        }
3494        Interrupt::Parking {
3495            parked,
3496            interrupt_task,
3497        } => {
3498            if in_flight.iter().any(|id| parked.contains(id)) {
3499                // Still waiting for what was in flight to actually stop.
3500                Interrupt::Parking {
3501                    parked,
3502                    interrupt_task,
3503                }
3504            } else if in_flight.contains(&interrupt_task) {
3505                Interrupt::Running {
3506                    parked,
3507                    interrupt_task,
3508                }
3509            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3510                // The parked run(s) are gone, but the interrupt task has not
3511                // been dispatched yet on this tick - `interrupt_gate` is
3512                // what lets it through next.
3513                Interrupt::Parking {
3514                    parked,
3515                    interrupt_task,
3516                }
3517            } else {
3518                // The interrupt task itself is no longer runnable - see this
3519                // function's own doc on abandonment. The parked run(s) still
3520                // get their guaranteed resume; there is simply no interrupt
3521                // to run ahead of them any longer.
3522                Interrupt::Resuming { parked }
3523            }
3524        }
3525        Interrupt::Running {
3526            parked,
3527            interrupt_task,
3528        } => {
3529            if in_flight.contains(&interrupt_task) {
3530                Interrupt::Running {
3531                    parked,
3532                    interrupt_task,
3533                }
3534            } else {
3535                // The interrupt task's own run reached a terminal status,
3536                // whichever one - this is the *only* trigger that moves the
3537                // sequence on, driven straight off the same in-flight
3538                // bookkeeping `poll` already reaps every tick, not a second,
3539                // independent poll of anything.
3540                Interrupt::Resuming { parked }
3541            }
3542        }
3543        Interrupt::Resuming { parked } => {
3544            if in_flight.iter().any(|id| parked.contains(id)) {
3545                // One of the parked runs has been dispatched - the resume
3546                // this sequence owed is fulfilled. Whatever else is left in
3547                // `parked` (ordinarily nothing, at the default concurrency
3548                // of one) rejoins ordinary priority-order dispatch, same as
3549                // any other runnable task.
3550                Interrupt::Idle
3551            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3552                Interrupt::Resuming { parked }
3553            } else {
3554                // Abandonment (see this function's own doc): nothing left in
3555                // `parked` is even runnable any longer.
3556                Interrupt::Idle
3557            }
3558        }
3559    }
3560}
3561
3562/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3563/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3564/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3565/// indistinguishable from any other runnable task - exactly the "off does
3566/// nothing" this feature promises.
3567fn advance_interrupt_tick(
3568    enabled: bool,
3569    state: Interrupt,
3570    in_flight: &[String],
3571    runnable: &[Task],
3572) -> Interrupt {
3573    if !enabled {
3574        return Interrupt::Idle;
3575    }
3576    advance_interrupt(state, in_flight, runnable)
3577}
3578
3579/// Which of this tick's runnable candidates the interrupt sequence actually
3580/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3581/// each half is assertable on its own: this is the half that keeps a
3582/// competition and an interrupt from ever running at the same moment.
3583fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3584    match state {
3585        Interrupt::Idle => candidates,
3586        Interrupt::Parking {
3587            parked,
3588            interrupt_task,
3589        } => {
3590            if in_flight.iter().any(|id| parked.contains(id)) {
3591                Vec::new()
3592            } else {
3593                candidates
3594                    .into_iter()
3595                    .filter(|t| &t.id == interrupt_task)
3596                    .collect()
3597            }
3598        }
3599        Interrupt::Running { .. } => Vec::new(),
3600        // At most one: even if `parked` names more than one id (more than
3601        // one run was in flight when the sequence began, only possible
3602        // above the default `max_concurrent_runs = 1`), only the first match
3603        // is offered. Capping this to a single candidate - not merely to
3604        // `parked`'s own ids - is what makes "exactly one resume, never two
3605        // dispatched together" true regardless of how many ordinary slots
3606        // happen to be free this tick.
3607        Interrupt::Resuming { parked } => candidates
3608            .into_iter()
3609            .find(|t| parked.contains(&t.id))
3610            .into_iter()
3611            .collect(),
3612    }
3613}
3614
3615/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3616/// bundled into one parameter so `poll`'s own signature stays readable -
3617/// see [`drive`]'s call site for where these are actually read.
3618struct DispatchLimits {
3619    /// How many *ordinary* candidates run at once. See
3620    /// [`crate::config::Daemon::max_concurrent_runs`].
3621    max_concurrent: usize,
3622    /// See [`crate::config::Daemon::pause_for_interrupts`].
3623    pause_for_interrupts: bool,
3624    recovery_cfg: Option<Config>,
3625}
3626
3627/// Which semaphore, if any, dispatching a candidate should draw its permit
3628/// from.
3629///
3630/// Pure and separate from [`poll`]'s loop body for the same reason
3631/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3632/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3633/// exactly the policy this feature adds, and a policy only exercisable by
3634/// running the whole loop is a policy nobody checks.
3635#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3636enum PermitKind {
3637    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3638    /// Checked first - a task can be both a land resume and marked
3639    /// [`Task::urgent`], and the resume's own "must not queue behind
3640    /// anything" guarantee takes precedence.
3641    None,
3642    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3643    /// (never in addition to trying) the ordinary pool. This is what lets
3644    /// an urgent task dispatch while every ordinary slot is already checked
3645    /// out, and what stops a second urgent task from opening a third run: it
3646    /// waits on this same one-slot semaphore rather than falling through to
3647    /// the ordinary one.
3648    Urgent,
3649    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3650    /// above.
3651    #[default]
3652    Ordinary,
3653}
3654
3655/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3656/// own boolean, already computed by the caller from [`land_resume_state`].
3657fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3658    if priority {
3659        PermitKind::None
3660    } else if urgent {
3661        PermitKind::Urgent
3662    } else {
3663        PermitKind::Ordinary
3664    }
3665}
3666
3667fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3668    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3669        (0usize, 0usize),
3670        |(ordinary, urgent), request| match request.lane {
3671            PermitKind::Ordinary => (ordinary + 1, urgent),
3672            PermitKind::Urgent => (ordinary, urgent + 1),
3673            PermitKind::None => (ordinary, urgent),
3674        },
3675    );
3676    (
3677        limit.saturating_sub(ordinary),
3678        1usize.saturating_sub(urgent),
3679    )
3680}
3681
3682/// Why a runnable candidate was not dispatched. This does not alter policy.
3683#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3684enum SkipReason {
3685    ClaimUnavailable,
3686    RereadFailed,
3687    NoLongerRunnable,
3688    WaitingOnLanding,
3689    CoolingDown,
3690    OrdinaryCapacity,
3691    UrgentCapacity,
3692    InterruptGate,
3693}
3694
3695impl SkipReason {
3696    fn key(self) -> &'static str {
3697        match self {
3698            Self::ClaimUnavailable => "claim_unavailable",
3699            Self::RereadFailed => "reread_failed",
3700            Self::NoLongerRunnable => "no_longer_runnable",
3701            Self::WaitingOnLanding => "waiting_on_landing",
3702            Self::CoolingDown => "cooling_down",
3703            Self::OrdinaryCapacity => "ordinary_capacity",
3704            Self::UrgentCapacity => "urgent_capacity",
3705            Self::InterruptGate => "interrupt_gate",
3706        }
3707    }
3708
3709    fn describe(self) -> &'static str {
3710        match self {
3711            Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3712            Self::RereadFailed => "could not re-read it",
3713            Self::NoLongerRunnable => "no longer runnable",
3714            Self::WaitingOnLanding => "waiting on landing",
3715            Self::CoolingDown => "quota cooldown",
3716            Self::OrdinaryCapacity => "no free ordinary slot",
3717            Self::UrgentCapacity => "urgent slot busy",
3718            Self::InterruptGate => "withheld by the interrupt sequence",
3719        }
3720    }
3721}
3722
3723/// A reason count from a completed dispatch scan.
3724#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3725pub struct DispatchReasonCount {
3726    /// Stable string key, so readers can preserve future reasons.
3727    pub reason: String,
3728    /// Candidates skipped for this reason.
3729    pub count: usize,
3730}
3731
3732/// Observations from a completed scan, not a fresh queue estimate.
3733#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3734pub struct DispatchWait {
3735    /// Runnable candidates before the interrupt gate.
3736    pub runnable: usize,
3737    /// Counts in descending order, with stable reason order for ties.
3738    pub reasons: Vec<DispatchReasonCount>,
3739}
3740
3741type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3742
3743fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3744    if runnable == 0 {
3745        return None;
3746    }
3747    let mut counts = std::collections::BTreeMap::new();
3748    for (_, reason) in skips {
3749        *counts.entry(*reason).or_insert(0usize) += 1;
3750    }
3751    let mut counts: Vec<_> = counts.into_iter().collect();
3752    counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3753    Some(DispatchWait {
3754        runnable,
3755        reasons: counts
3756            .into_iter()
3757            .map(|(reason, count)| DispatchReasonCount {
3758                reason: reason.key().to_owned(),
3759                count,
3760            })
3761            .collect(),
3762    })
3763}
3764
3765fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3766    before
3767        .iter()
3768        .filter(|id| !after.iter().any(|task| &task.id == *id))
3769        .map(|id| (id.clone(), SkipReason::InterruptGate))
3770        .collect()
3771}
3772
3773fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3774    if *previous == current {
3775        return false;
3776    }
3777    *previous = current;
3778    true
3779}
3780
3781struct DispatchClaim {
3782    task: Task,
3783    claim: crate::queue::Claim,
3784    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3785}
3786
3787/// Claim and re-read before choosing a lane: a queue listing may predate an
3788/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3789fn claim_dispatch(
3790    queue: &Queue,
3791    candidate: &Task,
3792    cooling_down: bool,
3793    ordinary: &Arc<tokio::sync::Semaphore>,
3794    urgent: &Arc<tokio::sync::Semaphore>,
3795) -> std::result::Result<DispatchClaim, SkipReason> {
3796    let claim = queue
3797        .claim(&candidate.id)
3798        .map_err(|_| SkipReason::ClaimUnavailable)?;
3799    let task = match queue.get(&candidate.id) {
3800        Ok(t) if t.status.runnable() => t,
3801        Ok(_) => return Err(SkipReason::NoLongerRunnable),
3802        Err(e) => {
3803            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3804            return Err(SkipReason::RereadFailed);
3805        }
3806    };
3807    if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, &task) {
3808        let mut held = task;
3809        hold.apply(&mut held);
3810        record(queue, &mut held);
3811        return Err(SkipReason::NoLongerRunnable);
3812    }
3813    let resume = land_resume_state(&task);
3814    if resume == LandResume::StillWaiting {
3815        return Err(SkipReason::WaitingOnLanding);
3816    }
3817    let priority = resume == LandResume::Ready;
3818    if !priority && cooling_down {
3819        return Err(SkipReason::CoolingDown);
3820    }
3821    // Never borrow an ordinary slot when the single urgent slot is busy.
3822    // Keep scanning other candidates when either pool has no free slot.
3823    let permit = match permit_kind(priority, task.urgent) {
3824        PermitKind::None => None,
3825        PermitKind::Urgent => Some(
3826            Arc::clone(urgent)
3827                .try_acquire_owned()
3828                .map_err(|_| SkipReason::UrgentCapacity)?,
3829        ),
3830        PermitKind::Ordinary => Some(
3831            Arc::clone(ordinary)
3832                .try_acquire_owned()
3833                .map_err(|_| SkipReason::OrdinaryCapacity)?,
3834        ),
3835    };
3836    // Persist the dispatch order under the claim, before config discovery or
3837    // coordination waits can reorder concurrent starts.
3838    let stamp = Timestamp::now();
3839    let mut task = task;
3840    task.dispatched_at = Some(stamp);
3841    if let Err(e) = queue.modify(&task.id, |t| {
3842        t.dispatched_at = Some(stamp);
3843        true
3844    }) {
3845        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3846    }
3847    Ok(DispatchClaim {
3848        task,
3849        claim,
3850        permit,
3851    })
3852}
3853
3854/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3855/// teardown and cannot skip the teardown on an early return.
3856///
3857/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3858/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3859/// land approval that has since been answered is dispatched outside that
3860/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3861/// the whole point of parking there is that it must not queue behind
3862/// whatever else the loop happens to be running, even at the default of one.
3863/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3864/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3865/// these exemptions is still subject to the interrupt gate below, urgent
3866/// included: a land-resume or urgent candidate is exactly as much "something
3867/// else running" as an ordinary one from the interrupt sequence's point of
3868/// view, and letting either slip through while a run is being parked, or
3869/// while the interrupt task itself has the floor, is precisely the second
3870/// run 75dd's own "at most one run, ever, at once" guarantee must never
3871/// allow - see [`Interrupt`]'s own doc.
3872#[derive(Serialize, Deserialize)]
3873struct ServiceWorker {
3874    opts: Opts,
3875    queue: PathBuf,
3876    worktrees_root: PathBuf,
3877    operation: String,
3878}
3879
3880fn load_conductor(home: &Path) -> Result<Conductor> {
3881    match std::fs::read(home.join("conductor-state.json")) {
3882        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3883        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3884        Err(error) => Err(error.into()),
3885    }
3886}
3887
3888fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3889    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3890        .into_iter()
3891        .map(|c| c.task)
3892        .collect();
3893    let stalled = stalled_tasks(queue, home, Timestamp::now());
3894    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3895    let finished = finished_tasks(queue)
3896        .into_iter()
3897        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3898        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3899        .collect();
3900    let queued = queued_tasks(queue)
3901        .into_iter()
3902        .filter(|t| !live.contains(&t.id))
3903        .collect();
3904    (queued, stalled, finished)
3905}
3906
3907// Separate latest dispatch and worker receipts expose version handoff and skips
3908// without erasing the last completed scan or treating observations as authority.
3909fn retention_service_receipt(
3910    home: &Path,
3911    operation: &str,
3912    phase: &str,
3913    outcome: &str,
3914    detail: &str,
3915    cfg: Option<&Config>,
3916) {
3917    if !matches!(operation, "housekeeping" | "disk-pressure") {
3918        return;
3919    }
3920    let receipt = serde_json::json!({"checked_at": Timestamp::now(),
3921        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
3922        "operation": operation, "outcome": outcome, "detail": detail,
3923        "auto_fold": cfg.map(|c| c.disk.auto_fold),
3924        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
3925    if let Err(error) = crate::fold_evidence::atomic_write(
3926        &home.join(format!("source-eviction-{operation}-{phase}.json")),
3927        &serde_json::to_vec(&receipt).expect("service receipt"),
3928    ) {
3929        tracing::warn!("retention service receipt failed: {error:#}");
3930    }
3931}
3932
3933async fn start_service(
3934    home: &Path,
3935    opts: &Opts,
3936    queue: &Queue,
3937    worktrees_root: &Path,
3938    operation: &str,
3939    cfg: Option<&Config>,
3940    busy: bool,
3941) -> Result<()> {
3942    // Fetch policy is live configuration, unlike question recovery capacity.
3943    // Reload before both cadence and eligibility, including disabled -> enabled.
3944    let fetch_cfg = if operation == "fetch" {
3945        match prepare(&opts.repo, opts) {
3946            Ok(cfg) => Some(cfg),
3947            Err(error) => {
3948                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3949                return Ok(());
3950            }
3951        }
3952    } else {
3953        None
3954    };
3955    let cfg = fetch_cfg.as_ref().or(cfg);
3956    let ticks = home.join("service-ticks");
3957    std::fs::create_dir_all(&ticks)?;
3958    let receipt = ticks.join(format!("daemon-{operation}"));
3959    let last = std::fs::read(&receipt)
3960        .ok()
3961        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3962    let interval = match operation {
3963        "disk-pressure" => 30,
3964        "chat-goals" => 60,
3965        "cache" => CACHE_CHECK_INTERVAL_SECS,
3966        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3967        _ => opts.poll.as_secs().max(1),
3968    };
3969    let now = Timestamp::now();
3970    if !cache_check_due(last, now, interval) {
3971        retention_service_receipt(
3972            home,
3973            operation,
3974            "dispatch",
3975            "skipped",
3976            "cadence not due",
3977            cfg,
3978        );
3979        return Ok(());
3980    }
3981    let key = format!("service:daemon-{operation}");
3982    if crate::worker::active(home)?
3983        .iter()
3984        .any(|job| job.key == key)
3985    {
3986        retention_service_receipt(
3987            home,
3988            operation,
3989            "dispatch",
3990            "skipped",
3991            "service worker already active",
3992            cfg,
3993        );
3994        return Ok(());
3995    }
3996    let eligible = match operation {
3997        "conductor" => {
3998            let (queued, stalled, finished) = conductor_work(queue, home);
3999            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4000                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
4001        }
4002        "maintenance" => {
4003            queue.list().iter().any(|task| {
4004                crate::triage::disk_wait_eligible(task)
4005                    && task
4006                        .disk_checked_at
4007                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
4008            }) || Questions::at(home.join("questions"))
4009                .list_for_effects()
4010                .iter()
4011                .any(|q| {
4012                    q.chosen_action().is_some_and(|action| action.maintenance())
4013                        && !home
4014                            .join("choice-actions")
4015                            .join(format!("{}.json", q.id))
4016                            .exists()
4017                })
4018        }
4019        "housekeeping" => !busy && runnable(queue).is_empty(),
4020        "cache" => {
4021            !busy
4022                && !runnable(queue).is_empty()
4023                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
4024        }
4025        "disk-pressure" => busy,
4026        "fetch" => {
4027            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
4028        }
4029        "chat-goals" => crate::talk::Talks::at(home.join("talks"))
4030            .list()
4031            .iter()
4032            .any(|talk| {
4033                talk.status.open()
4034                    && talk.pending.is_empty()
4035                    && talk.pending_attachments.is_empty()
4036                    && talk.goals.iter().any(|goal| goal.active())
4037            }),
4038        _ => false,
4039    };
4040    if !eligible {
4041        retention_service_receipt(
4042            home,
4043            operation,
4044            "dispatch",
4045            "skipped",
4046            if operation == "housekeeping" {
4047                "active work or runnable task queue"
4048            } else {
4049                "no active work; idle housekeeping owns scan"
4050            },
4051            cfg,
4052        );
4053        return Ok(());
4054    }
4055    retention_service_receipt(
4056        home,
4057        operation,
4058        "dispatch",
4059        "launching",
4060        "eligible and cadence due",
4061        cfg,
4062    );
4063    let request = ServiceWorker {
4064        opts: opts.absolute()?,
4065        queue: std::path::absolute(queue.root())?,
4066        worktrees_root: std::path::absolute(worktrees_root)?,
4067        operation: operation.to_owned(),
4068    };
4069    if let Err(error) =
4070        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
4071    {
4072        retention_service_receipt(
4073            home,
4074            operation,
4075            "dispatch",
4076            "error",
4077            &format!("worker launch: {error:#}"),
4078            cfg,
4079        );
4080        tracing::warn!(operation, "could not launch daemon service: {error:#}");
4081    }
4082    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
4083    Ok(())
4084}
4085
4086/// Finite maintenance jobs survive scheduler replacement without duplicating
4087/// agent calls or cancelling an operation between its effect and receipt.
4088pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
4089    let request: ServiceWorker = serde_json::from_value(payload)?;
4090    let opts = &request.opts;
4091    let queue = Queue::at(request.queue);
4092    let questions = Questions::at(home.join("questions"));
4093    match request.operation.as_str() {
4094        "chat-goals" => {
4095            let talks = crate::talk::Talks::at(home.join("talks"));
4096            crate::chat_goal_runtime::sweep(&talks, false).await;
4097        }
4098        "maintenance" => {
4099            apply_maintenance_choices(&queue, &questions, home).await;
4100            triage::monitor_disk_waits(
4101                &queue,
4102                &questions,
4103                opts.config.as_deref(),
4104                Timestamp::now(),
4105            );
4106        }
4107        "conductor" => {
4108            let path = home.join("conductor-state.json");
4109            let mut conductor = load_conductor(home)?;
4110            let (queued, stalled, finished) = conductor_work(&queue, home);
4111            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4112                && conductor.worth_a_look(&queue, &stalled, &finished)
4113            {
4114                let cfg = prepare(&opts.repo, opts)?;
4115                conductor
4116                    .maybe_run(
4117                        &cfg,
4118                        &opts.repo,
4119                        &queue,
4120                        &questions,
4121                        home,
4122                        &queued,
4123                        &stalled,
4124                        &finished,
4125                        opts.max_attempts,
4126                    )
4127                    .await;
4128                let temporary = path.with_extension("json.tmp");
4129                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
4130                std::fs::rename(temporary, path)?;
4131            }
4132        }
4133        "fetch" => {
4134            let cfg = prepare(&opts.repo, opts)?;
4135            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
4136                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
4137                tracing::debug!("fetch origins: {outcome:?}");
4138            }
4139        }
4140        "cache" => {
4141            if task_jobs(home)?.is_empty() {
4142                let mut checked = None;
4143                maybe_prune_cache_between_runs(
4144                    &opts.repo,
4145                    opts,
4146                    home,
4147                    &Stop::new(),
4148                    &mut checked,
4149                    Timestamp::now(),
4150                )
4151                .await;
4152            }
4153        }
4154        "disk-pressure" => {
4155            if let Ok(cfg) = prepare(&opts.repo, opts) {
4156                retention_service_receipt(
4157                    home,
4158                    "disk-pressure",
4159                    "worker",
4160                    "running",
4161                    "retention sweep",
4162                    Some(&cfg),
4163                );
4164                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4165                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
4166                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
4167                }
4168                if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
4169                    tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
4170                }
4171                for current in current_work(home, Timestamp::now()) {
4172                    if let Ok(state) = RunState::load_under(&current.run, home)
4173                        && let Some(reason) = disk_gate(&state.repo, &state.config)
4174                    {
4175                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
4176                            job.key.strip_prefix("task:") == Some(current.task.as_str())
4177                        }) {
4178                            request_task_park(
4179                                home,
4180                                &job,
4181                                crate::run::ParkCause::Interrupt {
4182                                    reason: reason.clone(),
4183                                },
4184                            )?;
4185                        }
4186                        notices::raise_in(
4187                            home,
4188                            Notice::warn(
4189                                "disk:pressure",
4190                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
4191                            ),
4192                        );
4193                    }
4194                }
4195            } else {
4196                retention_service_receipt(
4197                    home,
4198                    "disk-pressure",
4199                    "worker",
4200                    "error",
4201                    "configuration could not be loaded",
4202                    None,
4203                );
4204            }
4205        }
4206        "housekeeping" => {
4207            if task_jobs(home)?.is_empty() {
4208                match prepare(&opts.repo, opts) {
4209                    Ok(cfg) => {
4210                        retention_service_receipt(
4211                            home,
4212                            "housekeeping",
4213                            "worker",
4214                            "running",
4215                            "retention sweep",
4216                            Some(&cfg),
4217                        );
4218                        crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4219                    }
4220                    Err(error) => retention_service_receipt(
4221                        home,
4222                        "housekeeping",
4223                        "worker",
4224                        "error",
4225                        &format!("configuration: {error:#}"),
4226                        None,
4227                    ),
4228                }
4229                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
4230                resweep_superseded_attempts(&queue, home);
4231                triage_held(&queue, home, opts).await;
4232            } else {
4233                retention_service_receipt(
4234                    home,
4235                    "housekeeping",
4236                    "worker",
4237                    "skipped",
4238                    "task worker became active",
4239                    None,
4240                );
4241            }
4242        }
4243        operation => bail!("unknown daemon service {operation}"),
4244    }
4245    Ok(())
4246}
4247
4248/// Only a different request under the same key is a dispatch handoff race.
4249/// Our own unacknowledged reservation is a startup failure, not competing work:
4250/// stop dispatch without fencing it, so an already detached child may still run.
4251fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
4252    let key = format!("task:{}", request.task);
4253    let payload = serde_json::to_value(request)?;
4254    if crate::worker::active(home)?
4255        .iter()
4256        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
4257    {
4258        tracing::warn!(
4259            "task {} acquired a competing worker reservation: {error:#}",
4260            crate::run::short_of(&request.task)
4261        );
4262        return Ok(());
4263    }
4264    tracing::error!("task worker startup stopped dispatch: {error:#}");
4265    notices::raise_in(
4266        home,
4267        Notice::error(
4268            "loop:worker-startup",
4269            // Startup diagnostics may contain private child-process details;
4270            // keep them in the local error/log rather than the chat or notifier.
4271            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),
4272        ).link(Link::Task { id: request.task.clone() }),
4273    );
4274    Err(error).with_context(|| {
4275        format!(
4276            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
4277            crate::run::short_of(&request.task)
4278        )
4279    })
4280}
4281
4282async fn poll(
4283    opts: &Opts,
4284    queue: &Queue,
4285    status: &Arc<Mutex<Status>>,
4286    home: &Path,
4287    worktrees_root: &Path,
4288    stop: &Stop,
4289    limits: DispatchLimits,
4290) -> Result<()> {
4291    let mut attempted = Vec::new();
4292    let mut settling_once_services = false;
4293    let interrupt_path = home.join("scheduler-interrupt.json");
4294    let mut interrupt = match std::fs::read(&interrupt_path) {
4295        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
4296        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
4297        Err(error) => return Err(error.into()),
4298    };
4299    let mut previous = std::collections::BTreeSet::<String>::new();
4300    let mut previous_skips = DispatchSkips::new();
4301    while !stop.stopped() {
4302        let jobs: Vec<_> = crate::worker::active(home)?
4303            .into_iter()
4304            .filter(|job| job.kind == "task")
4305            .collect();
4306        let requests: Vec<_> = jobs
4307            .iter()
4308            .map(|job| {
4309                serde_json::from_value::<TaskWorker>(job.payload.clone())
4310                    .with_context(|| format!("read live task worker {}", job.id))
4311            })
4312            .collect::<Result<_>>()?;
4313        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4314        let owned: std::collections::BTreeSet<_> = requests
4315            .iter()
4316            .filter(|r| !r.standalone)
4317            .map(|r| r.task.clone())
4318            .collect();
4319        let current: Vec<_> = requests
4320            .iter()
4321            .zip(&jobs)
4322            .filter(|(request, _)| !request.standalone)
4323            .map(|(request, job)| Current {
4324                worker: Some(job.id.clone()),
4325                task: request.task.clone(),
4326                run: queue
4327                    .get(&request.task)
4328                    .ok()
4329                    .and_then(|task| task.execution_runs().last().cloned())
4330                    .unwrap_or_default(),
4331            })
4332            .collect();
4333        {
4334            let mut snapshot = lock(status);
4335            snapshot.polls += 1;
4336            snapshot.completed += previous.difference(&owned).count();
4337            snapshot.current = current;
4338            snapshot.idle = owned.is_empty();
4339            snapshot.dispatch_wait = None;
4340        }
4341        previous = owned.clone();
4342        stop.busy.store(owned.len(), Ordering::SeqCst);
4343
4344        // Slots are reconstructed from durable reservations and OS-held worker
4345        // leases, not this scheduler's lifetime or mutable task urgency.
4346        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4347        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4348        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4349        let mut permits = Vec::new();
4350        sweep_stale_claims(queue, STALE_CLAIM);
4351        reclaim_orphaned_running(queue, opts.max_attempts, &live);
4352        reclaim_abandoned_runs(home, Timestamp::now());
4353        let questions = Questions::at(home.join("questions"));
4354
4355        // Deterministic: no model, run before the conductor sees anything so
4356        // its input reflects the queue's current, already-resolved state.
4357        crate::task_chat::sweep(
4358            queue,
4359            &crate::talk::Talks::at(home.join("talks")),
4360            &questions,
4361            home,
4362        );
4363        if let Err(error) = crate::task_inquiry::Outbox::at(home)
4364            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4365        {
4366            tracing::warn!("task inquiry delivery remains pending: {error:#}");
4367        }
4368        repair_choice_offers(&questions);
4369        resolve_blockers(queue, &questions);
4370        apply_task_choice_actions(queue, &questions, home);
4371        triage::apply_answers(queue, &questions);
4372        reconcile_task_questions(queue, &questions);
4373        let talks = crate::talk::Talks::at(home.join("talks"));
4374        crate::chat_notify::sweep(queue, &talks, home);
4375        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4376        crate::chat_watch::sweep(home, &talks);
4377        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4378            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4379        }
4380        let mut turns = tokio::task::JoinSet::new();
4381        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4382        // start_turns dispatches detached turns; no paid work lives in this set.
4383        while turns.join_next().await.is_some() {}
4384
4385        crate::consult::start_services(
4386            home,
4387            &opts.repo,
4388            limits.recovery_cfg.as_ref(),
4389            opts.config.as_deref(),
4390        )
4391        .await?;
4392        for operation in [
4393            "conductor",
4394            "maintenance",
4395            "housekeeping",
4396            "disk-pressure",
4397            "cache",
4398            "fetch",
4399            "chat-goals",
4400        ] {
4401            // Once an idle --once drain starts settling services, subsequent
4402            // scans only consume their effects. An expired cadence receipt
4403            // must not start another service and keep the drain alive.
4404            if settling_once_services {
4405                break;
4406            }
4407            if operation == "chat-goals" && stop.parking() {
4408                continue;
4409            }
4410            start_service(
4411                home,
4412                opts,
4413                queue,
4414                worktrees_root,
4415                operation,
4416                limits.recovery_cfg.as_ref(),
4417                !live.is_empty(),
4418            )
4419            .await?;
4420        }
4421        let latest = crate::worker::active(home)?;
4422        if latest.iter().any(|job| job.key == "service:daemon-cache")
4423            || latest
4424                .iter()
4425                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4426        {
4427            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4428            continue;
4429        }
4430        let candidates: Vec<Task> = runnable(queue)
4431            .into_iter()
4432            .filter(|task| !live.contains(&task.id))
4433            .filter(|task| !opts.once || !attempted.contains(&task.id))
4434            .collect();
4435        let in_flight: Vec<_> = owned.iter().cloned().collect();
4436        let prior_interrupt = std::mem::discriminant(&interrupt);
4437        interrupt = advance_interrupt_tick(
4438            limits.pause_for_interrupts,
4439            interrupt,
4440            &in_flight,
4441            &candidates,
4442        );
4443        // Same-variant transitions preserve their identities. Only an actual
4444        // transition needs a durable write, atomically before sending controls.
4445        if prior_interrupt != std::mem::discriminant(&interrupt) {
4446            let temporary = interrupt_path.with_extension("json.tmp");
4447            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4448            std::fs::rename(temporary, &interrupt_path)?;
4449        }
4450        if let Interrupt::Parking {
4451            parked,
4452            interrupt_task,
4453        } = &interrupt
4454        {
4455            for job in jobs.iter().filter(|job| {
4456                parked
4457                    .iter()
4458                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4459            }) {
4460                if crate::worker::control(home, &job.key)?.is_none() {
4461                    request_task_park(
4462                        home,
4463                        job,
4464                        crate::run::ParkCause::Interrupt {
4465                            reason: format!(
4466                                "task {} asked to run first",
4467                                crate::run::short_of(interrupt_task)
4468                            ),
4469                        },
4470                    )?;
4471                }
4472            }
4473        }
4474        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
4475        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4476        let mut skips = interrupt_skips(&candidate_ids, &candidates);
4477        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4478        let mut started = false;
4479        let mut resync = false;
4480        for candidate in candidates {
4481            if stop.stopped() {
4482                break;
4483            }
4484            let DispatchClaim {
4485                task,
4486                claim,
4487                permit,
4488            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
4489                Ok(claim) => claim,
4490                Err(reason) => {
4491                    skips.insert((candidate.id, reason));
4492                    continue;
4493                }
4494            };
4495            if crate::worker::active(home)?
4496                .iter()
4497                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4498            {
4499                drop(claim);
4500                resync = true;
4501                break;
4502            }
4503            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4504            let request = TaskWorker {
4505                opts: opts.absolute()?,
4506                queue: std::path::absolute(queue.root())?,
4507                task: task.id.clone(),
4508                lane,
4509                standalone: false,
4510            };
4511            // Keep the claim until spawn acknowledges the worker's durable
4512            // reservation. The worker then claims and re-reads before attempt.
4513            if let Err(error) = crate::worker::spawn(
4514                home,
4515                "task",
4516                &format!("task:{}", task.id),
4517                serde_json::to_value(&request)?,
4518            )
4519            .await
4520            {
4521                task_worker_spawn_error(home, &request, error)?;
4522                drop(claim);
4523                resync = true;
4524                break;
4525            }
4526            drop(claim);
4527            permits.extend(permit);
4528            attempted.push(task.id);
4529            started = true;
4530        }
4531        if !resync && !stop.stopped() {
4532            if !started {
4533                lock(status).dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
4534            }
4535            if changed_dispatch_skips(&mut previous_skips, skips) {
4536                if previous_skips.is_empty() {
4537                    tracing::info!("dispatch skips cleared");
4538                }
4539                for (task, reason) in &previous_skips {
4540                    tracing::info!(
4541                        task,
4542                        reason = reason.key(),
4543                        "task {} skipped: {}",
4544                        crate::run::short_of(task),
4545                        reason.describe()
4546                    );
4547                }
4548            }
4549        }
4550        if started || resync {
4551            continue;
4552        }
4553        if owned.is_empty() && opts.once {
4554            settling_once_services = true;
4555            // These finite services can own queue claims or publish answers.
4556            // A skipped claim is not an idle queue until they have finished;
4557            // scan again afterwards so their changes are actually scheduled.
4558            if crate::worker::active(home)?.iter().any(|job| {
4559                job.kind == "daemon-service"
4560                    && matches!(
4561                        job.key.as_str(),
4562                        "service:daemon-housekeeping"
4563                            | "service:daemon-conductor"
4564                            | "service:daemon-maintenance"
4565                    )
4566            }) {
4567                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4568                continue;
4569            }
4570            break;
4571        }
4572        stop.idle(if live.is_empty() {
4573            opts.poll
4574        } else {
4575            RECHECK_WHILE_BUSY.min(opts.poll)
4576        })
4577        .await;
4578    }
4579    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4580    // every queue claim and Runner driver lease through outcome settlement.
4581    stop.busy.store(0, Ordering::SeqCst);
4582    lock(status).dispatch_wait = None;
4583    Ok(())
4584}
4585
4586/// A maintenance pass may briefly own the same record while a worker starts.
4587/// Wait without blocking the executor or charging an agent attempt, then read
4588/// ownership again under the acquired lock. Other I/O failures still fail closed.
4589async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4590    let busy = |error: &anyhow::Error| {
4591        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4592            error.kind() == std::io::ErrorKind::WouldBlock
4593                || cfg!(windows) && error.raw_os_error() == Some(33)
4594        })
4595    };
4596    match crate::pr_head::owner_lock(home, id) {
4597        Ok(lock) => return Ok(lock),
4598        Err(error) if busy(&error) => {}
4599        Err(error) => return Err(error),
4600    }
4601    let wait = RunState::load_under(id, home)?
4602        .config
4603        .graph
4604        .timeout_resource_wait;
4605    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4606}
4607
4608/// Historical successors do not revoke a still-resumable public owner. Scan
4609/// under the same lock as publication/driver claims, and fail closed on unknown
4610/// history before spending another attempt.
4611async fn public_resume_owner(
4612    home: &Path,
4613    runs: &[String],
4614    repo: &Path,
4615) -> Result<Option<RunState>> {
4616    let mut owner = None;
4617    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4618        let _lock = resume_owner_lock(home, id).await?;
4619        let state = RunState::load_under(id, home)?;
4620        if state.released()
4621            || state.retired_to.is_some()
4622            || state.pr_taken_over_by.is_some()
4623            || !crate::handover::landing_checkpoint(&state)
4624        {
4625            continue;
4626        }
4627        anyhow::ensure!(
4628            crate::git::toplevel(&state.repo).await?.canonicalize()?
4629                == crate::git::toplevel(repo).await?.canonicalize()?,
4630            "public owner repository differs; inspect run lineage"
4631        );
4632        anyhow::ensure!(
4633            owner.is_none(),
4634            "multiple retained public owners; inspect run lineage"
4635        );
4636        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4637            anyhow::bail!(reason.diagnostic(&state));
4638        }
4639        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4640        anyhow::ensure!(
4641            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4642            "public owner's driver is live or unknown; wait before retrying"
4643        );
4644        owner = Some(state);
4645    }
4646    Ok(owner)
4647}
4648
4649/// Run one claimed task to a terminal status and record the outcome.
4650///
4651/// Every transition is flushed to the queue as it happens, so the state on disk
4652/// is what actually occurred rather than what this process still intends to
4653/// write.
4654async fn attempt(
4655    opts: &Opts,
4656    queue: &Queue,
4657    status: &Arc<Mutex<Status>>,
4658    stop: &Stop,
4659    interrupt_pause: crate::graph::Pause,
4660    task: &mut Task,
4661) -> Vec<QuotaLoss> {
4662    if let Some(request) = task.sync_only.clone() {
4663        Box::pin(attempt_sync_only(
4664            queue,
4665            status,
4666            stop,
4667            interrupt_pause,
4668            task,
4669            request,
4670        ))
4671        .await;
4672        return Vec::new();
4673    }
4674    let repo = repo_for(task, &opts.repo);
4675    tracing::info!(
4676        "task {} — {} (repo {})",
4677        task.short(),
4678        task.title,
4679        repo.display()
4680    );
4681
4682    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4683        Ok(owner) => owner,
4684        Err(e) => {
4685            task.hold_machine(Some(format!(
4686                "Cannot verify existing public owner: {e:#}; no attempt started."
4687            )));
4688            record(queue, task);
4689            return Vec::new();
4690        }
4691    };
4692    let resume_runs = public_owner
4693        .as_ref()
4694        .map(|s| vec![s.id.clone()])
4695        .unwrap_or_else(|| task.execution_runs().to_vec());
4696
4697    // A stop spends no agent resources and uses the saved landing owner.
4698    // Current roster edits, missing attachments or a failed config fetch must
4699    // never turn it into a new implementation, or prevent a PR from closing.
4700    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4701        && previous
4702            .merge_decision
4703            .as_ref()
4704            .is_some_and(|decision| !decision.closed)
4705        && previous.status != RunStatus::Landing
4706        && !crate::merge_decision::resumable_hold(&previous)
4707    {
4708        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)));
4709        record(queue, task);
4710        return Vec::new();
4711    }
4712    let stop_owner = resume_runs
4713        .last()
4714        .and_then(|id| RunState::load(id).ok())
4715        .filter(|state| {
4716            crate::merge_decision::resumable_hold(state)
4717                || state.status == RunStatus::Landing
4718                    && state.land_approval.as_ref().is_some_and(|binding| {
4719                        Questions::open()
4720                            .get_for_effects(&binding.question)
4721                            .is_ok_and(|q| {
4722                                q.run == state.id
4723                                    && q.resolution()
4724                                        .as_deref()
4725                                        .is_some_and(crate::merge_decision::stops)
4726                            })
4727                    })
4728        });
4729    if let Some(owner) = stop_owner {
4730        let mut runner = match Runner::resume(&owner.id) {
4731            Ok(runner) => runner,
4732            Err(e) => {
4733                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4734                record(queue, task);
4735                return Vec::new();
4736            }
4737        };
4738        runner.on_pause(stop.pause());
4739        runner.watch_interrupt(interrupt_pause);
4740        let quota_before = runner.state.quota.clone();
4741        let before_start = task.clone();
4742        task.start(owner.id.clone());
4743        if let Err(error) = queue.put(task) {
4744            *task = before_start;
4745            let error = runner.fail_startup("task-start", error);
4746            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4747                task.record_startup_failure(failure.clone());
4748            }
4749            task.hold_manual(Some(format!(
4750                "Could not persist task start; no agents dispatched: {error:#}"
4751            )));
4752            record(queue, task);
4753            return Vec::new();
4754        }
4755        lock(status).current.push(Current {
4756            worker: None,
4757            task: task.id.clone(),
4758            run: owner.id,
4759        });
4760        runner.state.carry_dispatched_resumes(task);
4761        runner.state.next_pass_task_entry = true;
4762        let result = runner.execute().await;
4763        return finish_attempt(
4764            opts.max_attempts,
4765            queue,
4766            task,
4767            &runner.state,
4768            &quota_before,
4769            result,
4770        );
4771    }
4772
4773    if let Some(owner) = &public_owner
4774        && (task.fresh_start || !may_resume_run(owner, task))
4775    {
4776        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)));
4777        record(queue, task);
4778        return Vec::new();
4779    }
4780
4781    if let Some(state) = task
4782        .execution_runs()
4783        .last()
4784        .and_then(|id| RunState::load(id).ok())
4785        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4786    {
4787        task.hold_machine(Some(reason));
4788        record(queue, task);
4789        return Vec::new();
4790    }
4791
4792    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4793        && !task.fresh_start
4794        && task.pr_recovery.is_none()
4795    {
4796        // A pinned infrastructure resume continues the saved reservation;
4797        // it does not authorize another base-sync interval.
4798        let sequencer_resume = crate::repair_budget::legacy::resumable_sequencer_stop(&held)
4799            && task.review_branch.is_none()
4800            && task.assignment_accepts(&held)
4801            && compatible_run_instruction(&held, task)
4802            && task
4803                .resume_override
4804                .as_ref()
4805                .is_some_and(|pin| pin.pinned_run.as_ref() == Some(&held.id));
4806        // Exhaustion authorization still takes the owner lock and execution
4807        // lease and rechecks liveness, retained HEAD and ownership.
4808        let authorized = if sequencer_resume || crate::repair_budget::conflict_pending(task, &held)
4809        {
4810            true
4811        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4812            let home = queue.root().parent().expect("queue has a home");
4813            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4814                Ok(()) => true,
4815                Err(error) => {
4816                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4817                    false
4818                }
4819            }
4820        } else {
4821            false
4822        };
4823        if !authorized {
4824            task.hold_machine(Some(format!("Base synchronization remains stopped. {} A release without a new owner approval grants no additional synchronization budget and starts no replacement competition.", held.base_sync_next_action())));
4825            // Retain the existing stop identity when an old release reached the queue.
4826            task.base_sync_notice(&held);
4827            task.resume_override = None;
4828            record(queue, task);
4829            return Vec::new();
4830        }
4831    }
4832    let head_e2e_approval = match crate::head_e2e_stop::check_attempt(queue, task) {
4833        Some(crate::head_e2e_stop::AttemptGate::Hold(hold)) => {
4834            hold.apply(task);
4835            record(queue, task);
4836            return Vec::new();
4837        }
4838        Some(crate::head_e2e_stop::AttemptGate::ConsumeOwnerApproval {
4839            run,
4840            stop_id,
4841            generation,
4842            approval_at,
4843        }) => Some((run, stop_id, generation, approval_at)),
4844        None => None,
4845    };
4846    let unfinished = (!task.fresh_start)
4847        .then(|| unfinished_run(&resume_runs, task.short()))
4848        .flatten()
4849        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4850    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4851    if task.repair_grants.last().is_some_and(|receipt| {
4852        task.execution_runs().last() == Some(&receipt.request.run)
4853            && task.operator_decided_at == receipt.decision
4854            && previous
4855                .as_ref()
4856                .is_none_or(|run| run.id != receipt.request.run)
4857    }) {
4858        task.hold_unrequested_retry(Some(
4859            "The retained repair run cannot be read or no longer owns this task's recovery. Inspect the saved grant and run; no replacement was started.".into(),
4860        ));
4861        record(queue, task);
4862        return Vec::new();
4863    }
4864    if let Some(id) = &task.disk_resume_run
4865        && unfinished.as_ref() != Some(id)
4866    {
4867        task.hold_manual(Some("Automatic disk recovery cannot resume the retained execution safely. Inspect its state and recovery approvals; no replacement competition was started.".into()));
4868        record(queue, task);
4869        return Vec::new();
4870    }
4871
4872    if !task.fresh_start
4873        && task.pr_recovery.is_none()
4874        && task.review_branch.is_none()
4875        && task.resume_override.is_none()
4876        && previous
4877            .as_ref()
4878            .is_some_and(|run| run.retired_to.is_some())
4879        && unfinished.is_none()
4880    {
4881        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()));
4882        record(queue, task);
4883        return Vec::new();
4884    }
4885
4886    let saved_recovery = previous.as_ref().filter(|run| {
4887        task.replacement.is_none()
4888            && task.pr_recovery.as_ref().is_some_and(|selected| {
4889                selected
4890                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4891                    .is_ok()
4892                    && selected_starter(selected, Some(run), unfinished.as_deref())
4893                        == Starter::Resume(run.id.clone())
4894            })
4895    });
4896
4897    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4898    // failure here is the network's or the operator's, not the task's: hold
4899    // without spending an attempt, never fall back to a possibly stale copy.
4900    let explicit = match &task.overrides {
4901        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4902        Some(_) => opts.config.as_deref(),
4903        None => opts.config.as_deref(),
4904    };
4905    let (mut config, layers) = if let Some(run) = saved_recovery {
4906        // A matching resume owns its resolved configuration and evidence;
4907        // current layers and inherited overrides only configure new work.
4908        let mut saved = run.clone();
4909        if let Err(e) = saved.configure_recovery_resume() {
4910            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4911            record(queue, task);
4912            return Vec::new();
4913        }
4914        (saved.config, Vec::new())
4915    } else {
4916        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4917            Ok(loaded) => loaded,
4918            Err(e) => {
4919                let reason = format!("[config] {e:#}");
4920                record_config_failure(task, &e);
4921                task.last_error = Some(reason.clone());
4922                task.hold_machine(Some(reason));
4923                record(queue, task);
4924                return Vec::new();
4925            }
4926        };
4927        if let Err(e) = apply_options(&mut config, opts, task) {
4928            task.hold_manual(Some(format!(
4929                "[config] {e:#}; correct the merge override before releasing the task"
4930            )));
4931            record(queue, task);
4932            return Vec::new();
4933        }
4934        if let Some(selected) = &task.pr_recovery
4935            && let Err(e) = selected.configure(&mut config)
4936        {
4937            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4938            record(queue, task);
4939            return Vec::new();
4940        }
4941        (config, layers)
4942    };
4943    let config_evidence = crate::pr_recovery::ConfigEvidence {
4944        layers,
4945        overrides: task.overrides.clone(),
4946        daemon_merge: task
4947            .overrides
4948            .as_ref()
4949            .is_none_or(|o| o.inherit_daemon_options)
4950            .then(|| opts.merge.clone())
4951            .flatten(),
4952    };
4953    apply_task_implementers(&mut config, task);
4954    if let Some(replacement) = &task.replacement {
4955        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4956            old.liveness(false) == Liveness::Dead
4957                && old.merge_decision.as_ref().is_some_and(|d| {
4958                    d.closed
4959                        && d.question == replacement.question
4960                        && d.replacement_run.as_ref().is_none_or(|run| {
4961                            task.execution_runs().last() == Some(run)
4962                                && RunState::load(run).is_ok_and(|current| {
4963                                    current.replaces.as_ref().is_some_and(|pin| {
4964                                        pin.question == replacement.question
4965                                            && pin.agent == replacement.agent
4966                                    })
4967                                })
4968                        })
4969                })
4970        });
4971        if !safe {
4972            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()));
4973            record(queue, task);
4974            return Vec::new();
4975        }
4976        match config.agent(&replacement.agent) {
4977            Ok(agent) if crate::agent::installed(agent) => {}
4978            _ => {
4979                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)));
4980                record(queue, task);
4981                return Vec::new();
4982            }
4983        }
4984        config.graph.implementers = 1;
4985        config.graph.land_approval = true;
4986        config.merge.mode = MergeMode::Pr;
4987        config.graph.selected_implementer = Some(replacement.agent.clone());
4988    }
4989    let p = phrases(&config.graph.language);
4990    let start_failed = p.could_not_start;
4991    // Resolve once for both admission and settlement. The inputs are the
4992    // task's explicit sources (never prose), plus an explicit review source's
4993    // current head; review-only runs may rebase later, and neither fact can
4994    // refund a failed automatic generation.
4995    if let Ok(base) =
4996        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4997            .await
4998        && let Ok(head) =
4999            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
5000    {
5001        let mut inputs = crate::queue::recovery_inputs(&task.sources);
5002        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
5003            let source = crate::git::rev_parse(&repo, branch)
5004                .await
5005                .unwrap_or_default();
5006            inputs.push_str(&format!(";review:{branch}:{source}"));
5007        }
5008        if let Some(reason) = task
5009            .recovery_exhausted(
5010                &head,
5011                &inputs,
5012                task.attempt_limit
5013                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
5014            )
5015            .filter(|_| {
5016                !task.repair_grants.last().is_some_and(|receipt| {
5017                    RunState::load(&receipt.request.run)
5018                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
5019                })
5020            })
5021        {
5022            task.hold_recovery_budget(
5023                reason,
5024                crate::queue::RecoveryAdmission { base: head, inputs },
5025            );
5026            record(queue, task);
5027            return Vec::new();
5028        }
5029        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
5030    }
5031
5032    // A resumable run of this task is carried on, never re-competed. The
5033    // candidates are built and paid for, and a fresh competition races a
5034    // second implementation against them.
5035    //
5036    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
5037    // started 3cbf on the same task a moment later, duplicating two and a
5038    // half hours of agent work. Then b25f stalled on a judge that timed out
5039    // and one that answered with no JSON - `quota: 0`, so nothing the machine
5040    // was to blame for - and 4043 started **one second** later, buying three
5041    // fresh implementations to reach the same panel. `RunStatus::resumable`
5042    // rather than `!done()` is what catches the second case: a stall is
5043    // terminal, and its cheap recovery re-asks only the absent seats.
5044    //
5045    // A load failure is warned about rather than silently read as "not
5046    // resumable": the alternative is exactly what let a schema mismatch on
5047    // run `eba2` fall through to a full re-competition with nobody told why.
5048    // `crate::conduct` is what actually offers a better answer than
5049    // `Runner::start` here (see `Recovery::Review`), once this task's next
5050    // failure shows it up as `held`/`failed` with the run state unreadable.
5051    // Keep a retained review selection intact until disk admission succeeds.
5052    let consume_review = !previous
5053        .as_ref()
5054        .is_some_and(|state| crate::repair_budget::pending(task, state));
5055    let review_branch = consume_review
5056        .then(|| review_branch_for(task, previous.as_ref()))
5057        .flatten();
5058    let branch_exists = match review_branch {
5059        Some(branch) => crate::git::branch_exists(&repo, branch)
5060            .await
5061            .unwrap_or(false),
5062        None => false,
5063    };
5064    // An explicit `magi review <branch>` is reviewed whatever happens to the
5065    // branch unless an explicit implementer change requires fresh work. An
5066    // unfinished run of the same task still wins, so a retry resumes.
5067    let proposed = review_retry_starter(
5068        task,
5069        previous.as_ref(),
5070        review_branch,
5071        branch_exists,
5072        unfinished.as_deref(),
5073    );
5074    let retry_selected = task.replacement.is_some()
5075        && task.resumption.is_some()
5076        && !task.fresh_start
5077        && previous.as_ref().is_some_and(|run| {
5078            run.replaces.is_some()
5079                && ((run.status == RunStatus::Failed && run.viable().is_empty())
5080                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
5081        });
5082    let stop_pin = task
5083        .resume_override
5084        .as_ref()
5085        .filter(|pin| {
5086            Questions::open()
5087                .get_for_effects(&pin.question_id)
5088                .is_ok_and(|q| {
5089                    q.node == land::APPROVAL_NODE
5090                        && q.resolution()
5091                            .as_deref()
5092                            .is_some_and(crate::merge_decision::stops)
5093                })
5094        })
5095        .and_then(|pin| pin.pinned_run.clone());
5096    let granted_run = task.repair_grants.last().and_then(|receipt| {
5097        let state = RunState::load(&receipt.request.run).ok()?;
5098        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
5099    });
5100    let starter = if let Some(run) = granted_run {
5101        Starter::Resume(run)
5102    } else if let Some(owner) = &public_owner {
5103        Starter::Resume(owner.id.clone())
5104    } else if let Some(run) = stop_pin {
5105        // Stop actions resume their exact owner even after seat-count edits;
5106        // they must never fall through to implementation or a takeover.
5107        Starter::Resume(run)
5108    } else if retry_selected {
5109        Starter::Resume(previous.as_ref().unwrap().id.clone())
5110    } else if let Some(selected) = &task.pr_recovery {
5111        if selected
5112            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5113            .is_ok()
5114        {
5115            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
5116        } else {
5117            Starter::Review(selected.branch.clone())
5118        }
5119    } else {
5120        starter_with_implementers(task, previous.as_ref(), proposed)
5121    };
5122    // A retained execution still writes to its saved output volume. A newer
5123    // repository policy only selects the volume for a fresh run.
5124    let disk_reason = match &starter {
5125        Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
5126            || {
5127                RunState::load(id)
5128                    .ok()
5129                    .and_then(|run| disk_gate(&run.repo, &run.config))
5130            },
5131            |run| disk_gate(&run.repo, &run.config),
5132        ),
5133        _ => disk_gate(&repo, &config),
5134    };
5135    if let Some(reason) = disk_reason {
5136        task.notice_cause("disk-space", None, None);
5137        task.last_error = Some(reason.clone());
5138        let disk_checked_at = task.disk_checked_at;
5139        task.hold_machine(Some(reason.clone()));
5140        if matches!(starter, Starter::Resume(_)) {
5141            task.mark_disk_capacity();
5142        } else {
5143            task.mark_startup_disk_capacity();
5144        }
5145        task.disk_checked_at = disk_checked_at;
5146        record(queue, task);
5147        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
5148        notices::raise(
5149            Notice::warn(
5150                &format!("disk:{}", repo.display()),
5151                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
5152            )
5153            .link(Link::Task {
5154                id: task.id.clone(),
5155            }),
5156        );
5157        return Vec::new();
5158    }
5159    let review_branch = if consume_review {
5160        let valid = review_branch.is_some();
5161        task.review_instruction = None;
5162        task.review_branch.take().filter(|_| valid)
5163    } else {
5164        None
5165    };
5166    // An explicit resume pin must never degrade into a new competition or
5167    // takeover, including when its run stops being eligible after the answer.
5168    if let Some(pin) = &task.resume_override
5169        && let Some(run) = &pin.pinned_run
5170        && starter != Starter::Resume(run.clone())
5171    {
5172        let run = run.clone();
5173        task.notice_cause("resume-owner", Some(&run), None);
5174        task.hold_machine(Some(format!(
5175            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
5176            task.id
5177        )));
5178        record(queue, task);
5179        return Vec::new();
5180    }
5181    // Automatic disk recovery resumes its retained run or stops: a changed
5182    // seat count or review branch must not turn it into a new competition.
5183    // No attempt is spent here.
5184    if let Some(run) = &task.disk_resume_run
5185        && starter != Starter::Resume(run.clone())
5186    {
5187        task.hold_manual(Some("Automatic disk recovery cannot resume the retained execution safely: the task's current settings would start a different run. Inspect its state and recovery approvals; no replacement competition was started.".into()));
5188        record(queue, task);
5189        return Vec::new();
5190    }
5191    if task.replacement.is_some()
5192        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
5193        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
5194    {
5195        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()));
5196        record(queue, task);
5197        return Vec::new();
5198    }
5199    if let Some((ref run, ..)) = head_e2e_approval
5200        && starter != Starter::Resume(run.clone())
5201    {
5202        task.hold_machine(Some(format!(
5203            "Conclusive head_e2e stop on run {run} cannot resume safely with current task settings; inspect `magi show {run}` before retrying. No replacement competition was started."
5204        )));
5205        record(queue, task);
5206        return Vec::new();
5207    }
5208    if let Some(reason) = retained_attempt_hold(
5209        task,
5210        &starter,
5211        config.disk.retained_attempt_limit,
5212        RunState::load,
5213    ) {
5214        // The review choice was consumed above. Preserve it across this hold
5215        // so a later release cannot silently become a fresh implementation.
5216        if let Starter::Review(branch) = &starter {
5217            task.review_branch = Some(branch.clone());
5218        }
5219        task.hold_unrequested_retry(Some(reason));
5220        record(queue, task);
5221        return Vec::new();
5222    }
5223    // Absolute paths of the files the task was filed with, re-read from the
5224    // task now so a file attached while it was held reaches a resumed run
5225    // too. A stored name whose file has gone is an error before any agent is
5226    // paid for, never a silent omission the implementer cannot notice.
5227    let attachments = match task_attachments(queue, task) {
5228        Ok(a) => a,
5229        Err(e) => {
5230            task.attempts += 1;
5231            task.fail_startup_target(
5232                "startup-attachments",
5233                e.name.clone(),
5234                format!("{start_failed}{e:#}"),
5235                opts.max_attempts,
5236            );
5237            record(queue, task);
5238            return Vec::new();
5239        }
5240    };
5241    let startup_pause = stop.pause();
5242    let startup_interrupt = interrupt_pause.clone();
5243    let wait = crate::repo_lock::WaitPolicy::new(
5244        Duration::from_secs(config.graph.timeout_resource_wait),
5245        move || startup_pause.parked() || startup_interrupt.parked(),
5246    );
5247    // Startup includes review takeover and recovery. Do not embed its large
5248    // future in both the wait scope and the surrounding attempt stack frame.
5249    let started = wait.scope(Box::pin(async { match &starter {
5250        Starter::Review(_) if task.pr_recovery.is_some() => {
5251            let selected = task.pr_recovery.clone().expect("selected recovery");
5252            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
5253                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
5254                    .await
5255                    .map(|mut r| {
5256                        r.state.attachments = attachments.clone();
5257                        r
5258                    }),
5259                Err(e) => Err(e),
5260            }
5261        }
5262        Starter::Review(branch) => {
5263            tracing::info!(
5264                "task {} reopens `{branch}` as a review-only pass",
5265                task.short()
5266            );
5267            // Every earlier attempt is superseded by the one being minted
5268            // now, so a branch one of them still holds may be taken over.
5269            let takeover = crate::handover::Takeover {
5270                earlier: task.earlier_attempts().to_vec(),
5271                home: crate::run::home(),
5272                choice: take_divergence_answer(branch, &config.merge.remote, task),
5273                task_instruction: Some(instruction_for(task)),
5274            };
5275            Runner::review_taking_over(
5276                &repo,
5277                branch,
5278                config,
5279                Some(takeover),
5280                crate::run::Origin::queue(&task.id),
5281            )
5282            .await
5283        }
5284        Starter::Resume(id) => {
5285            tracing::info!("resuming run {id} rather than competing again");
5286            Runner::resume(id).and_then(|mut r| {
5287                if retry_selected {
5288                    // The explicit queue release retries this same pinned
5289                    // implementation, preserving the attempt and worktrees.
5290                    for candidate in &mut r.state.candidates {
5291                        candidate.failed = None;
5292                        candidate.empty = false;
5293                        candidate.commits = 0;
5294                    }
5295                    r.state.status = RunStatus::Implementing;
5296                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
5297                }
5298                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
5299                    r.state.sources = task.sources.clone();
5300                }
5301                if r.state.prep_failure.is_some() {
5302                    let approval = task
5303                        .resumption
5304                        .as_ref()
5305                        .context("preparation retry requires an explicit task release")?;
5306                    r.retry_preparation(approval.at)?;
5307                }
5308                if let Some(instruction) =
5309                    prepare_instruction(&starter, Some(&r.state.instruction), task)
5310                {
5311                    r.state.instruction = instruction;
5312                }
5313                r.state.attachments = attachments.clone();
5314                if task.replacement.is_some() {
5315                    r.state.config.merge.mode = MergeMode::Pr;
5316                    r.state.config.graph.land_approval = true;
5317                }
5318                // Replacements publish a new PR and ask again. Selected PR
5319                // recoveries keep their saved disposition; ordinary runs can
5320                // retain the task's merge override.
5321                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
5322                    .overrides
5323                    .as_ref()
5324                    .and_then(|o| o.merge.as_deref())
5325                    .and_then(|m| merge_mode(m).ok())
5326                {
5327                    r.state.config.merge.mode = mode;
5328                }
5329                Ok(r)
5330            })
5331        }
5332        Starter::Start => {
5333            if let Some(branch) = &review_branch {
5334                tracing::warn!(
5335                    "conductor chose review for task {} but branch `{branch}` no longer \
5336                     exists; requeuing as a fresh competition instead",
5337                    task.short()
5338                );
5339            }
5340            let instruction = prepare_instruction(&starter, None, task)
5341                .unwrap_or_else(|| task.instruction.clone());
5342            Runner::start_naming(
5343                &repo,
5344                instruction,
5345                &task.title,
5346                config,
5347                crate::run::Origin::queue(&task.id),
5348            )
5349            .await
5350            .map(|mut r| {
5351                r.state.attachments = attachments.clone();
5352                r.state.sources = task.sources.clone();
5353                r
5354            })
5355        }
5356    }})).await;
5357    if let Err(error) = &started
5358        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
5359    {
5360        task.record_startup_failure(failure.clone());
5361    }
5362    let mut runner = match started {
5363        Ok(r) => r,
5364        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
5365            let detail = format!("{e:#}");
5366            task.last_error = Some(detail.clone());
5367            if e.is::<crate::build_target::AdmissionDiskWait>()
5368                && let Starter::Review(branch) = &starter
5369                && review_branch.is_some()
5370            {
5371                task.review_branch = Some(branch.clone());
5372                task.review_instruction = Some(task.instruction.clone());
5373            }
5374            if stop.parking() || interrupt_pause.parked() {
5375                let attempts = task.attempts;
5376                task.park(e.to_string());
5377                // Startup has not spent an attempt to refund.
5378                task.attempts = attempts;
5379            } else if e.is::<crate::build_target::AdmissionDiskWait>() {
5380                let disk_checked_at = task.disk_checked_at;
5381                task.hold_machine(Some(detail));
5382                task.mark_startup_disk_capacity();
5383                task.disk_checked_at = disk_checked_at;
5384            } else {
5385                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
5386            }
5387            record(queue, task);
5388            return Vec::new();
5389        }
5390        // A branch an earlier attempt still holds and magi will not release
5391        // by itself is the operator's call, not a failed attempt: hold the
5392        // task with the reason, spend nothing, and say so on the bell.
5393        Err(e) if task.pr_recovery.is_some() => {
5394            task.startup_notice_cause("startup-public-head");
5395            task.attempts += 1;
5396            task.last_error = Some(format!("{start_failed}{e:#}"));
5397            task.hold_unrequested_retry(Some(format!(
5398                "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."
5399            )));
5400            record(queue, task);
5401            return Vec::new();
5402        }
5403        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
5404            let detail = match e.downcast_ref::<crate::handover::Refused>() {
5405                Some(r) => (p.handover_refused)(r),
5406                None => format!("{e:#}"),
5407            };
5408            task.startup_notice_cause("startup-handover");
5409            let reason = format!("{start_failed}{detail}");
5410            task.last_error = Some(reason.clone());
5411            // Consumed above by `take`; keep it so the released task retries
5412            // as a review of this same branch.
5413            let branch = match &starter {
5414                Starter::Review(branch) => Some(branch.clone()),
5415                _ => None,
5416            };
5417            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
5418            // one page; the guidance rides in the reason, fixed per state so a
5419            // re-put never changes the wording and relights it.
5420            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5421            record(queue, task);
5422            tracing::warn!(
5423                "holding {} for a branch it cannot take over: {e:#}",
5424                task.short()
5425            );
5426            return Vec::new();
5427        }
5428        // A branch that differs between here and the remote in ways magi
5429        // cannot prove are the same change is a decision for the owner, not a
5430        // failed attempt: ask with both sides laid out, spend no attempt, and
5431        // let the answer requeue the task.
5432        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5433            let d = e
5434                .downcast_ref::<crate::reconcile::Diverged>()
5435                .expect("checked by the guard");
5436            let mut q = ask::Question::new(
5437                task.id.clone(),
5438                crate::reconcile::NODE.to_owned(),
5439                crate::reconcile::SEAT.to_owned(),
5440                d.summary(),
5441                d.detail(),
5442                d.choices(),
5443            );
5444            match Questions::open().put(&mut q) {
5445                Ok(()) => {
5446                    task.last_error = Some(format!("{e:#}"));
5447                    // Consumed above by `take`; the answer has to reach a review
5448                    // of this same branch, so keep pointing the task at it.
5449                    task.review_branch = Some(d.branch.clone());
5450                    task.review_instruction = Some(task.instruction.clone());
5451                    task.block(vec![q.id.clone()], Some(d.summary()));
5452                }
5453                Err(put) => {
5454                    tracing::warn!("could not file the divergence question: {put:#}");
5455                    task.attempts += 1;
5456                    task.fail_startup(
5457                        "startup-question-store",
5458                        format!("{start_failed}{e:#}"),
5459                        opts.max_attempts,
5460                    );
5461                }
5462            }
5463            record(queue, task);
5464            return Vec::new();
5465        }
5466        Err(e) => {
5467            // The answer was stale and nothing was applied: keep pointing at
5468            // the branch so the next attempt asks again against its new tips.
5469            // Nothing went wrong with the task, so no attempt is spent: a
5470            // budget one short of its limit must not hold it instead of
5471            // letting the question be asked again.
5472            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5473                && let Starter::Review(branch) = &starter
5474            {
5475                task.review_branch = Some(branch.clone());
5476                task.review_instruction = Some(task.instruction.clone());
5477                task.last_error = Some(format!("{start_failed}{e:#}"));
5478                task.status = crate::queue::TaskStatus::Failed;
5479                record(queue, task);
5480                return Vec::new();
5481            }
5482            task.attempts += 1;
5483            task.last_error = Some(format!("{start_failed}{e:#}"));
5484            task.startup_notice_cause("startup-source");
5485            task.hold_unrequested_retry(Some(format!(
5486                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5487            )));
5488            record(queue, task);
5489            return Vec::new();
5490        }
5491    };
5492    if !matches!(starter, Starter::Resume(_))
5493        && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
5494    {
5495        runner
5496            .state
5497            .event("build-cache", format!("{mode} selected by {source}"));
5498    }
5499    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5500        runner.state.recovery_config = Some(config_evidence);
5501    }
5502    if let Some(replacement) = &task.replacement {
5503        if matches!(starter, Starter::Start) {
5504            runner.state.instruction.push_str(&format!(
5505                "\n\n# Replacement review context\n{}",
5506                replacement.context
5507            ));
5508        }
5509        runner.state.replaces = Some(replacement.clone());
5510        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5511        if let Ok(mut old) = RunState::load(&replacement.run)
5512            && let Some(d) = &mut old.merge_decision
5513        {
5514            d.replacement_run = Some(runner.state.id.clone());
5515            old.event(
5516                "replacement",
5517                format!(
5518                    "replacement run {} owns the next attempt; old PR remains closed",
5519                    runner.state.id
5520                ),
5521            );
5522            if let Err(e) = old.save() {
5523                let error = runner.fail_startup("replacement-history", e);
5524                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5525                    task.record_startup_failure(failure.clone());
5526                }
5527                task.hold_manual(Some(format!(
5528                    "Could not link replacement history: {error:#}; no agents dispatched"
5529                )));
5530                record(queue, task);
5531                return Vec::new();
5532            }
5533        }
5534    }
5535    runner.state.task_instruction = Some(task.instruction.clone());
5536    // The follow-up depth is fixed now, while the task certainly exists:
5537    // deleting it later must not reset the cap (`crate::followup`).
5538    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5539    if runner.state.origin_chat.is_none() {
5540        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5541    }
5542    // A stop that means "park" reaches the graph through this handle.
5543    runner.on_pause(stop.pause());
5544    // `poll`'s interrupt scheduler reaches this one run - and no other -
5545    // through this handle. See `Pause`'s own doc for why these are never
5546    // the same one.
5547    runner.watch_interrupt(interrupt_pause);
5548
5549    // `start` has minted the run, so the task can now point at it. Persisting
5550    // `Running` before `execute` is what makes a crash mid-run legible.
5551    let run = runner.state.id.clone();
5552    let before_start = task.clone();
5553    task.start(run.clone());
5554    if let Err(error) = queue.put(task) {
5555        *task = before_start;
5556        let error = runner.fail_startup("task-start", error);
5557        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5558            task.record_startup_failure(failure.clone());
5559        }
5560        task.hold_manual(Some(format!(
5561            "Could not persist task start; no agents dispatched: {error:#}"
5562        )));
5563        record(queue, task);
5564        return Vec::new();
5565    }
5566    if task.status != TaskStatus::Running {
5567        // Queue::put kept a newer hold or continuation instead of this start.
5568        return Vec::new();
5569    }
5570    lock(status).current.push(Current {
5571        worker: None,
5572        task: task.id.clone(),
5573        run,
5574    });
5575
5576    // `RunState::quota` is the run's whole history across every resume, so
5577    // only what this execution added may arm the cooldown or earn a refund.
5578    let quota_before = runner.state.quota.clone();
5579    runner.state.carry_dispatched_resumes(task);
5580    runner.state.entry_resumption_generation =
5581        Some(task.resumption.as_ref().map_or(0, |r| r.generation));
5582    if let Some((run, stop_id, generation, approval_at)) = head_e2e_approval
5583        && runner.state.id == run
5584    {
5585        crate::head_e2e_stop::record_consumed_approval(
5586            &mut runner.state,
5587            &task.id,
5588            &stop_id,
5589            generation,
5590            approval_at,
5591        );
5592    }
5593    runner.state.next_pass_task_entry = true;
5594    let result = runner.execute().await;
5595    finish_attempt(
5596        opts.max_attempts,
5597        queue,
5598        task,
5599        &runner.state,
5600        &quota_before,
5601        result,
5602    )
5603}
5604
5605async fn attempt_sync_only(
5606    queue: &Queue,
5607    status: &Arc<Mutex<Status>>,
5608    stop: &Stop,
5609    interrupt: crate::graph::Pause,
5610    task: &mut Task,
5611    request: crate::base_sync_only::Request,
5612) {
5613    let result = async {
5614        anyhow::ensure!(
5615            task.status == TaskStatus::Queued
5616                && task.execution_runs().last() == Some(&request.run)
5617                && task.resume_override.as_ref().is_some_and(
5618                    |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
5619                ),
5620            "sync-base-only request no longer owns the exact queued run"
5621        );
5622        let mut runner = Runner::resume(&request.run)?;
5623        anyhow::ensure!(
5624            public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
5625                .await?
5626                .is_none(),
5627            "the task still has a public execution owner"
5628        );
5629        anyhow::ensure!(
5630            !stop.parking() && !interrupt.parked(),
5631            "paused before base synchronization"
5632        );
5633        let original = task.clone();
5634        task.start(request.run.clone());
5635        task.attempts = original.attempts;
5636        if let Err(error) = queue.put(task) {
5637            *task = original;
5638            return Err(error);
5639        }
5640        if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
5641            return Ok(());
5642        }
5643        lock(status).current.push(Current {
5644            worker: None,
5645            task: task.id.clone(),
5646            run: request.run.clone(),
5647        });
5648        runner.on_pause(stop.pause());
5649        runner.watch_interrupt(interrupt);
5650        runner.execute_sync_only(request.clone()).await
5651    }
5652    .await;
5653    if task.sync_only.as_ref() == Some(&request) {
5654        let saved = RunState::load(&request.run).ok();
5655        let detail = result.err().map(|error| {
5656            format!("Base synchronization only: {error:#}; verification was not allowed")
5657        });
5658        crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
5659        record(queue, task);
5660    }
5661}
5662
5663/// Settle `task` after its run executed: the verdict, the diagnosis, the
5664/// supersession of earlier attempts and the save. Shared by the loop and by
5665/// `magi run --resume`, so an attempt is counted one way wherever it ran.
5666/// Returns the quota losses this execution added to the run.
5667pub fn finish_attempt(
5668    max_attempts: usize,
5669    queue: &Queue,
5670    task: &mut Task,
5671    state: &RunState,
5672    quota_before: &[QuotaLoss],
5673    result: Result<()>,
5674) -> Vec<QuotaLoss> {
5675    let detail = match result {
5676        Ok(()) => describe(state),
5677        Err(e) => format!("{e:#}"),
5678    };
5679    let fresh = losses_this_attempt(quota_before, &state.quota);
5680    let verdict = Verdict {
5681        status: state.status,
5682        // A run that opened a pull request handed its work over, whatever the
5683        // gate then decided about merging it.
5684        left_pr: state.pr.is_some(),
5685        // Only a rate limit earns the task its attempt back - and only one
5686        // suffered now: a refund justified by a previous session's loss is
5687        // the same mistake as re-arming the cooldown from it. A stalled run
5688        // resumed without hitting quota again therefore spends its attempt,
5689        // like any other failure of the task's own.
5690        quota_hit: !fresh.is_empty(),
5691        // A run that parked was asked to stop; that is not a failure and must
5692        // not spend an attempt, or replacing the binary a few times would
5693        // exhaust a task's budget without an agent ever misbehaving.
5694        parked: state.parked,
5695        // A quota loss that left nothing viable is the same machine fact as a
5696        // `Stalled` quota loss; see `settle`'s doc table.
5697        no_viable_candidates: state.viable().is_empty(),
5698    };
5699    if let Some(replacement) = &state.replaces
5700        && let Some(pr) = &state.pr
5701        && let Ok(mut old) = RunState::load(&replacement.run)
5702        && let Some(d) = &mut old.merge_decision
5703    {
5704        d.replacement_pr = Some(pr.url.clone());
5705        let _ = old.save();
5706    }
5707    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5708    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5709        task.hold_unrequested_retry(Some(format!(
5710            "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.",
5711            task.short()
5712        )));
5713    }
5714    if task.status == TaskStatus::Done {
5715        supersede_prior_runs(task, &crate::run::home());
5716    }
5717    record(queue, task);
5718    tracing::info!(
5719        "task {} is {} after run {} ({})",
5720        task.short(),
5721        task.status.as_str(),
5722        state.short(),
5723        label(state.status)
5724    );
5725    fresh
5726}
5727
5728/// A task a hand-started run leaves runnable (failed with attempts to spare,
5729/// or requeued) is **held**: nobody asked for a retry, and a loop starting
5730/// later must not spend agent calls on it. `magi task release` retries.
5731pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5732    // Parked work (including legacy Failed records with a parked run) is a
5733    // checkpoint or owner handoff, not an unrequested retry.
5734    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5735        && !awaiting_resume_with(task, RunState::load)
5736        // A run parked on the owner's word about a withheld PR title/body
5737        // resumes via `land_resume_state`, including review-only tasks that
5738        // `awaiting_resume_with` does not consider.
5739        && withheld_text_wait(task).is_none()
5740        && !(task.fresh_start && task.replacement.is_some())
5741    {
5742        let why = task.last_error.clone().map_or_else(
5743            || "the run did not finish".to_owned(),
5744            |e| format!("the run did not finish: {e}"),
5745        );
5746        task.hold_unrequested_retry(Some(format!(
5747            "{why}. It was started by hand, so it is not retried \
5748             automatically; `magi task release` retries it."
5749        )));
5750        record(queue, task);
5751    }
5752}
5753
5754/// Whether an attempt at a task whose newest run is `run` would resume that
5755/// run rather than start a fresh competition. `magi run --resume` hands a run
5756/// to a live loop only when this holds.
5757#[must_use]
5758pub fn loop_would_resume(run: &str) -> bool {
5759    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5760}
5761
5762/// A loop in another process that is alive right now: a fresh heartbeat in
5763/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
5764/// carries the pid it published (`None` inside when it published none - a
5765/// fresh heartbeat is still evidence of a live loop).
5766///
5767/// The one judgement of "is somebody else serving this queue", shared by the
5768/// web UI's refusal to start a second loop and by `magi run` / `magi review`
5769/// deciding whether to hand a task to the loop. A claim file proves nothing
5770/// here: whether a claim succeeds says nothing about whether its owner lives.
5771#[must_use]
5772pub fn foreign_loop(
5773    reading: Option<&Reading>,
5774    now: Timestamp,
5775    own_pid: u32,
5776) -> Option<Option<u32>> {
5777    let reading = reading.filter(|r| r.running(now))?;
5778    match reading.pid {
5779        Some(pid) if pid == own_pid => None,
5780        pid => Some(pid),
5781    }
5782}
5783
5784fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5785    reading.worker_protocol != Some(1)
5786        && (foreign_loop(Some(reading), now, own_pid).is_some()
5787            || reading
5788                .pid
5789                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5790}
5791
5792/// Low-level claimed-task execution shared by the detached standalone worker
5793/// and focused lifecycle fixtures. The caller must retain the queue claim for
5794/// this entire call. CLI callers transfer ownership through
5795/// [`run_detached_claimed`] instead of executing inside their own runtime.
5796///
5797/// The one deliberate difference from the loop: a task the attempt leaves
5798/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5799/// Nobody asked for a retry, and a daemon starting later must not spend agent
5800/// calls re-running a hand-started task behind the operator's back;
5801/// `magi task release` is the explicit retry.
5802pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5803    run_claimed_until(opts, queue, task, &Stop::new()).await;
5804}
5805
5806async fn run_claimed_until(
5807    opts: &Opts,
5808    queue: &Queue,
5809    task: &mut Task,
5810    stop: &Stop,
5811) -> Vec<QuotaLoss> {
5812    let status = Arc::new(Mutex::new(Status::new()));
5813    // An attempt embeds startup and graph futures. Keep it off the standalone
5814    // caller's stack, on both the initial execution and withheld-text resume.
5815    let mut quota = Box::pin(attempt(
5816        opts,
5817        queue,
5818        &status,
5819        stop,
5820        crate::graph::Pause::new(),
5821        task,
5822    ))
5823    .await;
5824    // A run parked on the owner's word about a withheld PR title/body has no
5825    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5826    // here with the claim still held, and resume once the question is settled
5827    // (answered, or abandoned at its deadline -> the neutral text).
5828    // A rejected reply files one more question (the gate asks at most twice),
5829    // so after a resume the run may be waiting again: keep going, with a fresh
5830    // limit for the new question. `resumes` bounds it even if a resume parks
5831    // without asking anything new.
5832    let mut resumes = 0;
5833    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5834        let Some(timeout) = withheld_text_wait(task) else {
5835            break;
5836        };
5837        eprintln!(
5838            "waiting for the owner's answer on a withheld pull request text \
5839             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5840        );
5841        // The deadline abandons the question itself; the extra margin only
5842        // covers an abandon that could not be saved.
5843        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5844        let ready = loop {
5845            match land_resume_state(task) {
5846                LandResume::StillWaiting
5847                    if !stop.parking() && std::time::Instant::now() < limit =>
5848                {
5849                    tokio::time::sleep(WITHHELD_POLL).await;
5850                }
5851                LandResume::Ready => break true,
5852                _ => break false,
5853            }
5854        };
5855        if !ready || stop.parking() {
5856            break;
5857        }
5858        resumes += 1;
5859        quota.extend(
5860            Box::pin(attempt(
5861                opts,
5862                queue,
5863                &status,
5864                stop,
5865                crate::graph::Pause::new(),
5866                task,
5867            ))
5868            .await,
5869        );
5870    }
5871    hold_if_runnable(queue, task);
5872    quota
5873}
5874
5875/// Resumes an in-process run makes for withheld-text questions: the gate asks
5876/// at most twice, plus one for a resume that asks nothing new.
5877const MAX_WITHHELD_RESUMES: u32 = 3;
5878
5879/// How often an in-process run rechecks its withheld-text question.
5880const WITHHELD_POLL: Duration = Duration::from_secs(15);
5881
5882/// The `answer_timeout` (seconds) of the task's last run when that run is
5883/// parked on an unresolved withheld-text question; `None` otherwise.
5884fn withheld_text_wait(task: &Task) -> Option<u64> {
5885    let id = task.execution_runs().last()?;
5886    let s = RunState::load(id).ok()?;
5887    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5888        .then_some(s.config.graph.answer_timeout)
5889}
5890
5891/// The quota losses `after` holds that `before` did not: what one execution
5892/// suffered, as opposed to the run's history.
5893///
5894/// Compared by value rather than by length or position because
5895/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5896/// the vector can shrink and shift under a resume. A retried seat that hits
5897/// quota again is a `push` with a new `at`, so it shows up as new here.
5898/// Crash recovery uses the recorded pass start as its boundary when available;
5899/// legacy records without passes retain their original history-based policy.
5900fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5901    after
5902        .iter()
5903        .filter(|q| !before.contains(q))
5904        .cloned()
5905        .collect()
5906}
5907
5908/// When the loop-wide quota cooldown should end, given this attempt's losses;
5909/// `None` when there were none. Reset-hint parsing and the cap live here.
5910fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5911    let quota: Vec<_> = quota
5912        .iter()
5913        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5914        .collect();
5915    if quota.is_empty() {
5916        return None;
5917    }
5918    let with_hint = quota.iter().find(|q| q.reset.is_some());
5919    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5920    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5921    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5922    Some(
5923        now.checked_add(jiff::SignedDuration::from_secs(secs))
5924            .unwrap_or(Timestamp::MAX),
5925    )
5926}
5927
5928/// An explicit task count must agree with a run before any resume.
5929fn implementers_match(task: &Task, state: &RunState) -> bool {
5930    task.replacement.as_ref().map_or_else(
5931        || {
5932            task.implementers()
5933                .is_none_or(|n| n == state.config.graph.implementers)
5934        },
5935        |replacement| {
5936            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5937                && state.config.graph.implementers == 1
5938        },
5939    )
5940}
5941
5942/// Never resume or take over candidate work built for a different seat count.
5943fn starter_with_implementers(
5944    task: &Task,
5945    previous: Option<&RunState>,
5946    proposed: Starter,
5947) -> Starter {
5948    if previous.is_some_and(|s| !implementers_match(task, s)) {
5949        task.review_of
5950            .as_ref()
5951            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5952    } else {
5953        proposed
5954    }
5955}
5956
5957/// Apply this task's explicit count to the new attempt, without changing defaults.
5958fn apply_task_implementers(config: &mut Config, task: &Task) {
5959    if let Some(n) = task.implementers() {
5960        config.graph.implementers = n;
5961    }
5962}
5963
5964/// [`prepare`] for one task: its own `--config` and command-line overrides
5965/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5966/// over the loop's, so handing a hand-started task to a daemon changes nothing
5967/// about what it does.
5968#[cfg(test)]
5969fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5970    let explicit = match &task.overrides {
5971        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5972        _ => opts.config.as_deref(),
5973    };
5974    let (mut config, _) = Config::discover(repo, explicit)?;
5975    apply_options(&mut config, opts, task)?;
5976    Ok(config)
5977}
5978
5979fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5980    if task
5981        .overrides
5982        .as_ref()
5983        .is_none_or(|o| o.inherit_daemon_options)
5984        && let Some(mode) = opts.merge.as_deref()
5985    {
5986        config.merge.mode = merge_mode(mode)?;
5987    }
5988    if let Some(o) = &task.overrides {
5989        o.apply(config);
5990    }
5991    if let Some((mode, _)) = task.build_cache_override(config) {
5992        config.verify.build_cache = mode;
5993    }
5994    Ok(())
5995}
5996
5997/// Load the config for a task's repository, with the merge override applied.
5998fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5999    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
6000    if let Some(mode) = &opts.merge {
6001        config.merge.mode = merge_mode(mode)?;
6002    }
6003    Ok(config)
6004}
6005
6006/// Prune the shared build cache at a between-runs boundary. The detached cache
6007/// service checks authoritative task jobs first; dispatch waits for that finite
6008/// service, so scheduler replacement cannot turn a compile into idle cleanup.
6009/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
6010async fn maybe_prune_cache_between_runs(
6011    repo: &Path,
6012    opts: &Opts,
6013    home: &Path,
6014    stop: &Stop,
6015    last_checked: &mut Option<Timestamp>,
6016    now: Timestamp,
6017) {
6018    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
6019        return;
6020    }
6021    *last_checked = Some(now);
6022    let cfg = match prepare(repo, opts) {
6023        Ok(cfg) => cfg,
6024        Err(e) => {
6025            tracing::warn!("cache check: no config: {e:#}");
6026            return;
6027        }
6028    };
6029    match clean::prune_cache_if_over_limit(&cfg, home) {
6030        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
6031            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
6032            pruned.files,
6033            pruned.freed
6034        ),
6035        Ok(_) => {}
6036        Err(e) => {
6037            tracing::warn!("housekeep: prune cache: {e:#}");
6038            notices::raise_in(
6039                home,
6040                Notice::warn(
6041                    "housekeep:cache",
6042                    format!(
6043                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
6044                        e.to_string()
6045                            .lines()
6046                            .next()
6047                            .unwrap_or("unknown cleanup error")
6048                    ),
6049                ),
6050            );
6051        }
6052    }
6053}
6054
6055/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
6056/// now, given when it last did (if ever). Pure, so the cadence is asserted
6057/// directly rather than by waiting out real minutes in a test.
6058fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
6059    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
6060}
6061
6062/// The disk janitor, with its housekeeping logged rather than fatal.
6063///
6064/// Called only at the loop's idle points, for the reason the caller documents:
6065/// a prune racing a live compile would delete files mid-build. The config is
6066/// re-read on every call because the repository that just ran may not be the
6067/// daemon's own default, and the cache directory is a repository fact.
6068///
6069/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
6070/// and [`crate::run::default_worktree_root`] read here, for the same reason
6071/// [`drive`] takes its queue and status file rather than resolving them: a
6072/// test driving the loop must not reach through to the operator's real home
6073/// or worktree bay just because the janitor runs on every idle tick.
6074/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
6075/// to get wrong silently - a test's `home` was already isolated, but nothing
6076/// exercised the parameter next to it, so a real worktree bay stayed wired in
6077/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
6078/// it for real, every test in this file that drives the loop at all started
6079/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
6080async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
6081    let cfg = match prepare(repo, opts) {
6082        Ok(cfg) => cfg,
6083        Err(e) => {
6084            tracing::warn!("housekeep: no config: {e:#}");
6085            return;
6086        }
6087    };
6088    // A run's own worktree lives under `config.graph.worktree_root` when the
6089    // repository sets one - the same precedence `RunState::worktree_root`
6090    // uses - and `worktrees_root` only stands in for the *default* an
6091    // unconfigured repository resolves to (see this function's own
6092    // parameter, or the test fixture wiring one to a fake path). Housekeeping
6093    // that always swept the default regardless of this override would never
6094    // see, and so never reclaim, a single worktree for a repository that
6095    // relocated them elsewhere.
6096    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
6097    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
6098    // Reported whenever there is anything to say, not only when `folded > 0`:
6099    // the incident this exists to prevent was 90 of 93 runs skipped and 0
6100    // folded, on every single pass, for months - a report gated on `folded`
6101    // would have stayed silent through every one of them.
6102    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
6103        let mut extra = Vec::new();
6104        if out.unreadable > 0 {
6105            extra.push(format!("{} unreadable", out.unreadable));
6106        }
6107        if out.orphaned_worktrees > 0 {
6108            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
6109        }
6110        let detail = if extra.is_empty() {
6111            String::new()
6112        } else {
6113            format!(" ({})", extra.join(", "))
6114        };
6115        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
6116    }
6117    if out.external_merges_recorded > 0 {
6118        tracing::info!(
6119            "housekeep: recorded {} run(s) as merged externally",
6120            out.external_merges_recorded
6121        );
6122    }
6123    if out.stale_pr_states_repaired > 0 {
6124        tracing::info!(
6125            "housekeep: rewrote {} run record(s) whose pull request had already settled",
6126            out.stale_pr_states_repaired
6127        );
6128    }
6129    if out.cache_files > 0 {
6130        tracing::info!(
6131            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
6132            out.cache_files,
6133            out.cache_freed
6134        );
6135    }
6136    if out.questions_abandoned > 0 {
6137        tracing::info!(
6138            "housekeep: abandoned {} question(s) left open by a finished run",
6139            out.questions_abandoned
6140        );
6141    }
6142}
6143
6144/// Run [`triage::run_once`] and log whatever it did, the same "only when
6145/// there is something to say" rule [`janitor`] follows for its own report.
6146///
6147/// Called at the same idle points as [`janitor`] - once per full poll
6148/// interval, never mid-attempt - for the same reason: it is not liveness
6149/// critical, and a task's own `hold_reason` string is the one thing this
6150/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
6151/// tick for no benefit.
6152async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
6153    let questions = Questions::at(home.join("questions"));
6154    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
6155    if report.is_empty() {
6156        return;
6157    }
6158    if !report.quarantined.is_empty() {
6159        tracing::info!(
6160            "triage: held {} blocked task(s) whose blocked-on task or \
6161             question no longer exists: {}",
6162            report.quarantined.len(),
6163            report.quarantined.join(", ")
6164        );
6165    }
6166    if !report.resumed.is_empty() {
6167        tracing::info!(
6168            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
6169            report.resumed.len(),
6170            report.resumed.join(", ")
6171        );
6172    }
6173    if !report.asked.is_empty() {
6174        tracing::info!(
6175            "triage: asked about {} held task(s): {}",
6176            report.asked.len(),
6177            report.asked.join(", ")
6178        );
6179    }
6180    if !report.answered.is_empty() {
6181        tracing::info!(
6182            "triage: applied {} operator answer(s): {}",
6183            report.answered.len(),
6184            report.answered.join(", ")
6185        );
6186    }
6187}
6188
6189/// The free-space gate: what stands between this task and a new run, if
6190/// anything. `Some(reason)` holds the task; `None` lets it start.
6191///
6192/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
6193/// the operator opted out. A measurement failure is a gate, not a pass: both
6194/// sides of "cannot tell" are served by not starting.
6195pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
6196    disk_gate_at(repo, config, crate::run::home)
6197}
6198
6199pub(crate) fn disk_gate_at(
6200    repo: &Path,
6201    config: &Config,
6202    home: impl FnOnce() -> PathBuf,
6203) -> Option<String> {
6204    let measure = if crate::build_target::isolated(config) {
6205        crate::disk::managed_free_bytes
6206    } else {
6207        crate::disk::free_bytes
6208    };
6209    disk_gate_with(repo, config, home, measure)
6210}
6211
6212/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
6213/// test can assert the exact wiring `attempt` runs - config's threshold in,
6214/// task-holding reason out - without asking the real machine's disk anything.
6215fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
6216    repo: &Path,
6217    config: &Config,
6218    home: impl FnOnce() -> PathBuf,
6219    free_bytes: F,
6220) -> Option<String> {
6221    let min = config.disk.min_free_bytes;
6222    if min == 0 {
6223        return None;
6224    }
6225    let output = match config.verify.build_cache {
6226        BuildCache::Shared => config.cache_dir(),
6227        BuildCache::Isolated => Some(home()),
6228    };
6229    let default_worktree_root;
6230    let worktree_root = match config.graph.worktree_root.as_deref() {
6231        Some(root) => root,
6232        None => {
6233            default_worktree_root = crate::run::default_worktree_root();
6234            &default_worktree_root
6235        }
6236    };
6237    for path in [Some(repo), output.as_deref(), Some(worktree_root)]
6238        .into_iter()
6239        .flatten()
6240    {
6241        let probe = if path == repo {
6242            path
6243        } else {
6244            path.ancestors().find(|p| p.exists()).unwrap_or(path)
6245        };
6246        let reason = match free_bytes(probe) {
6247            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
6248            Err(e) => Some(crate::disk::unmeasured_in(
6249                probe,
6250                &e,
6251                &config.graph.language,
6252            )),
6253        };
6254        if reason.is_some() {
6255            return reason;
6256        }
6257    }
6258    None
6259}
6260
6261/// How long to wait before offering another task when a run lost a seat to a
6262/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
6263/// could read, or carried nothing at all. Long enough that a quota outage
6264/// cannot burn through a whole backlog in the few seconds each doomed attempt
6265/// takes to fail; short enough that a quota which clears early is not left
6266/// idle for the fallback's sake.
6267const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
6268
6269/// Longest a parsed reset hint may push the wait out to. The hint comes from
6270/// the CLI's own words, not a contract, so a parsing slip that lands a day
6271/// away must not leave the loop asleep for a day.
6272const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
6273
6274/// How long [`poll`] should wait before offering the next task, after a run
6275/// lost at least one seat to a rate limit.
6276///
6277/// Pure and separate from the loop so the policy can be exercised without a
6278/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
6279/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
6280/// nothing to parse, or the parsed time has already passed; `cap` bounds how
6281/// far a parsed hint is trusted to push the wait out.
6282fn quota_wait(
6283    reset_at: Option<Timestamp>,
6284    now: Timestamp,
6285    fallback: Duration,
6286    cap: Duration,
6287) -> Duration {
6288    match reset_at {
6289        Some(at) if at > now => {
6290            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
6291            Duration::from_secs(secs).min(cap)
6292        }
6293        _ => fallback,
6294    }
6295}
6296
6297/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
6298///
6299/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
6300/// explains why parsing it exactly "would be a bug factory" — so this only
6301/// recognises the shapes actually observed in the wild, and returns `None`
6302/// for anything else rather than guess at a format nobody has seen.
6303///
6304/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
6305/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
6306/// said it, not from whenever this loop happens to read it: anchoring on `now`
6307/// would push the reset later on every read and would read an already-elapsed
6308/// reset as still in the future. (A long hint is still clamped by
6309/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
6310fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
6311    parse_reset_hint_zoned(text, now)
6312        .or_else(|| parse_reset_hint_dated(text))
6313        .or_else(|| parse_reset_hint_relative(text, recorded))
6314}
6315
6316/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
6317/// optional but at least one required, in that order. A bare number or any
6318/// unknown unit is refused.
6319fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
6320    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
6321    let mut rest = rest.trim();
6322    if rest.is_empty() {
6323        return None;
6324    }
6325    let mut total: i64 = 0;
6326    let mut matched = false;
6327    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
6328        if let Some((digits, tail)) = rest.split_once(unit)
6329            && !digits.is_empty()
6330            && digits.bytes().all(|b| b.is_ascii_digit())
6331        {
6332            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
6333            rest = tail;
6334            matched = true;
6335        }
6336    }
6337    if !rest.is_empty() || !matched {
6338        return None;
6339    }
6340    recorded
6341        .checked_add(jiff::SignedDuration::from_secs(total))
6342        .ok()
6343}
6344
6345/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
6346/// case-insensitive) into a 24-hour hour and minute. Shared by every
6347/// reset-hint shape below.
6348fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
6349    let clock = clock.trim().to_lowercase();
6350    let (digits, pm) = clock
6351        .strip_suffix("am")
6352        .map(|d| (d, false))
6353        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
6354    let (h, m) = digits.trim().split_once(':')?;
6355    let mut hour: i8 = h.trim().parse().ok()?;
6356    let minute: i8 = m.trim().parse().ok()?;
6357    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
6358        return None;
6359    }
6360    if pm && hour != 12 {
6361        hour += 12;
6362    } else if !pm && hour == 12 {
6363        hour = 0;
6364    }
6365    Some((hour, minute))
6366}
6367
6368/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
6369/// and a zone, never a date. A clock reading already past today is read as
6370/// tomorrow's: a CLI naming a same-day reset that has already gone by means
6371/// the window rolled over while nothing was watching.
6372fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
6373    let open = text.find('(')?;
6374    let close = text.rfind(')')?;
6375    if close <= open {
6376        return None;
6377    }
6378    let zone = text[open + 1..close].trim();
6379    let (hour, minute) = parse_12h_clock(&text[..open])?;
6380    let tz = jiff::tz::TimeZone::get(zone).ok()?;
6381    let candidate = now
6382        .to_zoned(tz)
6383        .with()
6384        .hour(hour)
6385        .minute(minute)
6386        .second(0)
6387        .millisecond(0)
6388        .microsecond(0)
6389        .nanosecond(0)
6390        .build()
6391        .ok()?;
6392    let mut at = candidate.timestamp();
6393    if at <= now {
6394        at += jiff::SignedDuration::from_hours(24);
6395    }
6396    Some(at)
6397}
6398
6399/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
6400/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
6401/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
6402/// "already past today" correction to make: the year already disambiguates
6403/// it. Scanned as a five-word window so it can be pulled out of the middle
6404/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
6405/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
6406/// any other timestamp with no zone attached.
6407fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
6408    let words: Vec<&str> = text.split_whitespace().collect();
6409    if words.len() < 5 {
6410        return None;
6411    }
6412    (0..=words.len() - 5)
6413        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
6414}
6415
6416/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
6417/// parenthesis right after the window is refused rather than ignored — it
6418/// reads as an explicit zone annotation on a shape that otherwise carries
6419/// none, and guessing UTC anyway would be exactly the silent misread this
6420/// module's parsing otherwise avoids.
6421fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
6422    if trailing.is_some_and(|next| next.starts_with('(')) {
6423        return None;
6424    }
6425    let month = month_number(window[0])?;
6426    let day_token = window[1].strip_suffix(',')?.to_lowercase();
6427    let day_digits = ["st", "nd", "rd", "th"]
6428        .iter()
6429        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
6430    let day: i8 = day_digits.parse().ok()?;
6431    let year_token = window[2];
6432    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
6433        return None;
6434    }
6435    let year: i16 = year_token.parse().ok()?;
6436    // The am/pm word carries the sentence's own trailing punctuation, e.g.
6437    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
6438    // reusing the same 12-hour clock reader the bracketed shape uses.
6439    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
6440    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
6441    let date = jiff::civil::Date::new(year, month, day).ok()?;
6442    let candidate = date
6443        .at(hour, minute, 0, 0)
6444        .to_zoned(jiff::tz::TimeZone::UTC)
6445        .ok()?;
6446    Some(candidate.timestamp())
6447}
6448
6449/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
6450/// case-insensitively, into a 1-based month number.
6451fn month_number(name: &str) -> Option<i8> {
6452    const NAMES: [&str; 12] = [
6453        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
6454    ];
6455    let lower = name.to_lowercase();
6456    NAMES
6457        .iter()
6458        .position(|n| *n == lower.as_str())
6459        .map(|i| i as i8 + 1)
6460}
6461
6462/// Test probe for the shared resume policy's review-budget exclusion.
6463#[cfg(test)]
6464fn exhausted_review_budget(state: &RunState) -> bool {
6465    // A run whose task-head publication failed has nothing left to review:
6466    // resuming it only retries the publication, so it is never "exhausted".
6467    !crate::handover::can_resume(state)
6468        && state.status == RunStatus::Blocked
6469        && !state.released()
6470        && state.retired_to.is_none()
6471}
6472
6473/// This task's *most recent* run, if resuming it would actually make
6474/// progress. `short` is only for the warning's own message.
6475///
6476/// Only ever `runs.last()` — never a search back through older history.
6477/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
6478/// mint, oldest first, and every entry before the last one was already
6479/// superseded at the moment it was minted: the daemon only ever starts a new
6480/// run when the previous one was not worth resuming (unresumable, exhausted,
6481/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
6482/// opens a fresh review-only run alongside an older, already-failed
6483/// competition. Searching further back would let an old run that merely
6484/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
6485/// behind, say — get resumed instead of the fresh competition
6486/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
6487/// nothing asked to revisit.
6488///
6489/// Two runs paid for the "prefer resuming over restarting" half of this
6490/// lesson, which is why this still checks `runs.last()` rather than always
6491/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
6492/// task a moment later, duplicating two and a half hours of agent work. Then
6493/// b25f stalled on a judge that timed out and one that answered with no JSON
6494/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
6495/// **one second** later, buying three fresh implementations to reach the
6496/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
6497/// the second case: a stall is terminal, and its cheap recovery re-asks only
6498/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
6499/// that is technically `resumable()` but provably cannot progress must not
6500/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
6501/// no-op instead of the fresh competition it promises.
6502///
6503/// A load failure is warned about rather than silently read as "not
6504/// resumable": the alternative is exactly what let a schema mismatch on run
6505/// `eba2` fall through to a full re-competition with nobody told why.
6506/// `crate::conduct` is what actually offers a better answer than
6507/// `Runner::start` here (see `Recovery::Review`), once this task's next
6508/// failure shows it up as `held`/`failed` with the run state unreadable.
6509fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
6510    unfinished_run_with(runs, short, RunState::load)
6511}
6512
6513/// [`unfinished_run`] with an injected state reader. Tests provide their
6514/// fixtures directly rather than touching the process-global run home.
6515pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6516where
6517    F: FnMut(&str) -> Result<RunState>,
6518{
6519    let mut id = runs.last()?.clone();
6520    let mut visited = std::collections::BTreeSet::new();
6521    let mut repo = None;
6522    loop {
6523        if !runs.contains(&id) || !visited.insert(id.clone()) {
6524            tracing::warn!("invalid or cyclic recovery authority for task {short}");
6525            return None;
6526        }
6527        let state = match load(&id) {
6528            Ok(state) if state.id == id => state,
6529            Ok(_) => return None,
6530            Err(e) => {
6531                tracing::warn!("could not read run {id} for task {short}: {e:#}");
6532                return None;
6533            }
6534        };
6535        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6536            return None;
6537        }
6538        repo = Some(state.repo.clone());
6539        if let Some(authority) = state.retired_to {
6540            id = authority;
6541            continue;
6542        }
6543        return (crate::handover::can_resume(&state)
6544            && state.liveness(false) != crate::run::Liveness::Live)
6545            .then_some(id);
6546    }
6547}
6548
6549/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
6550/// that [`attempt`] will resume it on its own?
6551///
6552/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
6553/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
6554/// injected reader like its sibling. An unreadable run is not awaiting
6555/// anything: it keeps going to the conductor as before.
6556fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6557where
6558    F: FnOnce(&str) -> Result<RunState>,
6559{
6560    // `Failed` stays: a record an older build wrote for a parked run.
6561    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6562        || task.fresh_start
6563        || task.review_branch.is_some()
6564    {
6565        return false;
6566    }
6567    let Some(id) = task.execution_runs().last() else {
6568        return false;
6569    };
6570    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6571}
6572
6573/// Which of the three ways [`attempt`] can mint or continue a run this task
6574/// should use.
6575#[derive(Debug, Clone, PartialEq, Eq)]
6576enum Starter {
6577    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
6578    /// and that still exists.
6579    Review(String),
6580    /// `crate::graph::Runner::resume` on an unfinished run of this task.
6581    Resume(String),
6582    /// `crate::graph::Runner::start`: a fresh competition.
6583    Start,
6584}
6585
6586/// A second bound independent of inputs and the resettable failure counter.
6587/// Count execution and failed-startup recovery records once per run. Startup
6588/// failures can retain unrecorded preparation assets without an execution pass.
6589/// Unknown history is not evidence that a new set of worktrees is affordable.
6590fn retained_attempt_hold(
6591    task: &Task,
6592    starter: &Starter,
6593    limit: usize,
6594    mut load: impl FnMut(&str) -> Result<RunState>,
6595) -> Option<String> {
6596    if limit == 0 || matches!(starter, Starter::Resume(_)) {
6597        return None;
6598    }
6599    let mut retained = 0;
6600    for id in task
6601        .runs
6602        .iter()
6603        .chain(task.startup_failures.iter().map(|failure| &failure.run))
6604        .collect::<std::collections::BTreeSet<_>>()
6605    {
6606        let state = match load(id) {
6607            Ok(state) if state.id == *id => state,
6608            _ => {
6609                return Some(format!(
6610                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6611                ));
6612            }
6613        };
6614        if state.retired_to.is_some() || state.released() {
6615            continue;
6616        }
6617        // Neither a completed status nor an empty candidate array proves that
6618        // all recovery sources (including unrecorded preparation) were retired.
6619        retained += 1;
6620    }
6621    (retained >= limit).then(|| format!(
6622        "[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."
6623    ))
6624}
6625
6626/// A selected public implementation overrides every historical candidate and pin.
6627fn selected_starter(
6628    selected: &crate::pr_recovery::Selection,
6629    previous: Option<&RunState>,
6630    unfinished: Option<&str>,
6631) -> Starter {
6632    if let Some(id) = unfinished
6633        && previous.is_some_and(|r| {
6634            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6635        })
6636    {
6637        Starter::Resume(id.to_owned())
6638    } else {
6639        Starter::Review(selected.branch.clone())
6640    }
6641}
6642
6643/// The owner's answer to this branch's divergence question, consumed from the
6644/// task so a later, different divergence asks again. The runner applies it
6645/// (see `Runner::review_taking_over`), after the earlier worktree is released.
6646fn take_divergence_answer(
6647    branch: &str,
6648    remote: &str,
6649    task: &mut Task,
6650) -> Option<crate::reconcile::Choice> {
6651    let summary = crate::reconcile::summary_for(branch, remote);
6652    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6653        (a.question == summary)
6654            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6655            .flatten()
6656            .map(|c| (i, c))
6657    })?;
6658    task.answers.remove(idx);
6659    Some(choice)
6660}
6661
6662/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
6663/// this attempt should use. Pure, and separate from [`attempt`], so the
6664/// routing itself is assertable without spawning a real graph or a git
6665/// process: `attempt`'s own `crate::git::branch_exists` call has already
6666/// happened by the time this is called.
6667///
6668/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
6669/// whose branch is gone falls all the way through to [`Starter::Start`], not
6670/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
6671/// old (likely `Blocked`) run in the first place, and a branch that vanished
6672/// out from under that choice is not evidence resuming it would fare better.
6673fn choose_starter(
6674    review_branch: Option<&str>,
6675    branch_exists: bool,
6676    unfinished: Option<&str>,
6677) -> Starter {
6678    match review_branch {
6679        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6680        Some(_) => Starter::Start,
6681        None => match unfinished {
6682            Some(id) => Starter::Resume(id.to_owned()),
6683            None => Starter::Start,
6684        },
6685    }
6686}
6687
6688/// Reuse a compatible latest review owner instead of taking its checked-out
6689/// branch into a new run. Different branches and changed criteria still use
6690/// the ordinary review/takeover policy.
6691fn review_retry_starter(
6692    task: &Task,
6693    previous: Option<&RunState>,
6694    branch: Option<&str>,
6695    exists: bool,
6696    unfinished: Option<&str>,
6697) -> Starter {
6698    if let Some(run) = previous
6699        && unfinished == Some(run.id.as_str())
6700        && run.reviewed_commits.is_some()
6701        && branch.is_some_and(|branch| {
6702            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6703        })
6704        && may_resume_run(run, task)
6705    {
6706        return Starter::Resume(run.id.clone());
6707    }
6708    match (branch, unfinished, &task.review_of) {
6709        (None, None, Some(branch)) => Starter::Review(branch.clone()),
6710        _ => choose_starter(branch, exists, unfinished),
6711    }
6712}
6713
6714/// A retained review is valid only while its authored criteria still match.
6715fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
6716    task.review_branch
6717        .as_deref()
6718        .filter(|&branch| match &task.review_instruction {
6719            Some(authored) => *authored == task.instruction,
6720            // Legacy retained branches must agree with their prior run; only an
6721            // explicitly pinned review can proceed without recoverable provenance.
6722            None => previous.map_or_else(
6723                || task.review_of.as_deref() == Some(branch),
6724                |run| compatible_run_instruction(run, task),
6725            ),
6726        })
6727}
6728
6729/// A current explicit pin can select an otherwise incompatible run. Edits
6730/// and subsequent approvals invalidate pins selected for earlier criteria.
6731fn may_resume_run(run: &RunState, task: &Task) -> bool {
6732    if !task.assignment_accepts(run) {
6733        return false;
6734    }
6735    task.resume_override
6736        .as_ref()
6737        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6738        || compatible_run_instruction(run, task)
6739}
6740
6741/// Review scaffolding is execution context, not evidence of an operator edit.
6742pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6743    if let Some(authored) = &run.task_instruction {
6744        return compatible_instruction(authored, task);
6745    }
6746    if compatible_instruction(&run.instruction, task) {
6747        return true;
6748    }
6749    // Recognize only the existing generated review shapes on legacy runs.
6750    // Ordinary authored text with a similar heading is left intact.
6751    if run.reviewed_commits.is_some() {
6752        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6753            return strip_answers_block(authored, task).trim() == task.instruction.trim();
6754        }
6755        if let Some(branch) = &task.review_of {
6756            let canonical = format!(
6757                "Review the branch `{branch}` (review-only: no implementation, no judging)."
6758            );
6759            let generated = format!(
6760                "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"
6761            );
6762            return task.instruction == canonical && run.instruction.starts_with(&generated);
6763        }
6764    }
6765    false
6766}
6767
6768/// Compare authored instructions, excluding answer blocks appended by the daemon.
6769pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6770    strip_answers_block(old, task) == task.instruction
6771}
6772
6773/// Which repository a task runs in. A task that names none — the normal case
6774/// for one filed from a phone — runs in the daemon's own default.
6775fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6776    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6777        return fallback.to_path_buf();
6778    }
6779    task.repo.clone()
6780}
6781
6782/// The header [`append_answers`] appends operator answers under. Shared with
6783/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
6784/// rather than grown a new block on every resume.
6785const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6786
6787/// Render the first `count` answers in the block appended to an instruction.
6788fn answers_block(task: &Task, count: usize) -> String {
6789    let mut s = ANSWERS_HEADER.to_owned();
6790    for a in &task.answers[..count] {
6791        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6792    }
6793    s
6794}
6795
6796/// Render the approval independently of transient task state, so historical
6797/// suffixes remain recognizable after another explicit release.
6798fn resumption_block(r: &crate::queue::Resumption) -> String {
6799    format!(
6800        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6801         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6802        r.generation, r.at, r.instruction, r.answers_through,
6803    )
6804}
6805
6806/// Append audit answers and the latest explicit approval to the instruction.
6807fn append_answers(base: &str, task: &Task) -> String {
6808    let mut s = base.to_owned();
6809    if !task.answers.is_empty() {
6810        s.push_str(&answers_block(task, task.answers.len()));
6811    }
6812    if let Some(r) = &task.resumption {
6813        s.push_str(&resumption_block(r));
6814    }
6815    s
6816}
6817
6818/// Drop the prior answer block only when it is exactly the suffix this task
6819/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6820/// the task author is ordinary instruction text, not a block to remove.
6821fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6822    let mut instruction = instruction;
6823    for approval in task
6824        .resumption
6825        .iter()
6826        .chain(task.resumption_history.iter().rev())
6827    {
6828        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6829            instruction = base;
6830            break;
6831        }
6832    }
6833    for count in (1..=task.answers.len()).rev() {
6834        let block = answers_block(task, count);
6835        if let Some(base) = instruction.strip_suffix(&block) {
6836            return base;
6837        }
6838    }
6839    instruction
6840}
6841
6842/// The instruction handed to `Runner::start`: the task's own text, plus any
6843/// operator answers `crate::conduct` collected for it (see
6844/// [`Task::answers`]), so a decision the operator actually made reaches the
6845/// implementers rather than only clearing the block that was waiting on it.
6846///
6847/// Appended rather than merged into [`Task::instruction`] itself, so the
6848/// task's own record stays exactly what its author wrote.
6849fn instruction_for(task: &Task) -> String {
6850    append_answers(&task.instruction, task)
6851}
6852
6853/// The instruction a resumed run should carry on with: whatever it already
6854/// had, refreshed with the task's *current* operator answers.
6855///
6856/// A resumable run's own `RunState::instruction` predates any answer
6857/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6858/// the behaviour before this function existed — silently drops the very
6859/// decision the operator made to unblock it. Re-stripping any block this
6860/// function appended on an earlier resume before re-appending the current
6861/// list (rather than blindly appending again) is what keeps a task resumed
6862/// three times over three answered questions from carrying the same answer
6863/// three times.
6864fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6865    append_answers(strip_answers_block(old_instruction, task), task)
6866}
6867
6868/// Preserve the producer's verified boundary and target, independent of prose.
6869fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6870    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6871    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6872    if let Some(cause) = task.hold_notice_cause.as_mut() {
6873        cause.target = failure.map(|f| f.target.clone());
6874    }
6875}
6876
6877#[derive(Debug, thiserror::Error)]
6878#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6879struct MissingAttachment {
6880    name: String,
6881    path: PathBuf,
6882}
6883
6884/// The task's attachments as absolute paths, each checked to still exist.
6885fn task_attachments(
6886    queue: &Queue,
6887    task: &Task,
6888) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6889    let paths = queue.attachment_paths(task);
6890    for (name, path) in task.attachments.iter().zip(&paths) {
6891        if !path.is_file() {
6892            return Err(MissingAttachment {
6893                name: name.clone(),
6894                path: path.clone(),
6895            });
6896        }
6897    }
6898    Ok(paths)
6899}
6900
6901/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6902/// answers before handing it to `Runner` — the actual boundary between
6903/// [`choose_starter`]'s routing and the graph, factored out so it is
6904/// assertable without a real repository, git branch, or agent CLI.
6905///
6906/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6907/// instruction from the reviewed branch's own commit log because there is no
6908/// task statement to speak of for hand-written work, and splicing operator
6909/// answers into that text would contradict the very message it sends
6910/// reviewers ("there is no task statement").
6911fn prepare_instruction(
6912    starter: &Starter,
6913    old_instruction: Option<&str>,
6914    task: &Task,
6915) -> Option<String> {
6916    match starter {
6917        Starter::Start => Some(instruction_for(task)),
6918        Starter::Resume(_) => Some(resumed_instruction(
6919            old_instruction.expect("a resumed run always has a prior instruction"),
6920            task,
6921        )),
6922        Starter::Review(_) => None,
6923    }
6924}
6925
6926/// Persist a transition. A queue write failure is logged rather than fatal: the
6927/// run already happened, and taking the daemon down would only add a lost
6928/// backlog to a full disk.
6929fn record(queue: &Queue, task: &mut Task) {
6930    if let Err(e) = queue.put(task) {
6931        tracing::error!("could not record task {}: {e:#}", task.short());
6932        let notice = Notice::error(
6933            "loop:record",
6934            format!(
6935                "Task {} state could not be saved: {}. Check the disk.",
6936                task.id,
6937                e.to_string().lines().next().unwrap_or("unknown save error")
6938            ),
6939        )
6940        .link(Link::Task {
6941            id: task.id.clone(),
6942        });
6943        // The queue lives at `<home>/queue`, so its parent is the home.
6944        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6945            Some(home) => notices::raise_in(home, notice),
6946            None => notices::raise(notice),
6947        }
6948    }
6949}
6950
6951/// Every runnable task, in the order the loop should try them.
6952///
6953/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6954/// tail exists so that a claim somebody else holds costs the loop the next
6955/// candidate rather than a whole poll interval of idleness.
6956fn runnable(queue: &Queue) -> Vec<Task> {
6957    let mut tasks: Vec<Task> = queue
6958        .list()
6959        .into_iter()
6960        .filter(|t| t.status.runnable())
6961        .collect();
6962    tasks.sort_unstable_by(crate::queue::dispatch_order);
6963    tasks
6964}
6965
6966/// Why a run ended where it did, in one line, for [`Task::last_error`].
6967///
6968/// A stalled run names the seats the quota took out: "out of quota" is not
6969/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6970/// agent to replace or which plan to top up.
6971///
6972/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6973/// purpose: unlike `label`'s other callers (an internal log line, an
6974/// already-a-bug fallback message), this string becomes `Task::last_error`
6975/// verbatim, which the phone renders in the same alarm-styled box an
6976/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6977/// `.err` styling. A bare `verified_noop` there would read exactly like the
6978/// failure this whole feature exists to tell apart from one.
6979fn describe(state: &RunState) -> String {
6980    let p = phrases(&state.config.graph.language);
6981    let mut detail = if state.status == RunStatus::Stalled {
6982        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6983        seats.sort_unstable();
6984        seats.dedup();
6985        if seats.is_empty() {
6986            p.quorum_lost.to_owned()
6987        } else {
6988            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6989        }
6990    } else {
6991        format!("{}{}", p.run_ended, state.status.display_label())
6992    };
6993    if let Some(cause) = state.verification_blocking_cause() {
6994        detail.push_str(&format!(" ({cause})"));
6995    } else if let Some(last) = state.events.last() {
6996        // The review loop's "never answered" stop is the one event worth
6997        // translating; it is recognised from structured state, not by
6998        // matching the English event text (which stays as recorded).
6999        let unanswered = state
7000            .reviews
7001            .last()
7002            .filter(|r| {
7003                state.status == RunStatus::Blocked
7004                    && last.node == "review"
7005                    && r.incomplete()
7006                    && r.blocking == 0
7007                    && r.round == state.config.graph.review_rounds
7008                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
7009            })
7010            .map(|r| (r.expected - r.answered, r.round));
7011        match unanswered {
7012            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
7013                detail.push_str(&format!(
7014                    " ({}: {})",
7015                    last.node,
7016                    (p.reviewers_never_answered)(missing, rounds)
7017                ));
7018            }
7019            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
7020        }
7021    }
7022    detail.push_str(&format!(" [run {}]", state.id));
7023    detail
7024}
7025
7026/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
7027///
7028/// The task file lives in the backlog indefinitely; a diagnostic is an
7029/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
7030/// stay small regardless of how much a gate command or a candidate printed.
7031const DIAGNOSTIC_MAX: usize = 4_000;
7032
7033/// Tail kept from a single failing command's output inside a diagnostic.
7034/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
7035/// pointer for a human deciding whether to go read the full artifact by hand,
7036/// not a replacement for reading it.
7037const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
7038
7039/// Assemble a bounded diagnostic excerpt from a held task's own run, so
7040/// `magi task show` says more than the one-line reason in [`describe`].
7041///
7042/// The one-liner answers "where did the run stop"; this answers "what would a
7043/// human have found opening `artifacts/` by hand" — the point of the whole
7044/// feature is the case that one-liner actively misleads on: a run held as "no
7045/// candidate produced a change" can mean the implementer actually finished
7046/// the task (opened a PR, merged it, tagged a release) and only left a clean
7047/// local worktree behind, which reads as "nothing happened" unless someone
7048/// goes and reads what the agent actually said. `None` when the run carries
7049/// none of the three shapes this recognises — an ordinary run held for
7050/// something not diagnosable from `RunState` alone still explains itself
7051/// through `Task::last_error`.
7052pub(crate) fn diagnostic_for(state: &RunState) -> Option<String> {
7053    diagnostic(state)
7054}
7055
7056fn diagnostic(state: &RunState) -> Option<String> {
7057    let mut parts: Vec<String> = Vec::new();
7058
7059    if let Some(e2e) = &state.head_e2e
7060        && !e2e.passed
7061    {
7062        for o in e2e
7063            .outcomes
7064            .iter()
7065            .filter(|o| !o.ok() && !o.resource_blocked)
7066        {
7067            parts.push(format!(
7068                "head_e2e `{}` failed on {} ({}):\n{}",
7069                o.command,
7070                e2e.head.chars().take(7).collect::<String>(),
7071                notices::exit_status(o.code),
7072                crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
7073            ));
7074        }
7075    }
7076
7077    // Gate failure: which check(s), and the tail of what each printed.
7078    for o in state.gate.iter().filter(|o| !o.ok()) {
7079        parts.push(format!(
7080            "gate `{}` failed ({}):\n{}",
7081            o.command,
7082            notices::exit_status(o.code),
7083            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
7084        ));
7085    }
7086
7087    // The land loop gave up because the fixer declined while checks were
7088    // still red: the message already names them (see `land::run`).
7089    if let Some(last) = state
7090        .events
7091        .iter()
7092        .rev()
7093        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
7094    {
7095        parts.push(last.message.clone());
7096    }
7097
7098    // No viable candidate: every implementer's own final word, sanitized the
7099    // same way a judge would have read it, so a run that actually finished
7100    // the job does not read as an unexplained failure. A verified no-op is
7101    // called out ahead of its own summary and apart from an ordinary
7102    // failure's `why` — this is the one candidate shape whose diagnostic a
7103    // human is expected to actually judge, not just skim.
7104    if state.viable().is_empty() {
7105        for c in &state.candidates {
7106            if c.has_valid_verified_noop()
7107                && let Some(evidence) = c.verified_noop_display()
7108            {
7109                parts.push(format!(
7110                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
7111                    c.label
7112                ));
7113            } else if !c.summary.trim().is_empty() {
7114                if let Some(why) = &c.failed {
7115                    parts.push(format!(
7116                        "candidate {} ({why}): {}",
7117                        c.label,
7118                        c.summary.trim()
7119                    ));
7120                } else {
7121                    parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
7122                }
7123            } else if let Some(why) = &c.failed {
7124                parts.push(format!("candidate {}: {why}", c.label));
7125            }
7126        }
7127    }
7128
7129    if parts.is_empty() {
7130        return None;
7131    }
7132    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
7133    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
7134    // back slightly over. Leave it enough room to always land under the
7135    // limit.
7136    Some(crate::run::tail(
7137        &parts.join("\n\n"),
7138        DIAGNOSTIC_MAX.saturating_sub(100),
7139    ))
7140}
7141
7142/// Stable lower-case name for a run status, for an internal log line and the
7143/// "graph stopped without reaching a terminal status" bug message in
7144/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
7145/// doc for why that one reads [`RunStatus::display_label`] instead. One
7146/// definition of a status's name, on the type that owns it: this table used
7147/// to live here as a second copy, and a status renamed in one place would
7148/// have gone on reading correctly in the other.
7149fn label(status: RunStatus) -> &'static str {
7150    status.as_str()
7151}
7152
7153/// Parse a merge mode override.
7154pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
7155    match mode {
7156        "none" => Ok(MergeMode::None),
7157        "local" => Ok(MergeMode::Local),
7158        "pr" => Ok(MergeMode::Pr),
7159        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
7160    }
7161}
7162
7163/// Take the status lock, recovering from a poisoned one.
7164///
7165/// A panic elsewhere must not silently stop the heartbeat: the status is plain
7166/// data, and the worst a poisoned lock can hold is a stale timestamp.
7167fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
7168    mutex
7169        .lock()
7170        .unwrap_or_else(std::sync::PoisonError::into_inner)
7171}
7172
7173#[cfg(test)]
7174mod tests {
7175    use super::*;
7176    use crate::queue::{Source, TaskStatus};
7177    use crate::run::{Candidate, CommandOutcome};
7178    use pretty_assertions::assert_eq;
7179
7180    fn task() -> Task {
7181        Task::new(
7182            "add retries".to_owned(),
7183            "add retries".to_owned(),
7184            PathBuf::from("/repo"),
7185            Source::Human,
7186        )
7187    }
7188
7189    #[test]
7190    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
7191        let skips = DispatchSkips::from([
7192            ("a".into(), SkipReason::CoolingDown),
7193            ("b".into(), SkipReason::WaitingOnLanding),
7194            ("c".into(), SkipReason::WaitingOnLanding),
7195            ("d".into(), SkipReason::OrdinaryCapacity),
7196        ]);
7197        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
7198        assert_eq!(wait.runnable, 4);
7199        assert_eq!(
7200            wait.reasons
7201                .iter()
7202                .map(|r| (r.reason.as_str(), r.count))
7203                .collect::<Vec<_>>(),
7204            [
7205                ("waiting_on_landing", 2),
7206                ("cooling_down", 1),
7207                ("ordinary_capacity", 1)
7208            ]
7209        );
7210        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
7211        assert!(
7212            aggregate_dispatch_wait(2, &DispatchSkips::new())
7213                .unwrap()
7214                .reasons
7215                .is_empty()
7216        );
7217    }
7218
7219    #[test]
7220    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
7221        let before = vec!["a".into(), "b".into(), "c".into()];
7222        let allowed = vec![task_with_id("b")];
7223        let skips = interrupt_skips(&before, &allowed);
7224        assert_eq!(
7225            skips,
7226            DispatchSkips::from([
7227                ("a".into(), SkipReason::InterruptGate),
7228                ("c".into(), SkipReason::InterruptGate),
7229            ])
7230        );
7231        let mut previous = DispatchSkips::new();
7232        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7233        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
7234        assert!(!changed_dispatch_skips(&mut previous, skips));
7235        assert!(changed_dispatch_skips(
7236            &mut previous,
7237            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
7238        ));
7239        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7240    }
7241
7242    #[test]
7243    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
7244        let mut value = serde_json::to_value(Status::new()).unwrap();
7245        value.as_object_mut().unwrap().remove("dispatch_wait");
7246        assert!(
7247            serde_json::from_value::<Status>(value.clone())
7248                .unwrap()
7249                .dispatch_wait
7250                .is_none()
7251        );
7252        assert!(
7253            serde_json::from_value::<Reading>(value.clone())
7254                .unwrap()
7255                .dispatch_wait
7256                .is_none()
7257        );
7258        value["dispatch_wait"] = serde_json::json!({
7259            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
7260        });
7261        let reading = serde_json::from_value::<Reading>(value).unwrap();
7262        assert_eq!(
7263            reading.dispatch_wait.unwrap().reasons[0].reason,
7264            "future_reason"
7265        );
7266    }
7267
7268    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
7269        let job = crate::worker::Job {
7270            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
7271            sequence: 1,
7272            kind: "task".into(),
7273            key: format!("task:{}", request.task),
7274            payload: serde_json::to_value(request).unwrap(),
7275            generation: "a".repeat(64),
7276            version: None,
7277            status: crate::worker::Status::Starting,
7278            result: None,
7279            pid: None,
7280            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
7281            finished_at: None,
7282        };
7283        let dir = home.join("workers/jobs").join(&job.id);
7284        std::fs::create_dir_all(&dir).unwrap();
7285        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
7286        job
7287    }
7288
7289    #[test]
7290    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
7291        let home = tempfile::tempdir().unwrap();
7292        let request = TaskWorker {
7293            opts: Opts::default(),
7294            queue: home.path().join("queue"),
7295            task: "startup".into(),
7296            lane: PermitKind::Ordinary,
7297            standalone: false,
7298        };
7299        let job = starting_task_reservation(home.path(), &request);
7300        let error = task_worker_spawn_error(
7301            home.path(),
7302            &request,
7303            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
7304        )
7305        .expect_err("our own reservation must not turn a failed spawn into a resync");
7306        let active = crate::worker::active(home.path()).unwrap();
7307        assert_eq!(active.len(), 1);
7308        assert_eq!(active[0].id, job.id);
7309        assert_eq!(active[0].status, crate::worker::Status::Starting);
7310        assert!(
7311            crate::worker::control(home.path(), &job.key)
7312                .unwrap()
7313                .is_none()
7314        );
7315        let notices = notices::Notices::at(home.path().join("notifications")).list();
7316        assert_eq!(notices.len(), 1);
7317        assert_eq!(notices[0].key, "loop:worker-startup");
7318        assert!(!notices[0].message.contains("private-error-detail"));
7319        assert!(notices[0].message.contains(&request.task));
7320        assert!(
7321            notices[0]
7322                .message
7323                .contains("could not be started or acknowledged")
7324        );
7325        assert!(notices[0].message.contains("worker.log"));
7326        assert_eq!(
7327            notices[0].link,
7328            Some(Link::Task {
7329                id: request.task.clone()
7330            })
7331        );
7332        assert!(format!("{error:#}").contains("private-error-detail"));
7333    }
7334
7335    #[test]
7336    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
7337        let home = tempfile::tempdir().unwrap();
7338        let mut request = TaskWorker {
7339            opts: Opts::default(),
7340            queue: home.path().join("queue"),
7341            task: "handoff".into(),
7342            lane: PermitKind::Ordinary,
7343            standalone: true,
7344        };
7345        let job = starting_task_reservation(home.path(), &request);
7346        request.standalone = false;
7347        task_worker_spawn_error(
7348            home.path(),
7349            &request,
7350            anyhow::anyhow!("operation key is already reserved for a different request"),
7351        )
7352        .expect("a different standalone request is the handoff race, not our startup failure");
7353        let active = crate::worker::active(home.path()).unwrap();
7354        assert_eq!(active.len(), 1);
7355        assert_eq!(active[0].id, job.id);
7356        assert_eq!(active[0].payload, job.payload);
7357        assert!(
7358            notices::Notices::at(home.path().join("notifications"))
7359                .list()
7360                .is_empty()
7361        );
7362    }
7363
7364    #[test]
7365    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
7366        let home = tempfile::tempdir().unwrap();
7367        let queue = Queue::at(home.path().join("queue"));
7368        let mut task = task();
7369        task.runs = vec!["previous".into()];
7370        queue.put(&mut task).unwrap();
7371        let request = TaskWorker {
7372            opts: Opts::default(),
7373            queue: home.path().join("queue"),
7374            task: task.id.clone(),
7375            lane: PermitKind::Ordinary,
7376            standalone: false,
7377        };
7378        let job = starting_task_reservation(home.path(), &request);
7379        let claims = current_work(home.path(), Timestamp::now());
7380        assert_eq!(claims.len(), 1);
7381        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
7382        assert_eq!(claims[0].run, "previous");
7383        assert!(other_claims_run(&claims, "previous", None));
7384        // Only after confirming the executing caller may admission ignore
7385        // this exact projection. Cleanup continues to observe it as live.
7386        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
7387        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
7388    }
7389
7390    #[test]
7391    fn admission_excludes_only_the_callers_exact_reservation() {
7392        let own = Current {
7393            worker: Some("own".into()),
7394            task: "same-task".into(),
7395            run: "previous".into(),
7396        };
7397        assert!(!other_claims_run(
7398            std::slice::from_ref(&own),
7399            "previous",
7400            Some("own")
7401        ));
7402        assert!(other_claims_run(
7403            std::slice::from_ref(&own),
7404            "previous",
7405            None
7406        ));
7407        for worker in [None, Some("other".into())] {
7408            let other = Current {
7409                worker,
7410                ..own.clone()
7411            };
7412            assert!(other_claims_run(
7413                &[own.clone(), other],
7414                "previous",
7415                Some("own")
7416            ));
7417        }
7418        let legacy: Current =
7419            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
7420        assert!(other_claims_run(&[legacy], "previous", Some("own")));
7421    }
7422
7423    #[test]
7424    fn os_leased_task_worker_survives_wall_clock_advance() {
7425        let home = tempfile::tempdir().unwrap();
7426        let queue = Queue::at(home.path().join("queue"));
7427        let mut task = task();
7428        let run = "20260903-100000-abcd";
7429        task.start(run.into());
7430        queue.put(&mut task).unwrap();
7431        let mut worker = live_task_fixture(home.path(), &task.id).unwrap();
7432        let future = Timestamp::now() + jiff::SignedDuration::from_secs(3600);
7433        assert!(
7434            current_work(home.path(), future)
7435                .iter()
7436                .any(
7437                    |claim| claim.worker.as_deref() == Some(worker.job.id.as_str())
7438                        && claim.run == run
7439                )
7440        );
7441        worker.release_lease();
7442        assert!(worker.dir.join("job.json").is_file());
7443        assert!(!is_working_on(home.path(), run, future));
7444        let dir = worker.dir.clone();
7445        drop(worker);
7446        assert!(!dir.exists());
7447    }
7448
7449    #[test]
7450    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
7451        let mut task = task();
7452        let mut run = run_state(RunStatus::Reviewing);
7453        run.task_instruction = Some(task.instruction.clone());
7454        run.reviewed_commits = Some(vec!["committed-fix".into()]);
7455        let branch = "magi/test/B";
7456        run.candidates.push(crate::run::Candidate {
7457            branch: branch.into(),
7458            ..candidate('B', "preserved work", false, None)
7459        });
7460        task.runs = vec![run.id.clone()];
7461        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
7462        assert_eq!(
7463            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7464            Starter::Resume(run.id.clone())
7465        );
7466        assert!(matches!(
7467            review_retry_starter(
7468                &task,
7469                Some(&run),
7470                Some("different"),
7471                true,
7472                unfinished.as_deref()
7473            ),
7474            Starter::Review(_)
7475        ));
7476        assert_eq!(
7477            review_retry_starter(
7478                &task,
7479                Some(&run),
7480                Some(branch),
7481                false,
7482                unfinished.as_deref()
7483            ),
7484            Starter::Start
7485        );
7486        task.instruction.push_str(" changed criteria");
7487        assert!(matches!(
7488            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7489            Starter::Review(_)
7490        ));
7491        assert!(matches!(
7492            review_retry_starter(&task, Some(&run), Some(branch), true, None),
7493            Starter::Review(_)
7494        ));
7495    }
7496
7497    #[test]
7498    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
7499        let dir = tempfile::tempdir().unwrap();
7500        let queue = Queue::at(dir.path().join("queue"));
7501        let mut task = task();
7502        task.status = TaskStatus::Running;
7503        task.attempts = 1;
7504        queue.put(&mut task).unwrap();
7505        let live = std::collections::BTreeSet::from([task.id.clone()]);
7506        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
7507        drop(queue.claim(&task.id).unwrap());
7508        let saved = queue.get(&task.id).unwrap();
7509        assert_eq!(saved.status, TaskStatus::Running);
7510        assert_eq!(saved.attempts, 1);
7511        assert!(saved.last_error.is_none());
7512    }
7513
7514    #[test]
7515    fn standalone_workers_do_not_consume_scheduler_lanes() {
7516        let request = |task: &str, lane, standalone| TaskWorker {
7517            opts: Opts::default(),
7518            queue: PathBuf::from("/queue"),
7519            task: task.to_owned(),
7520            lane,
7521            standalone,
7522        };
7523        let mut jobs = vec![
7524            request("ordinary", PermitKind::Ordinary, false),
7525            request("standalone-urgent", PermitKind::Urgent, true),
7526            request("standalone-ordinary", PermitKind::Ordinary, true),
7527            request("decision", PermitKind::None, false),
7528        ];
7529        assert_eq!(available_slots(&jobs, 2), (1, 1));
7530        jobs.push(request("urgent", PermitKind::Urgent, false));
7531        assert_eq!(available_slots(&jobs, 2), (1, 0));
7532        assert_eq!(available_slots(&jobs, 0), (0, 0));
7533    }
7534
7535    #[test]
7536    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
7537        let now = Timestamp::now();
7538        let mut reading = Reading {
7539            pid: Some(std::process::id()),
7540            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
7541            ..Reading::default()
7542        };
7543        assert!(!reading.running(now));
7544        assert!(legacy_scheduler_running(&reading, now, 0));
7545        reading.worker_protocol = Some(1);
7546        assert!(!legacy_scheduler_running(&reading, now, 0));
7547    }
7548
7549    #[test]
7550    fn selected_public_head_overrides_historical_resume_and_pin() {
7551        let mut t = task();
7552        let mut old = run_state(RunStatus::Blocked);
7553        let selection = crate::pr_recovery::Selection {
7554            url: "url".into(),
7555            branch: format!("magi/task-{}", t.id),
7556            head: "a".repeat(40),
7557            source_head: None,
7558            source_run: None,
7559            source_proof: None,
7560            disposition: Some(crate::pr_recovery::Disposition::Review),
7561            instruction: t.instruction.clone(),
7562            approved_at: Timestamp::now(),
7563        };
7564        t.resume_override = Some(crate::queue::OperatorResume {
7565            pinned_run: Some(old.id.clone()),
7566            question_id: "choice".into(),
7567            at: Timestamp::now(),
7568            conductor_rehold: None,
7569            forced: false,
7570        });
7571        assert_eq!(
7572            selected_starter(&selection, Some(&old), Some(&old.id)),
7573            Starter::Review(selection.branch.clone())
7574        );
7575        old.pr_recovery = Some(selection.clone());
7576        assert_eq!(
7577            selected_starter(&selection, Some(&old), Some(&old.id)),
7578            Starter::Review(selection.branch.clone())
7579        );
7580        old.reviewed_commits = Some(vec!["implementation".into()]);
7581        assert_eq!(
7582            selected_starter(&selection, Some(&old), Some(&old.id)),
7583            Starter::Resume(old.id.clone())
7584        );
7585        let mut changed = selection.clone();
7586        changed.head = "b".repeat(40);
7587        assert_eq!(
7588            selected_starter(&changed, Some(&old), Some(&old.id)),
7589            Starter::Review(changed.branch)
7590        );
7591    }
7592
7593    #[test]
7594    fn candidate_transplant_failure_is_one_actionable_hold() {
7595        let dir = tempfile::tempdir().unwrap();
7596        let q = Queue::at(dir.path().join("queue"));
7597        let mut t = task();
7598        let mut state = run_state(RunStatus::Blocked);
7599        state.event("prep", "cannot apply referenced commit: conflict");
7600        state.prep_failure = Some("conflict".into());
7601        t.start(state.id.clone());
7602        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
7603        assert_eq!(t.attempts, 1);
7604        assert_eq!(t.status, TaskStatus::Held);
7605        assert!(t.operator_held());
7606        assert!(!t.status.runnable());
7607        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
7608        let first = t.chat_notice_key().unwrap();
7609        t.chat_notices.push(first.clone());
7610        t.release_operator("test", None);
7611        state.id = "another-unprepared-run".into();
7612        t.start(state.id.clone());
7613        finish_attempt(
7614            3,
7615            &q,
7616            &mut t,
7617            &state,
7618            &[],
7619            Err(anyhow::anyhow!("still conflicts")),
7620        );
7621        assert_eq!(
7622            t.chat_notice_key().as_ref(),
7623            Some(&first),
7624            "no work happened"
7625        );
7626        t.release_operator("test", None);
7627        state.prep_failure = None;
7628        state.status = RunStatus::Failed;
7629        state.begin_pass();
7630        t.start(state.id.clone());
7631        finish_attempt(
7632            1,
7633            &q,
7634            &mut t,
7635            &state,
7636            &[],
7637            Err(anyhow::anyhow!("new gate failure")),
7638        );
7639        let failure = t.chat_notice_key().unwrap();
7640        assert_ne!(failure, first, "approved recovery reached a real failure");
7641        t.release_operator("test", None);
7642        state.begin_pass();
7643        t.start(state.id.clone());
7644        finish_attempt(
7645            1,
7646            &q,
7647            &mut t,
7648            &state,
7649            &[],
7650            Err(anyhow::anyhow!("new failure on resume")),
7651        );
7652        assert_ne!(
7653            t.chat_notice_key().as_ref(),
7654            Some(&failure),
7655            "a new settled pass"
7656        );
7657    }
7658
7659    #[test]
7660    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7661        for source in ["cli", "web"] {
7662            let mut t = task();
7663            let mut run = run_state(RunStatus::Blocked);
7664            run.instruction = "Run A original criteria".into();
7665            run.task_instruction = Some(run.instruction.clone());
7666            t.start(run.id.clone());
7667            t.release_operator("choice", Some("resume-question"));
7668            t.resume_override = Some(crate::queue::OperatorResume {
7669                question_id: "resume-question".into(),
7670                at: Timestamp::now(),
7671                conductor_rehold: None,
7672                forced: true,
7673                pinned_run: Some(run.id.clone()),
7674            });
7675            t.hold_machine(Some("not enough free space to start a run".into()));
7676            let mut unchanged = t.clone();
7677            unchanged
7678                .edit("title changed".into(), unchanged.instruction.clone())
7679                .unwrap();
7680            unchanged.release_operator(source, None);
7681            assert_eq!(
7682                unchanged
7683                    .resume_override
7684                    .as_ref()
7685                    .unwrap()
7686                    .pinned_run
7687                    .as_deref(),
7688                Some(run.id.as_str())
7689            );
7690            assert!(!compatible_run_instruction(&run, &unchanged));
7691            assert!(may_resume_run(&run, &unchanged));
7692
7693            t.edit(
7694                "approved recovery".into(),
7695                "Reuse measured PR head B; fix Clippy; review".into(),
7696            )
7697            .unwrap();
7698            assert!(t.resume_override.is_none());
7699            t.release_operator(source, None);
7700            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7701            assert!(reloaded.resume_override.is_none());
7702            assert!(!may_resume_run(&run, &reloaded));
7703            let unfinished =
7704                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7705                    .filter(|_| may_resume_run(&run, &reloaded));
7706            assert_eq!(
7707                choose_starter(None, false, unfinished.as_deref()),
7708                Starter::Start
7709            );
7710            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7711            assert_eq!(
7712                reloaded.resumption_history[0].question_id.as_deref(),
7713                Some("resume-question")
7714            );
7715
7716            // A revision already persisted with the old approval/pin is also
7717            // invalidated when the new operator release is recorded.
7718            unchanged.instruction = "Reuse measured PR head B".into();
7719            unchanged.hold_machine(Some("disk hold".into()));
7720            unchanged.release_operator(source, None);
7721            assert!(unchanged.resume_override.is_none());
7722            assert!(!may_resume_run(&run, &unchanged));
7723        }
7724    }
7725
7726    #[test]
7727    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7728        let mut t = task();
7729        let mut run = run_state(RunStatus::Blocked);
7730        t.review_of = Some("approved-head".into());
7731        t.instruction =
7732            "Review the branch `approved-head` (review-only: no implementation, no judging)."
7733                .into();
7734        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();
7735        run.reviewed_commits = Some(vec!["Commit log".into()]);
7736        t.start(run.id.clone());
7737        t.hold_machine(Some("interrupted review".into()));
7738        t.release_operator("cli", None);
7739        assert!(
7740            compatible_run_instruction(&run, &t),
7741            "legacy explicit review remains resumable"
7742        );
7743        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7744            .filter(|_| compatible_run_instruction(&run, &t));
7745        assert_eq!(
7746            choose_starter(None, false, unfinished.as_deref()),
7747            Starter::Resume(run.id.clone())
7748        );
7749        run.task_instruction = Some(t.instruction.clone());
7750        assert!(compatible_run_instruction(&run, &t));
7751        let reloaded: RunState =
7752            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7753        assert!(compatible_run_instruction(&reloaded, &t));
7754        t.edit(
7755            "new approved head".into(),
7756            "Reuse measured PR head B".into(),
7757        )
7758        .unwrap();
7759        assert!(!compatible_run_instruction(&run, &t));
7760
7761        // Legacy recovery reviews retain the task criteria ahead of the log.
7762        t.review_of = None;
7763        t.instruction = "Fix Clippy on approved head".into();
7764        run.task_instruction = None;
7765        run.instruction = format!(
7766            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7767            t.instruction
7768        );
7769        assert!(compatible_run_instruction(&run, &t));
7770        t.instruction.push('\n');
7771        assert!(
7772            compatible_run_instruction(&run, &t),
7773            "legacy generated review trimmed the original criteria"
7774        );
7775        t.hold_for_handover(Some("approved-head".into()), "refused".into());
7776        assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
7777        t.edit("new plan".into(), "Reuse measured PR head B".into())
7778            .unwrap();
7779        assert!(review_branch_for(&t, Some(&run)).is_none());
7780        assert!(!compatible_run_instruction(&run, &t));
7781        t.review_branch = Some("approved-head".into());
7782        t.review_instruction = None;
7783        assert!(
7784            review_branch_for(&t, Some(&run)).is_none(),
7785            "legacy retained candidate cannot replace a revised approved head"
7786        );
7787    }
7788
7789    #[test]
7790    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7791        let home = crate::run::test_home();
7792        crate::run::pin_test_home();
7793        let dir = tempfile::tempdir().unwrap();
7794        let queue = Queue::at(dir.path().join("queue"));
7795        for resume in [true, false] {
7796            let state = run_state(RunStatus::Blocked);
7797            let mut t = task();
7798            t.start(state.id.clone());
7799            let action = if resume {
7800                ask::ChoiceAction::Resume {
7801                    run: state.id.clone(),
7802                }
7803            } else {
7804                ask::ChoiceAction::Requeue
7805            };
7806            let mut q = action_question(&state.id, action);
7807            q.status = ask::QuestionStatus::Open;
7808            q.answer = None;
7809            q.answered_at = None;
7810            t.fail("run stopped with a question", 3);
7811            hold_if_runnable(&queue, &mut t);
7812            assert!(t.operator_decided_at.is_none());
7813            assert!(t.operator_held());
7814            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7815            let expected = if resume {
7816                ActionDecision::Resume(state.id.clone())
7817            } else {
7818                ActionDecision::Requeue
7819            };
7820            assert_eq!(
7821                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7822                expected
7823            );
7824            t.hold_manual(Some("later explicit hold".into()));
7825            assert_eq!(
7826                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7827                ActionDecision::Stale
7828            );
7829        }
7830    }
7831
7832    #[test]
7833    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7834        let mut t = task();
7835        t.answers.push(crate::queue::AnsweredQuestion {
7836            question: "Inspect the remote?".into(),
7837            answer: "Inspect then wait".into(),
7838        });
7839        let old = instruction_for(&t);
7840        assert!(compatible_instruction(&old, &t));
7841        t.instruction = "Reuse approved PR head and review".into();
7842        t.release_operator("cli", None);
7843        assert!(!compatible_instruction(&old, &t));
7844        let approved = instruction_for(&t);
7845        assert!(approved.contains("waiting premises are superseded"));
7846        assert!(compatible_instruction(&approved, &t));
7847        assert_eq!(resumed_instruction(&approved, &t), approved);
7848        t.release_operator("web", None);
7849        assert!(compatible_instruction(&approved, &t));
7850        assert_eq!(t.resumption_history.len(), 1);
7851        t.start("run".into());
7852        assert!(instruction_for(&t).contains("Explicit operator resumption"));
7853    }
7854
7855    /// A run that stopped on an infrastructure wait asked no agent anything:
7856    /// the task is held by the machine under a `[resource]` reason (resumable,
7857    /// re-checked by triage), and the attempt it started is given back.
7858    #[test]
7859    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7860        let mut state = RunState::new(
7861            PathBuf::from("/repo"),
7862            "main".into(),
7863            "base".into(),
7864            "task".into(),
7865            Config::default(),
7866        );
7867        state.status = RunStatus::Landing;
7868        state.parked = true;
7869        state.pr_pushed_head = Some("head".into());
7870        state.land_unrelated = Some(
7871            serde_json::from_value(serde_json::json!({
7872                "head": "head", "question": "ci-question",
7873                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7874            }))
7875            .unwrap(),
7876        );
7877        let mut t = task();
7878        t.start(state.id.clone());
7879        let verdict = Verdict {
7880            status: RunStatus::Landing,
7881            left_pr: true,
7882            quota_hit: false,
7883            parked: true,
7884            no_viable_candidates: false,
7885        };
7886        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7887        assert_eq!(t.attempts, 0);
7888        assert_eq!(t.status, TaskStatus::Held);
7889        assert!(!t.operator_held());
7890        assert!(
7891            t.hold_reason
7892                .as_deref()
7893                .unwrap()
7894                .starts_with("[ci-unrelated]")
7895        );
7896        // A second settlement must not refund an earlier task attempt.
7897        t.attempts = 1;
7898        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7899        assert_eq!(t.attempts, 1);
7900        assert_eq!(t.passes.len(), 1);
7901        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7902        state.pr_pushed_head = Some("new-head".into());
7903        state.parked = false;
7904        state.status = RunStatus::Blocked;
7905        let stale = Verdict {
7906            status: RunStatus::Blocked,
7907            parked: false,
7908            ..verdict
7909        };
7910        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7911        assert_eq!(t.attempts, 1);
7912        // A new execution pass can refund its own newly charged attempt.
7913        state.begin_pass();
7914        state.begin_pass();
7915        state.status = RunStatus::Landing;
7916        state.parked = true;
7917        state.pr_pushed_head = Some("head".into());
7918        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7919        assert_eq!(t.attempts, 0);
7920        assert_eq!(t.passes.len(), 2);
7921    }
7922
7923    #[test]
7924    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7925        let mut state = run_state(RunStatus::Failed);
7926        state
7927            .quota
7928            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7929        state.begin_pass();
7930        let mut t = task();
7931        t.start(state.id.clone());
7932        reclaim(&mut t, Some(state), 2, "en");
7933        assert_eq!(t.attempts, 1);
7934    }
7935
7936    #[test]
7937    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7938        let mut state = run_state(RunStatus::Blocked);
7939        let losses: Vec<_> = ["alpha", "beta"]
7940            .into_iter()
7941            .enumerate()
7942            .map(|(i, agent)| {
7943                QuotaLoss::from_report(
7944                    format!("advisor-{i}"),
7945                    "advise",
7946                    Some(&crate::agent::Quota {
7947                        cause: crate::agent::QuotaCause::Authentication,
7948                        agent: agent.to_owned(),
7949                        reset: None,
7950                    }),
7951                )
7952            })
7953            .collect();
7954        crate::graph::block_machine_outage(&mut state, "advise", &losses);
7955        state.quota = losses;
7956        let mut t = task();
7957        t.start(state.id.clone());
7958        let verdict = Verdict {
7959            status: state.status,
7960            left_pr: false,
7961            quota_hit: true,
7962            parked: false,
7963            no_viable_candidates: true,
7964        };
7965        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7966        assert_eq!(t.attempts, 0);
7967        assert_eq!(t.status, TaskStatus::Held);
7968        assert!(!t.operator_held());
7969        let reason = t.hold_reason.as_deref().unwrap();
7970        assert!(reason.starts_with("[authentication]"));
7971        assert!(
7972            reason.contains("alpha")
7973                && reason.contains("beta")
7974                && reason.contains("re-authenticate")
7975        );
7976        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7977        // Orphan recovery uses the same settlement and cannot spend an attempt.
7978        let mut orphan = task();
7979        orphan.start(state.id.clone());
7980        reclaim(&mut orphan, Some(state), 2, "en");
7981        assert_eq!(orphan.attempts, 0);
7982        assert_eq!(orphan.status, TaskStatus::Held);
7983    }
7984
7985    #[test]
7986    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7987        let mut state = RunState::new(
7988            PathBuf::from("/repo"),
7989            "main".to_owned(),
7990            "abc1234".to_owned(),
7991            "task".to_owned(),
7992            Config::default(),
7993        );
7994        state.status = RunStatus::Blocked;
7995        state.resource_block = Some(crate::run::ResourceBlock {
7996            cause: crate::run::ResourceBlockCause::Other,
7997            node: "graft".to_owned(),
7998            kind: "shared build cache".to_owned(),
7999            detail: "timed out".to_owned(),
8000            at: jiff::Timestamp::now(),
8001        });
8002        let mut t = task();
8003        t.start("20260902-000000-aaaa".to_owned());
8004        assert_eq!(t.attempts, 1);
8005        let verdict = Verdict {
8006            status: RunStatus::Blocked,
8007            left_pr: false,
8008            quota_hit: false,
8009            parked: false,
8010            no_viable_candidates: false,
8011        };
8012        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
8013        assert_eq!(t.status, TaskStatus::Held);
8014        assert_eq!(t.attempts, 0, "the attempt is refunded");
8015        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
8016        assert!(
8017            !t.operator_held(),
8018            "a machine hold, released without a human"
8019        );
8020
8021        let mut selected = task();
8022        selected.start("20260902-000000-cccc".into());
8023        selected.replacement = Some(crate::merge_decision::Replacement {
8024            question: "fixture".into(),
8025            run: "earlier".into(),
8026            pr: "https://example.invalid/pr/1".into(),
8027            agent: "selected".into(),
8028            context: "fixture".into(),
8029        });
8030        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
8031        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
8032        assert_eq!(selected.attempts, 0);
8033        assert!(
8034            !selected.operator_held(),
8035            "a selected agent also retains a machine resource hold"
8036        );
8037        assert!(
8038            selected
8039                .hold_reason
8040                .as_deref()
8041                .unwrap()
8042                .starts_with("[resource] ")
8043        );
8044
8045        // A park request outranks it: still the operator's doing.
8046        let mut p = task();
8047        p.start("20260902-000000-bbbb".to_owned());
8048        settle_and_diagnose(
8049            &mut p,
8050            Verdict {
8051                parked: true,
8052                ..verdict
8053            },
8054            "parked",
8055            2,
8056            &state,
8057        );
8058        assert_eq!(p.status, TaskStatus::Parked);
8059        assert_eq!(
8060            p.attempts, 0,
8061            "parking refunds once rather than also settling the resource hold"
8062        );
8063    }
8064
8065    #[test]
8066    fn record_failure_notice_links_the_task() {
8067        let dir = tempfile::tempdir().unwrap();
8068        // A regular file where the queue directory should be makes every
8069        // `put` fail, on every platform and whoever runs the test.
8070        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
8071        let queue = Queue::at(dir.path().join("queue"));
8072        let mut t = interrupt_task("rec-fail-1");
8073        record(&queue, &mut t);
8074
8075        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
8076        assert_eq!(found.len(), 1);
8077        assert_eq!(found[0].key, "loop:record");
8078        assert_eq!(
8079            found[0].link,
8080            Some(Link::Task {
8081                id: "rec-fail-1".to_owned()
8082            })
8083        );
8084    }
8085
8086    /// A runnable task marked to interrupt, with an id fixed for assertions
8087    /// rather than the random one [`Task::new`] mints.
8088    fn interrupt_task(id: &str) -> Task {
8089        let mut t = task();
8090        t.id = id.to_owned();
8091        t.interrupt = true;
8092        t
8093    }
8094
8095    /// An ordinary runnable task with an id fixed for assertions.
8096    fn task_with_id(id: &str) -> Task {
8097        let mut t = task();
8098        t.id = id.to_owned();
8099        t
8100    }
8101
8102    /// A runnable task marked `--urgent`, with an id fixed for assertions.
8103    fn urgent_task(id: &str) -> Task {
8104        let mut t = task();
8105        t.id = id.to_owned();
8106        t.urgent = true;
8107        t
8108    }
8109
8110    #[test]
8111    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
8112        let dir = tempfile::tempdir().unwrap();
8113        let queue = Queue::at(dir.path().join("queue"));
8114        let mut parked = task_with_id("parked");
8115        parked.start("run".into());
8116        parked.park("upgrade");
8117        parked.record_pass_at(
8118            "run",
8119            0,
8120            Some(Timestamp::now()),
8121            1,
8122            Some(crate::run::ParkCause::Upgrade {
8123                from: "old".into(),
8124                to: None,
8125            }),
8126        );
8127        let mut fresh = task_with_id("fresh");
8128        fresh.priority = 100;
8129        let mut urgent_task = urgent_task("urgent");
8130        for t in [&mut parked, &mut fresh, &mut urgent_task] {
8131            queue.put(t).unwrap();
8132        }
8133        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8134        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8135        let candidates = runnable(&queue);
8136        assert_eq!(candidates[0].id, parked.id);
8137        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
8138        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
8139        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
8140        drop(first);
8141        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
8142        let next = runnable(&queue)
8143            .into_iter()
8144            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
8145            .unwrap();
8146        assert_eq!(next.task.id, fresh.id);
8147        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
8148        drop(claimed_elsewhere);
8149        drop(next);
8150        assert!(matches!(
8151            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
8152            Err(SkipReason::CoolingDown)
8153        ));
8154    }
8155
8156    #[test]
8157    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
8158        let dir = tempfile::tempdir().unwrap();
8159        let queue = Queue::at(dir.path().join("queue"));
8160        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8161        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8162        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
8163        let mut first = task();
8164        queue.put(&mut first).unwrap();
8165        let stale_plain = queue.get(&first.id).unwrap();
8166        first.set_urgent(true).unwrap();
8167        queue.put(&mut first).unwrap();
8168        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
8169        let mut second = urgent_task("second");
8170        queue.put(&mut second).unwrap();
8171        assert!(matches!(
8172            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
8173            Err(SkipReason::UrgentCapacity)
8174        ));
8175        drop(queue.claim(&second.id).unwrap());
8176        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
8177        drop(dispatched);
8178        let stale_urgent = queue.get(&first.id).unwrap();
8179        first.set_urgent(false).unwrap();
8180        queue.put(&mut first).unwrap();
8181        assert!(matches!(
8182            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
8183            Err(SkipReason::OrdinaryCapacity)
8184        ));
8185        assert_eq!(urgent.available_permits(), 1);
8186        drop(queue.claim(&first.id).unwrap());
8187        drop(occupied);
8188    }
8189
8190    #[test]
8191    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
8192        let dir = tempfile::tempdir().unwrap();
8193        let queue = Queue::at(dir.path().join("queue"));
8194        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8195        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8196        let mut t = task();
8197        queue.put(&mut t).unwrap();
8198        for enabled in [true, false] {
8199            let stale = queue.get(&t.id).unwrap();
8200            t.set_urgent(enabled).unwrap();
8201            queue.put(&mut t).unwrap();
8202            assert_ne!(stale.urgent, enabled);
8203            let DispatchClaim {
8204                task: fresh,
8205                claim,
8206                permit,
8207            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
8208            assert_eq!(fresh.urgent, enabled);
8209            assert_eq!(ordinary.available_permits(), usize::from(enabled));
8210            assert_eq!(urgent.available_permits(), usize::from(!enabled));
8211            assert!(queue.claim(&t.id).is_err());
8212            assert_eq!(fresh.attempts, stale.attempts);
8213            drop((claim, permit));
8214            assert_eq!(ordinary.available_permits(), 1);
8215            assert_eq!(urgent.available_permits(), 1);
8216        }
8217        t.set_urgent(true).unwrap();
8218        queue.put(&mut t).unwrap();
8219        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
8220        assert!(matches!(
8221            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8222            Err(SkipReason::UrgentCapacity)
8223        ));
8224        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
8225        drop(queue.claim(&t.id).unwrap());
8226        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
8227        drop(occupied);
8228        assert!(matches!(
8229            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
8230            Err(SkipReason::CoolingDown)
8231        ));
8232        drop(queue.claim(&t.id).unwrap());
8233        let held = queue.claim(&t.id).unwrap();
8234        assert!(matches!(
8235            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8236            Err(SkipReason::ClaimUnavailable)
8237        ));
8238        drop(held);
8239        t.status = TaskStatus::Held;
8240        queue.put(&mut t).unwrap();
8241        assert!(matches!(
8242            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8243            Err(SkipReason::NoLongerRunnable)
8244        ));
8245        drop(queue.claim(&t.id).unwrap());
8246        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
8247        assert!(matches!(
8248            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8249            Err(SkipReason::RereadFailed)
8250        ));
8251        drop(queue.claim(&t.id).unwrap());
8252        assert_eq!(urgent.available_permits(), 1);
8253    }
8254
8255    /// The land-resume exemption wins outright, whether or not the candidate
8256    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
8257    /// queue behind anything" guarantee cannot be weaker just because the
8258    /// same task was also filed with `--urgent`.
8259    #[test]
8260    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
8261        assert_eq!(permit_kind(true, false), PermitKind::None);
8262        assert_eq!(permit_kind(true, true), PermitKind::None);
8263    }
8264
8265    /// The one property this whole feature exists for: `--urgent` draws from
8266    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
8267    /// ordinary candidate draws from the ordinary pool exactly as before,
8268    /// untouched by the urgent slot's existence.
8269    #[test]
8270    fn permit_kind_separates_urgent_from_ordinary() {
8271        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
8272        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
8273    }
8274
8275    /// The exact wiring `attempt` runs before minting anything: a config's
8276    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
8277    /// Free space is injected rather than asked of the real disk - the point
8278    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
8279    /// is deterministic on every machine this test runs on, never dependent
8280    /// on how full the CI runner's own disk happens to be.
8281    #[test]
8282    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
8283        let cfg = Config::default();
8284        let repo = Path::new("/any/repo/path");
8285
8286        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
8287            .expect("must hold below the threshold");
8288        assert!(reason.contains("1024"), "{reason}");
8289        assert!(
8290            reason.contains(&cfg.disk.min_free_bytes.to_string()),
8291            "{reason}"
8292        );
8293
8294        assert_eq!(
8295            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
8296            None,
8297            "exactly at the floor is open"
8298        );
8299        assert_eq!(
8300            disk_gate_with(
8301                repo,
8302                &cfg,
8303                PathBuf::new,
8304                |_| Ok(cfg.disk.min_free_bytes + 1)
8305            ),
8306            None,
8307            "comfortably above the floor is open"
8308        );
8309    }
8310
8311    #[test]
8312    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
8313        let dir = tempfile::tempdir().unwrap();
8314        let repo = dir.path().join("repo");
8315        let cache = dir.path().join("cache");
8316        let worktrees = dir.path().join("worktrees");
8317        for path in [&repo, &cache, &worktrees] {
8318            std::fs::create_dir(path).unwrap();
8319        }
8320        let mut cfg = Config::default();
8321        cfg.graph.worktree_root = Some(worktrees.clone());
8322        cfg.verify.gate = vec![format!(
8323            "CARGO_TARGET_DIR='{}' cargo build",
8324            cache.display()
8325        )];
8326        for blocked in [&cache, &worktrees] {
8327            for unmeasured in [false, true] {
8328                assert!(
8329                    disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
8330                        if path == blocked {
8331                            if unmeasured {
8332                                Err(anyhow::anyhow!("measurement failed"))
8333                            } else {
8334                                Ok(0)
8335                            }
8336                        } else {
8337                            Ok(u64::MAX)
8338                        }
8339                    })
8340                    .is_some(),
8341                    "a blocked secondary output volume must close admission"
8342                );
8343            }
8344        }
8345        assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
8346    }
8347
8348    #[test]
8349    fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
8350        let dir = tempfile::tempdir().unwrap();
8351        let repo = dir.path().join("repo");
8352        let cache = dir.path().join("cache");
8353        let home_parent = dir.path().join("run-volume");
8354        let home = home_parent.join("new-home");
8355        for path in [&repo, &cache, &home_parent] {
8356            std::fs::create_dir(path).unwrap();
8357        }
8358        let mut cfg = Config::default();
8359        cfg.graph.worktree_root = Some(repo.clone());
8360        cfg.verify.gate = vec![format!(
8361            "CARGO_TARGET_DIR='{}' cargo build",
8362            cache.display()
8363        )];
8364        cfg.verify.build_cache = BuildCache::Isolated;
8365        let denied = |blocked: &Path| {
8366            disk_gate_with(
8367                &repo,
8368                &cfg,
8369                || home.clone(),
8370                |path| Ok(if path == blocked { 0 } else { u64::MAX }),
8371            )
8372            .is_some()
8373        };
8374        assert!(!denied(&cache));
8375        assert!(denied(&home_parent));
8376    }
8377
8378    #[test]
8379    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
8380        let mut cfg = Config::default();
8381        cfg.disk.min_free_bytes = 0;
8382        let repo = Path::new("/any/repo/path");
8383        assert_eq!(
8384            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
8385            None,
8386            "a zero floor never measures at all"
8387        );
8388    }
8389
8390    #[test]
8391    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
8392        let cfg = Config::default();
8393        let repo = Path::new("/any/repo/path");
8394        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
8395            Err(anyhow::anyhow!("no df on this box"))
8396        })
8397        .expect("a measurement failure must close the gate, not open it");
8398        assert!(reason.contains("could not measure"), "{reason}");
8399    }
8400
8401    #[test]
8402    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
8403        let ordinary = task();
8404        let next = advance_interrupt(
8405            Interrupt::Idle,
8406            std::slice::from_ref(&ordinary.id),
8407            std::slice::from_ref(&ordinary),
8408        );
8409        assert_eq!(next, Interrupt::Idle);
8410    }
8411
8412    #[test]
8413    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
8414        // Nothing to interrupt - this is just an ordinary candidate, and the
8415        // loop's normal dispatch will pick it up like any other.
8416        let marked = interrupt_task("marked");
8417        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8418        assert_eq!(next, Interrupt::Idle);
8419    }
8420
8421    #[test]
8422    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
8423        let marked = interrupt_task("marked");
8424        let next = advance_interrupt(
8425            Interrupt::Idle,
8426            &["running".to_owned()],
8427            std::slice::from_ref(&marked),
8428        );
8429        assert_eq!(
8430            next,
8431            Interrupt::Parking {
8432                parked: vec!["running".to_owned()],
8433                interrupt_task: "marked".to_owned(),
8434            }
8435        );
8436    }
8437
8438    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
8439    /// one run can be in flight when a task becomes runnable and marked.
8440    /// Parking all of them would mean `Resuming` later has more than one id
8441    /// to release back to ordinary dispatch, which cannot be made safe
8442    /// against that same setting's own extra concurrency slots letting two
8443    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
8444    /// The simplification the task's own constraints ask for: do not begin
8445    /// a sequence at all until the herd settles back to exactly one.
8446    #[test]
8447    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
8448        let marked = interrupt_task("marked");
8449
8450        let two = advance_interrupt(
8451            Interrupt::Idle,
8452            &["a".to_owned(), "b".to_owned()],
8453            std::slice::from_ref(&marked),
8454        );
8455        assert_eq!(two, Interrupt::Idle);
8456
8457        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8458        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
8459    }
8460
8461    #[test]
8462    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
8463        let state = Interrupt::Parking {
8464            parked: vec!["running".to_owned()],
8465            interrupt_task: "marked".to_owned(),
8466        };
8467        // Still in flight: no change.
8468        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
8469        assert_eq!(still_going, state);
8470
8471        // Left flight, but the interrupt task has not been dispatched yet on
8472        // this tick - stays `Parking` so `interrupt_gate` can let it through,
8473        // as long as it is still runnable.
8474        let stopped_but_not_yet_dispatched =
8475            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
8476        assert_eq!(stopped_but_not_yet_dispatched, state);
8477
8478        // Left flight, and the interrupt task is now in flight itself.
8479        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
8480        assert_eq!(
8481            dispatched,
8482            Interrupt::Running {
8483                parked: vec!["running".to_owned()],
8484                interrupt_task: "marked".to_owned(),
8485            }
8486        );
8487    }
8488
8489    #[test]
8490    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
8491        let state = Interrupt::Running {
8492            parked: vec!["running".to_owned()],
8493            interrupt_task: "marked".to_owned(),
8494        };
8495        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
8496        assert_eq!(still_running, state);
8497
8498        // Whatever it ended as - merged, failed, held - is not this
8499        // function's concern: leaving flight is the only trigger, driven
8500        // straight off the same in-flight list `poll` already reaps. It does
8501        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
8502        // why that would let an unrelated task start ahead of, or alongside,
8503        // the guaranteed resume.
8504        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
8505        assert_eq!(
8506            ended,
8507            Interrupt::Resuming {
8508                parked: vec!["running".to_owned()]
8509            }
8510        );
8511    }
8512
8513    #[test]
8514    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
8515        let state = Interrupt::Resuming {
8516            parked: vec!["running".to_owned()],
8517        };
8518        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
8519        assert_eq!(still_waiting, state);
8520
8521        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
8522        assert_eq!(dispatched, Interrupt::Idle);
8523    }
8524
8525    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
8526    /// or otherwise moved on by an operator with no claim standing in the
8527    /// way - must not wedge the sequence (and so the whole loop's dispatch,
8528    /// via `interrupt_gate`) waiting forever for a dispatch that can never
8529    /// come. The parked run still gets its resume.
8530    #[test]
8531    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
8532    {
8533        let state = Interrupt::Parking {
8534            parked: vec!["running".to_owned()],
8535            interrupt_task: "marked".to_owned(),
8536        };
8537        // `marked` has been held/blocked/deleted since the sequence began:
8538        // it no longer appears in `runnable` at all.
8539        let next = advance_interrupt(state, &[], &[]);
8540        assert_eq!(
8541            next,
8542            Interrupt::Resuming {
8543                parked: vec!["running".to_owned()]
8544            },
8545            "abandoning the interrupt must not abandon the resume it owes"
8546        );
8547    }
8548
8549    /// The same abandonment, one step later: `Resuming` itself must not wait
8550    /// forever for a parked task that has since become unrunnable.
8551    #[test]
8552    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
8553        let state = Interrupt::Resuming {
8554            parked: vec!["running".to_owned()],
8555        };
8556        let next = advance_interrupt(state, &[], &[]);
8557        assert_eq!(
8558            next,
8559            Interrupt::Idle,
8560            "nothing is left to wait for; the loop must not stay wedged"
8561        );
8562    }
8563
8564    #[test]
8565    fn disabled_by_config_the_sequence_can_never_leave_idle() {
8566        let marked = interrupt_task("marked");
8567        let next = advance_interrupt_tick(
8568            false,
8569            Interrupt::Idle,
8570            &["running".to_owned()],
8571            std::slice::from_ref(&marked),
8572        );
8573        assert_eq!(
8574            next,
8575            Interrupt::Idle,
8576            "an unmarked, unconfigured daemon must behave exactly as before"
8577        );
8578    }
8579
8580    #[test]
8581    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
8582        let state = Interrupt::Parking {
8583            parked: vec!["running".to_owned()],
8584            interrupt_task: "marked".to_owned(),
8585        };
8586        let candidates = vec![interrupt_task("marked"), task()];
8587        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8588        assert!(
8589            allowed.is_empty(),
8590            "nothing may dispatch - not even the interrupt task itself - \
8591             until the parked run has actually stopped"
8592        );
8593    }
8594
8595    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
8596    /// grow a special case for it: an urgent candidate that is not the
8597    /// interrupt task withholds exactly like an ordinary one for as long as
8598    /// the parked run it is racing has not actually left flight. A version
8599    /// of this feature once bypassed the gate for urgent candidates, on the
8600    /// theory that a genuinely separate concurrency lane could not collide
8601    /// with 75dd's own; it could, and did - the bypassed task dispatched
8602    /// alongside a run 75dd's own state machine had only *asked* to park,
8603    /// not yet confirmed gone, which is exactly the second run
8604    /// `Interrupt::Parking`'s own doc says must never happen. There is no
8605    /// tick during Parking/Running/Resuming where letting an extra
8606    /// candidate through is safe, urgent or not - the parked run may still
8607    /// be genuinely mid-call.
8608    #[test]
8609    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
8610        for state in [
8611            Interrupt::Parking {
8612                parked: vec!["running".to_owned()],
8613                interrupt_task: "marked".to_owned(),
8614            },
8615            Interrupt::Running {
8616                parked: vec!["running".to_owned()],
8617                interrupt_task: "marked".to_owned(),
8618            },
8619            Interrupt::Resuming {
8620                parked: vec!["running".to_owned()],
8621            },
8622        ] {
8623            let candidates = vec![
8624                interrupt_task("marked"),
8625                urgent_task("hot"),
8626                task_with_id("ordinary"),
8627            ];
8628            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8629            assert!(
8630                !allowed.iter().any(|t| t.id == "hot"),
8631                "an urgent candidate must wait out the same gate as anything \
8632                 else while the run it would run alongside has not actually \
8633                 left flight, for state {state:?}: {allowed:?}"
8634            );
8635        }
8636    }
8637
8638    /// The one case where marking a task `--urgent` and `interrupt` at once
8639    /// is not redundant: once the interrupt sequence's own guaranteed
8640    /// resume/dispatch actually admits the task, it is unaffected by also
8641    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
8642    /// never on the urgent flag.
8643    #[test]
8644    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
8645        let state = Interrupt::Resuming {
8646            parked: vec!["hot".to_owned()],
8647        };
8648        let candidates = vec![urgent_task("hot"), task()];
8649        let allowed = interrupt_gate(&state, &[], candidates);
8650        assert_eq!(
8651            allowed.iter().filter(|t| t.id == "hot").count(),
8652            1,
8653            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
8654        );
8655    }
8656
8657    #[test]
8658    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
8659        let state = Interrupt::Parking {
8660            parked: vec!["running".to_owned()],
8661            interrupt_task: "marked".to_owned(),
8662        };
8663        let other = task();
8664        let candidates = vec![interrupt_task("marked"), other.clone()];
8665        let allowed = interrupt_gate(&state, &[], candidates);
8666        assert_eq!(allowed.len(), 1);
8667        assert_eq!(allowed[0].id, "marked");
8668    }
8669
8670    #[test]
8671    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
8672        let state = Interrupt::Running {
8673            parked: vec!["running".to_owned()],
8674            interrupt_task: "marked".to_owned(),
8675        };
8676        let candidates = vec![task(), task()];
8677        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
8678        assert!(allowed.is_empty());
8679    }
8680
8681    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
8682    /// sequence began (only reachable above the default
8683    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
8684    /// never both in the same tick, which is what "exactly one resume, no
8685    /// simultaneous run" actually requires structurally rather than by
8686    /// coincidence of how many ordinary slots happen to be free.
8687    #[test]
8688    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
8689        let state = Interrupt::Resuming {
8690            parked: vec!["a".to_owned(), "c".to_owned()],
8691        };
8692        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
8693        let allowed = interrupt_gate(&state, &[], candidates);
8694        assert_eq!(
8695            allowed.len(),
8696            1,
8697            "at most one candidate may be offered while resuming: {allowed:?}"
8698        );
8699        assert_eq!(allowed[0].id, "a");
8700    }
8701
8702    #[test]
8703    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
8704        let state = Interrupt::Resuming {
8705            parked: vec!["a".to_owned()],
8706        };
8707        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
8708        assert!(allowed.is_empty());
8709    }
8710
8711    /// The invariant the completion criteria ask for by name: across a whole
8712    /// simulated sequence, there is never a tick where the gate would let
8713    /// through both the parked run's resume and the interrupt task, and
8714    /// exactly one candidate resumes the instant the interrupt task's run
8715    /// ends - never zero, never more than one.
8716    #[test]
8717    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8718        let running = task(); // id: whatever `Task::new` minted
8719        let marked = interrupt_task("marked");
8720
8721        let mut state = Interrupt::Idle;
8722        // Tick 1: `running` is in flight, `marked` becomes runnable.
8723        let in_flight = vec![running.id.clone()];
8724        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8725        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8726        assert!(gated.is_empty(), "still waiting on `running` to park");
8727
8728        // Tick 2: `running` parked and left flight; nothing dispatched yet.
8729        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8730        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8731        assert_eq!(
8732            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8733            vec!["marked"],
8734            "only the interrupt task may be offered to the dispatcher now"
8735        );
8736
8737        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
8738        state = advance_interrupt_tick(
8739            true,
8740            state,
8741            &["marked".to_owned()],
8742            std::slice::from_ref(&running),
8743        );
8744        let gated = interrupt_gate(
8745            &state,
8746            &["marked".to_owned()],
8747            vec![marked.clone(), running.clone()],
8748        );
8749        assert!(
8750            gated.is_empty(),
8751            "the parked run must not be offered back while the interrupt \
8752             task is still running"
8753        );
8754
8755        // Tick 4: `marked`'s run reached a terminal status and left flight.
8756        // A higher-priority ordinary task `other` is also runnable now - it
8757        // must not be let through instead of, or alongside, `running`.
8758        let other = task_with_id("other");
8759        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8760        assert_eq!(
8761            state,
8762            Interrupt::Resuming {
8763                parked: vec![running.id.clone()]
8764            }
8765        );
8766        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8767        assert_eq!(
8768            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8769            vec![running.id.as_str()],
8770            "exactly the parked run resumes - not the unrelated task, even \
8771             though it was offered first"
8772        );
8773
8774        // Tick 5: `running` is now in flight (dispatched from tick 4's
8775        // gate). Only now does the sequence end and ordinary dispatch fully
8776        // resume.
8777        state = advance_interrupt_tick(
8778            true,
8779            state,
8780            std::slice::from_ref(&running.id),
8781            std::slice::from_ref(&other),
8782        );
8783        assert_eq!(state, Interrupt::Idle);
8784        let gated = interrupt_gate(
8785            &state,
8786            std::slice::from_ref(&running.id),
8787            vec![other.clone()],
8788        );
8789        assert_eq!(
8790            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8791            vec![other.id.as_str()],
8792            "ordinary dispatch is unrestricted again"
8793        );
8794    }
8795
8796    #[test]
8797    fn every_run_status_settles_the_task_it_came_from() {
8798        // run status, resulting task status, attempts still standing after one
8799        let table = [
8800            (RunStatus::Merged, TaskStatus::Done, 1),
8801            (RunStatus::Ready, TaskStatus::Done, 1),
8802            (RunStatus::Stalled, TaskStatus::Failed, 0),
8803            (RunStatus::Blocked, TaskStatus::Failed, 1),
8804            (RunStatus::Failed, TaskStatus::Failed, 1),
8805            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8806            (RunStatus::Prep, TaskStatus::Failed, 1),
8807            (RunStatus::Implementing, TaskStatus::Failed, 1),
8808            (RunStatus::Judging, TaskStatus::Failed, 1),
8809            (RunStatus::Deliberating, TaskStatus::Failed, 1),
8810            (RunStatus::Voting, TaskStatus::Failed, 1),
8811            (RunStatus::Reviewing, TaskStatus::Failed, 1),
8812            (RunStatus::Gating, TaskStatus::Failed, 1),
8813        ];
8814        for (run, want, attempts) in table {
8815            let mut t = task();
8816            t.start("20260902-000000-aaaa".to_owned());
8817            settle(
8818                &mut t,
8819                Verdict {
8820                    status: run,
8821                    left_pr: false,
8822                    parked: false,
8823                    quota_hit: matches!(run, RunStatus::Stalled),
8824                    no_viable_candidates: false,
8825                },
8826                "why",
8827                2,
8828            );
8829            assert_eq!(t.status, want, "task status after {}", label(run));
8830            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8831        }
8832    }
8833
8834    #[test]
8835    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8836        let mut stalled = task();
8837        stalled.start("20260902-000000-aaaa".to_owned());
8838        settle(
8839            &mut stalled,
8840            Verdict {
8841                status: RunStatus::Stalled,
8842                left_pr: false,
8843                parked: false,
8844                quota_hit: true,
8845                no_viable_candidates: false,
8846            },
8847            "quota",
8848            1,
8849        );
8850        assert_eq!(stalled.attempts, 0);
8851        assert!(
8852            stalled.status.runnable(),
8853            "a machine problem must leave the task in line"
8854        );
8855
8856        let mut blocked = task();
8857        blocked.start("20260902-000000-aaaa".to_owned());
8858        settle(
8859            &mut blocked,
8860            Verdict {
8861                status: RunStatus::Blocked,
8862                left_pr: false,
8863                parked: false,
8864                quota_hit: false,
8865                no_viable_candidates: false,
8866            },
8867            "findings open",
8868            1,
8869        );
8870        assert_eq!(blocked.attempts, 1);
8871        assert_eq!(
8872            blocked.status,
8873            TaskStatus::Held,
8874            "the last attempt hands the task to a human"
8875        );
8876    }
8877
8878    #[test]
8879    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8880        // Attempts to spare: without the pull request this task would go
8881        // straight back in line and run the whole competition again.
8882        let mut delivered = task();
8883        delivered.start("20260903-080619-01c2".to_owned());
8884        settle(
8885            &mut delivered,
8886            Verdict {
8887                status: RunStatus::Blocked,
8888                left_pr: true,
8889                parked: false,
8890                quota_hit: false,
8891                no_viable_candidates: false,
8892            },
8893            "no check status",
8894            4,
8895        );
8896        assert_eq!(
8897            delivered.status,
8898            TaskStatus::Held,
8899            "a pull request waiting on CI or a person is not a retryable failure"
8900        );
8901        assert!(
8902            !delivered.status.runnable(),
8903            "the loop must not pick this task up again"
8904        );
8905        assert_eq!(
8906            delivered.last_error.as_deref(),
8907            Some("no check status"),
8908            "the operator needs to be told what the gate was waiting for"
8909        );
8910
8911        // The same status without a pull request is a plain failure, and with
8912        // attempts left it is retried.
8913        let mut empty_handed = task();
8914        empty_handed.start("20260903-080619-01c2".to_owned());
8915        settle(
8916            &mut empty_handed,
8917            Verdict {
8918                status: RunStatus::Blocked,
8919                left_pr: false,
8920                parked: false,
8921                quota_hit: false,
8922                no_viable_candidates: false,
8923            },
8924            "findings open",
8925            4,
8926        );
8927        assert_eq!(empty_handed.status, TaskStatus::Failed);
8928        assert!(empty_handed.status.runnable());
8929    }
8930
8931    #[test]
8932    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8933        // Every candidate agreed, with evidence, that nothing belonged in the
8934        // worktree. That is not a confirmed success to close automatically -
8935        // a human still has to check the claim - and it is not an ordinary
8936        // failure either, so this settles exactly like a pull request nobody
8937        // merged yet: `Held`, same as `Blocked` with a PR.
8938        let mut noop = task();
8939        noop.start("20260912-131304-391f".to_owned());
8940        settle(
8941            &mut noop,
8942            Verdict {
8943                status: RunStatus::VerifiedNoop,
8944                left_pr: false,
8945                parked: false,
8946                quota_hit: false,
8947                no_viable_candidates: true,
8948            },
8949            "candidate A: already fixed by b32cfc4, on main",
8950            4,
8951        );
8952        assert_eq!(
8953            noop.status,
8954            TaskStatus::Held,
8955            "an unverified claim is a request for a human, not a failure"
8956        );
8957        assert!(
8958            !noop.status.runnable(),
8959            "the loop must not requeue this on the same unverified claim"
8960        );
8961        // `Task::release` resets attempts to zero the moment a human looks at
8962        // the evidence and lets it run again, so it does not matter here
8963        // whether the one attempt already spent stays spent - what matters is
8964        // that nothing retries this task unattended in the meantime.
8965        assert_eq!(noop.attempts, 1);
8966    }
8967
8968    #[test]
8969    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8970        // Parking is the operator asking for the process back - to replace the
8971        // binary, most of all. The run's work is intact on disk, so this is
8972        // not a failed attempt, and charging for it would mean a few upgrades
8973        // could exhaust a budget meant for agents that misbehaved.
8974        let mut parked = task();
8975        parked.start("20260903-183634-2d98".to_owned());
8976        settle(
8977            &mut parked,
8978            Verdict {
8979                status: RunStatus::Implementing,
8980                left_pr: false,
8981                quota_hit: false,
8982                parked: true,
8983                no_viable_candidates: false,
8984            },
8985            "parked after `implementing`",
8986            2,
8987        );
8988        assert_eq!(parked.attempts, 0, "a park is refunded");
8989        assert!(
8990            parked.status.runnable(),
8991            "and the task stays in line so the next loop resumes its run"
8992        );
8993        assert_eq!(parked.status, TaskStatus::Parked);
8994        assert_eq!(
8995            parked.park_reason.as_deref(),
8996            Some("parked after `implementing`"),
8997            "the card says where it stopped"
8998        );
8999        assert_eq!(parked.last_error, None, "nothing failed");
9000
9001        // Without the park flag the same non-terminal status is what it always
9002        // was: `execute` returning mid-flight, which is a bug and spends an
9003        // attempt so a task cannot loop on it forever.
9004        let mut broken = task();
9005        broken.start("20260903-183634-2d98".to_owned());
9006        settle(
9007            &mut broken,
9008            Verdict {
9009                status: RunStatus::Implementing,
9010                left_pr: false,
9011                quota_hit: false,
9012                parked: false,
9013                no_viable_candidates: false,
9014            },
9015            "returned mid-flight",
9016            2,
9017        );
9018        assert_eq!(broken.attempts, 1);
9019    }
9020
9021    #[test]
9022    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
9023        // Run e633: quorum lost because two judges answered with the wrong
9024        // JSON shape, `quota: []`. Refunding that takes the bound off the
9025        // retry loop, and each retry pays for a fresh hour-long implement
9026        // wave before it can fail the same way.
9027        let mut flaky = task();
9028        flaky.start("20260903-123023-e633".to_owned());
9029        settle(
9030            &mut flaky,
9031            Verdict {
9032                status: RunStatus::Stalled,
9033                left_pr: false,
9034                parked: false,
9035                quota_hit: false,
9036                no_viable_candidates: false,
9037            },
9038            "verdict rests on 1 of 3 judges",
9039            2,
9040        );
9041        assert_eq!(
9042            flaky.attempts, 1,
9043            "flakiness spends an attempt, so `max_attempts` still bounds it"
9044        );
9045        assert!(flaky.status.runnable(), "and it is still worth retrying");
9046
9047        // The same status, lost to a rate limit, is the machine's fault.
9048        let mut limited = task();
9049        limited.start("20260903-123023-e633".to_owned());
9050        settle(
9051            &mut limited,
9052            Verdict {
9053                status: RunStatus::Stalled,
9054                left_pr: false,
9055                parked: false,
9056                quota_hit: true,
9057                no_viable_candidates: false,
9058            },
9059            "judge-2, judge-3 out of quota",
9060            2,
9061        );
9062        assert_eq!(limited.attempts, 0, "a quota window is refunded");
9063        assert!(limited.status.runnable());
9064
9065        // And the bound really binds: a task that keeps stalling on flakiness
9066        // reaches a human instead of running the roster forever.
9067        let mut worn = task();
9068        for _ in 0..2 {
9069            worn.release();
9070        }
9071        worn.start("20260903-123023-e633".to_owned());
9072        worn.attempts = 2;
9073        settle(
9074            &mut worn,
9075            Verdict {
9076                status: RunStatus::Stalled,
9077                left_pr: false,
9078                parked: false,
9079                quota_hit: false,
9080                no_viable_candidates: false,
9081            },
9082            "no quorum again",
9083            2,
9084        );
9085        assert_eq!(worn.status, TaskStatus::Held);
9086        assert!(!worn.status.runnable());
9087    }
9088
9089    #[test]
9090    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
9091        // The implement wave loses every seat to the same rate limit and
9092        // `after_implement` bails with nothing viable, which surfaces as
9093        // `Failed` rather than `Stalled`. That is the same machine fact the
9094        // `Stalled`-quota row already refunds, and must be refunded the same
9095        // way, or a quota outage quietly holds every task it touches instead
9096        // of leaving them in line for the reset.
9097        let mut wiped_out = task();
9098        wiped_out.start("20260907-025000-a1b2".to_owned());
9099        settle(
9100            &mut wiped_out,
9101            Verdict {
9102                status: RunStatus::Failed,
9103                left_pr: false,
9104                parked: false,
9105                quota_hit: true,
9106                no_viable_candidates: true,
9107            },
9108            "no candidate produced a change; nothing to judge",
9109            2,
9110        );
9111        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
9112        assert!(
9113            wiped_out.status.runnable(),
9114            "a machine problem must leave the task in line"
9115        );
9116
9117        // This is the exemption that must stay narrow: a candidate that did
9118        // produce a change, and then failed for some other reason, still
9119        // spends the attempt even though a seat elsewhere hit its quota.
9120        // Otherwise every ordinary failure that happens to share a run with
9121        // an unrelated rate limit would be refunded for free.
9122        let mut partial_progress = task();
9123        partial_progress.start("20260907-025500-c3d4".to_owned());
9124        settle(
9125            &mut partial_progress,
9126            Verdict {
9127                status: RunStatus::Failed,
9128                left_pr: false,
9129                parked: false,
9130                quota_hit: true,
9131                no_viable_candidates: false,
9132            },
9133            "gate failed on the winning candidate",
9134            2,
9135        );
9136        assert_eq!(
9137            partial_progress.attempts, 1,
9138            "a candidate that actually produced a change spends the attempt \
9139             even though some other seat hit its quota"
9140        );
9141        assert!(partial_progress.status.runnable());
9142    }
9143
9144    #[test]
9145    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
9146        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
9147        // disk, and that construction must reach the same conclusion as the
9148        // one `attempt` builds from a live run, or a crash at exactly the
9149        // wrong moment gives a recovered task a different policy than one a
9150        // daemon finished settling itself.
9151        let mut t = task();
9152        t.start("20260907-025000-a1b2".to_owned());
9153        let mut state = run_state(RunStatus::Failed);
9154        state.quota.push(QuotaLoss {
9155            cause: crate::agent::QuotaCause::UsageLimit,
9156            agent: String::new(),
9157            seat: "cand-a".to_owned(),
9158            node: "implement".to_owned(),
9159            at: Timestamp::now(),
9160            reset: None,
9161        });
9162        assert!(
9163            state.viable().is_empty(),
9164            "no candidate was added, so nothing is viable"
9165        );
9166        reclaim(&mut t, Some(state), 2, "en");
9167        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
9168        assert!(t.status.runnable());
9169    }
9170
9171    #[test]
9172    fn a_held_task_is_never_offered_to_the_loop() {
9173        let dir = tempfile::tempdir().unwrap();
9174        let queue = Queue::at(dir.path().to_path_buf());
9175        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
9176            let mut t = task();
9177            t.id = format!("2026090{n}-000000-000{n}");
9178            t.priority = priority;
9179            queue.put(&mut t).unwrap();
9180        }
9181        let mut held = task();
9182        held.id = "20260909-000000-9999".to_owned();
9183        held.priority = 99;
9184        held.hold_machine(None);
9185        queue.put(&mut held).unwrap();
9186
9187        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
9188        assert_eq!(order.len(), 3);
9189        assert!(!order.contains(&held.id));
9190        assert_eq!(
9191            order.first().cloned(),
9192            queue.next_runnable().map(|t| t.id),
9193            "the loop's first candidate is exactly what the queue offers"
9194        );
9195        assert_eq!(
9196            order,
9197            vec![
9198                "20260902-000000-0002".to_owned(),
9199                "20260903-000000-0003".to_owned(),
9200                "20260901-000000-0001".to_owned(),
9201            ],
9202            "priority first, then oldest, so nothing starves"
9203        );
9204    }
9205
9206    #[test]
9207    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
9208        let dir = tempfile::tempdir().unwrap();
9209        let queue = Queue::at(dir.path().to_path_buf());
9210        let mut old = task();
9211        old.id = "20260101-000000-old0".to_owned();
9212        queue.put(&mut old).unwrap();
9213        let mut fresh = task();
9214        fresh.id = "20260101-000000-new0".to_owned();
9215        queue.put(&mut fresh).unwrap();
9216
9217        // No parseable pid at all, so age is the only signal there is to
9218        // check - unlike a real `Queue::claim`, which always names a real,
9219        // and therefore alive, pid this test cannot fake as dead.
9220        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
9221        std::thread::sleep(Duration::from_millis(60));
9222        let live = queue.claim(&fresh.id).unwrap();
9223
9224        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9225        assert_eq!(swept, vec![old.id.clone()]);
9226        assert!(
9227            queue.claim(&old.id).is_ok(),
9228            "an unparseable lock older than the threshold is swept"
9229        );
9230        assert!(
9231            queue.claim(&fresh.id).is_err(),
9232            "a live pid protects its lock regardless of age"
9233        );
9234        drop(live);
9235    }
9236
9237    #[test]
9238    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
9239        // A live worker's claim remains authoritative even beyond the sweep's
9240        // age limit. Sweeping it would permit a second competing attempt.
9241        let dir = tempfile::tempdir().unwrap();
9242        let queue = Queue::at(dir.path().to_path_buf());
9243        let mut t = task();
9244        t.id = "20260101-000000-live".to_owned();
9245        queue.put(&mut t).unwrap();
9246
9247        let claim = queue.claim(&t.id).unwrap();
9248        std::thread::sleep(Duration::from_millis(60));
9249
9250        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9251        assert!(
9252            swept.is_empty(),
9253            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
9254        );
9255        assert!(
9256            queue.claim(&t.id).is_err(),
9257            "the lock still protects its task"
9258        );
9259        drop(claim);
9260    }
9261
9262    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
9263    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
9264    fn injected_dead_pid() -> u32 {
9265        std::process::id().checked_add(1).unwrap_or(1)
9266    }
9267
9268    #[test]
9269    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
9270        let dir = tempfile::tempdir().unwrap();
9271        let queue = Queue::at(dir.path().to_path_buf());
9272        let mut t = task();
9273        t.id = "20260101-000000-dead".to_owned();
9274        queue.put(&mut t).unwrap();
9275        let dead_pid = injected_dead_pid();
9276
9277        // Written directly rather than through `Queue::claim`, which would
9278        // stamp this test process's own very much alive pid and defeat the
9279        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
9280        // like moments after it died, not six hours later.
9281        std::fs::write(
9282            dir.path().join(format!("{}.lock", t.id)),
9283            dead_pid.to_string(),
9284        )
9285        .unwrap();
9286
9287        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9288            pid != dead_pid
9289        });
9290        assert_eq!(
9291            swept,
9292            vec![t.id.clone()],
9293            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
9294        );
9295        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
9296    }
9297
9298    #[test]
9299    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
9300        let dir = tempfile::tempdir().unwrap();
9301        let queue = Queue::at(dir.path().to_path_buf());
9302        let mut t = task();
9303        t.id = "20260101-000000-late".to_owned();
9304        queue.put(&mut t).unwrap();
9305        let dead_pid = injected_dead_pid();
9306
9307        // Tick one, standing in for the sweep `poll` already runs at
9308        // startup: nothing to find yet.
9309        assert!(
9310            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
9311            "nothing has claimed the task yet"
9312        );
9313
9314        // A second daemon claims the task and dies before it ever writes
9315        // `running`, well after this loop's own startup sweep already ran.
9316        std::fs::write(
9317            dir.path().join(format!("{}.lock", t.id)),
9318            dead_pid.to_string(),
9319        )
9320        .unwrap();
9321
9322        // Tick two, standing in for a poll long into this daemon's uptime:
9323        // the same function, called again, notices what only just appeared -
9324        // proving the sweep is not a one-shot startup check.
9325        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9326            pid != dead_pid
9327        });
9328        assert_eq!(swept, vec![t.id.clone()]);
9329    }
9330
9331    #[test]
9332    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
9333        // `reclaim_orphaned_running` looks up the task's last run, which
9334        // touches `run::home()`; the first call anywhere in this binary wins,
9335        // so this is a no-op if another test already pinned one, and either
9336        // way the run id below is never written under it.
9337        crate::run::pin_test_home();
9338        let dir = tempfile::tempdir().unwrap();
9339        let queue = Queue::at(dir.path().to_path_buf());
9340        let mut t = task();
9341        t.id = "20260101-000000-crsh".to_owned();
9342        t.status = TaskStatus::Running;
9343        t.attempts = 1;
9344        // No `run.json` behind this id: standing in for a run this test does
9345        // not need to make readable, since the point is the lock, not the
9346        // recovery table `reclaim` already has its own tests for.
9347        t.runs.push("20260904-000000-4043".to_owned());
9348        queue.put(&mut t).unwrap();
9349        let dead_pid = injected_dead_pid();
9350
9351        // The crashed daemon's own claim, naming a pid nothing on the
9352        // machine holds anymore.
9353        std::fs::write(
9354            dir.path().join(format!("{}.lock", t.id)),
9355            dead_pid.to_string(),
9356        )
9357        .unwrap();
9358
9359        // Before the lock is swept the task looks claimed, and
9360        // `reclaim_orphaned_running` must leave it alone - this is exactly
9361        // the bug: a `running` task stranded behind a dead daemon's lock,
9362        // invisible to the claim-as-proof check because the lock outlived
9363        // the process that wrote it.
9364        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
9365        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9366
9367        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9368            pid != dead_pid
9369        });
9370        assert_eq!(swept, vec![t.id.clone()]);
9371
9372        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9373        assert_eq!(reclaimed, vec![t.id.clone()]);
9374        let after = queue.get(&t.id).unwrap();
9375        assert_eq!(
9376            after.status,
9377            TaskStatus::Held,
9378            "no run.json to recover from, so a human is asked"
9379        );
9380        assert_eq!(
9381            after.runs,
9382            vec!["20260904-000000-4043".to_owned()],
9383            "the crashed run's id is kept as evidence, not discarded"
9384        );
9385    }
9386
9387    #[test]
9388    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
9389        let dir = tempfile::tempdir().unwrap();
9390        let queue = Queue::at(dir.path().to_path_buf());
9391        let mut t = task();
9392        t.id = "20260101-000000-unknown".to_owned();
9393        queue.put(&mut t).unwrap();
9394        let dead_pid = injected_dead_pid();
9395        std::fs::write(
9396            dir.path().join(format!("{}.lock", t.id)),
9397            dead_pid.to_string(),
9398        )
9399        .unwrap();
9400
9401        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
9402        assert!(swept.is_empty(), "an unknown pid must keep its lock");
9403        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
9404    }
9405
9406    fn run_state_in(status: RunStatus, language: &str) -> RunState {
9407        let mut s = run_state(status);
9408        s.config.graph.language = language.to_owned();
9409        s
9410    }
9411
9412    fn unstarted_verdict(status: RunStatus) -> Verdict {
9413        Verdict {
9414            status,
9415            left_pr: false,
9416            quota_hit: false,
9417            parked: false,
9418            no_viable_candidates: false,
9419        }
9420    }
9421
9422    #[test]
9423    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
9424        let mut t = task();
9425        t.attempts = 1;
9426        settle_in(
9427            &mut t,
9428            unstarted_verdict(RunStatus::AlreadyInBase),
9429            "already in main",
9430            1,
9431            phrases("en"),
9432            None,
9433        );
9434        assert_eq!(t.status, TaskStatus::Done);
9435        assert_eq!(t.attempts, 0);
9436    }
9437
9438    #[test]
9439    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
9440        let reason = |language: &str| {
9441            let mut t = task();
9442            settle_in(
9443                &mut t,
9444                unstarted_verdict(RunStatus::Judging),
9445                "boom",
9446                1,
9447                phrases(language),
9448                None,
9449            );
9450            t.last_error.or(t.hold_reason).unwrap_or_default()
9451        };
9452        assert!(
9453            reason("en").starts_with("the graph stopped at `"),
9454            "{}",
9455            reason("en")
9456        );
9457        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
9458        assert!(reason("日本語").contains("boom"));
9459        assert_eq!(reason("fr"), reason("en"));
9460    }
9461
9462    #[test]
9463    fn describe_follows_the_run_language_and_keeps_the_run_id() {
9464        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
9465        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
9466        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
9467        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
9468        assert!(ja.contains("[run "), "{ja}");
9469        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
9470        assert!(ended.starts_with("run 終了: "), "{ended}");
9471        let mut de = run_state_in(RunStatus::Failed, "de");
9472        let mut en = run_state_in(RunStatus::Failed, "en");
9473        de.id = "same".to_owned();
9474        en.id = "same".to_owned();
9475        assert_eq!(describe(&de), describe(&en));
9476    }
9477
9478    #[test]
9479    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
9480        use crate::handover::Refused;
9481        let cases = [
9482            Refused::Foreign {
9483                branch: "b".into(),
9484                path: "/w/x".into(),
9485                why: "made by hand".into(),
9486            },
9487            Refused::Unsafe {
9488                branch: "b".into(),
9489                path: "/w/x".into(),
9490                why: "its worktree has uncommitted changes (a.rs)".into(),
9491            },
9492            Refused::ReleaseFailed {
9493                branch: "b".into(),
9494                path: "/w/x".into(),
9495                run: "ab12".into(),
9496            },
9497        ];
9498        for r in &cases {
9499            let en = (phrases("en").handover_refused)(r);
9500            assert_eq!(en, r.to_string());
9501            let ja = (phrases("ja").handover_refused)(r);
9502            assert!(
9503                !ja.contains("is checked out") && !ja.contains("try again"),
9504                "{ja}"
9505            );
9506            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
9507            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
9508                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
9509            }
9510        }
9511        assert!(phrases("en").handover_hint.contains("release the task"));
9512        assert!(phrases("ja").handover_hint.contains("解放"));
9513    }
9514
9515    #[test]
9516    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
9517        let build = |lang: &str| {
9518            let mut s = run_state_in(RunStatus::Blocked, lang);
9519            s.id = "same".to_owned();
9520            s.config.graph.review_rounds = 3;
9521            let mut r = review_round(3);
9522            r.expected = 3;
9523            r.answered = 1;
9524            s.reviews.push(r);
9525            s.event(
9526                "review",
9527                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
9528            );
9529            s
9530        };
9531        let en = describe(&build("en"));
9532        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
9533        let ja = describe(&build("ja"));
9534        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
9535        assert!(!ja.contains("never answered"), "{ja}");
9536        assert!(ja.contains("[run "), "{ja}");
9537
9538        // An incomplete panel whose verification failed is a different stop:
9539        // the real event must survive in ja too.
9540        let mut failed = build("ja");
9541        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
9542            command: "cargo test".to_owned(),
9543            code: Some(1),
9544            output_tail: String::new(),
9545            duration_ms: 0,
9546            resource_blocked: false,
9547            ..Default::default()
9548        });
9549        failed.event("review", "stopped; e2e failed: cargo test");
9550        let ja = describe(&failed);
9551        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
9552        assert!(!ja.contains("席のレビュアー"), "{ja}");
9553    }
9554
9555    #[test]
9556    fn refusals_and_recovery_prose_follow_the_language() {
9557        let home = crate::run::test_home();
9558        let t = held_task_with("r1");
9559        let q = action_question(
9560            "r1",
9561            ask::ChoiceAction::Resume {
9562                run: "r1".to_owned(),
9563            },
9564        );
9565        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
9566            ActionDecision::Refuse(s) => s,
9567            other => panic!("{other:?}"),
9568        };
9569        assert!(refuse(phrases("en")).contains("could not be read: gone"));
9570        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
9571        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
9572
9573        let mut held = task();
9574        reclaim(&mut held, None, 2, "ja");
9575        assert!(held.hold_reason.unwrap().contains("保留にしました"));
9576        let mut held = task();
9577        reclaim(&mut held, None, 2, "xx");
9578        assert!(held.hold_reason.unwrap().contains("held for a human"));
9579    }
9580
9581    fn run_state(status: RunStatus) -> RunState {
9582        let mut state = RunState::new(
9583            PathBuf::from("/repo"),
9584            "main".to_owned(),
9585            "abc1234def".to_owned(),
9586            "add retries".to_owned(),
9587            Config::default(),
9588        );
9589        state.status = status;
9590        state
9591    }
9592
9593    #[test]
9594    fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
9595        crate::run::pin_test_home();
9596        let dir = tempfile::tempdir().unwrap();
9597        let mut state = run_state(RunStatus::Blocked);
9598        state.id = "20260101-000000-audit".into();
9599        state.save_under(dir.path()).unwrap();
9600        let mut t = task();
9601        t.start(state.id.clone());
9602        // The final state is newer than disk, as when a worker settles its
9603        // in-memory outcome or recovery is passed an already loaded run.
9604        state.status = RunStatus::Ready;
9605        settle_and_diagnose(
9606            &mut t,
9607            unstarted_verdict(RunStatus::Ready),
9608            "Verified local delivery",
9609            2,
9610            &state,
9611        );
9612        let completion = t.completion_history.last().unwrap();
9613        assert_eq!(completion.actor, CompletionActor::DaemonSettle);
9614        assert_eq!(completion.prior_status, TaskStatus::Running);
9615        assert_eq!(
9616            completion.reason.as_deref(),
9617            Some("Verified local delivery")
9618        );
9619        let snapshot = completion.run.as_ref().unwrap();
9620        assert_eq!(snapshot.id, state.id);
9621        assert_eq!(snapshot.status, Some(RunStatus::Ready));
9622        assert_eq!(
9623            RunState::load_under(&state.id, dir.path()).unwrap().status,
9624            RunStatus::Blocked,
9625            "settlement records the actual outcome without rewriting run history"
9626        );
9627    }
9628
9629    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
9630        Candidate {
9631            index: 0,
9632            label,
9633            agent: "claude".to_owned(),
9634            branch: format!("magi/x/{label}"),
9635            worktree: PathBuf::from("/repo"),
9636            summary: summary.to_owned(),
9637            stat: String::new(),
9638            files: 0,
9639            commits: usize::from(!empty),
9640            empty,
9641            failed: failed.map(str::to_owned),
9642            verified_noop: None,
9643            duration_ms: 0,
9644            folded: false,
9645        }
9646    }
9647
9648    #[test]
9649    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
9650        let mut state = run_state(RunStatus::Blocked);
9651        state.gate = vec![
9652            CommandOutcome {
9653                command: "cargo make check".to_owned(),
9654                code: Some(0),
9655                output_tail: "ok".to_owned(),
9656                duration_ms: 0,
9657                resource_blocked: false,
9658                ..Default::default()
9659            },
9660            CommandOutcome {
9661                command: "cargo test".to_owned(),
9662                code: Some(101),
9663                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
9664                duration_ms: 0,
9665                resource_blocked: false,
9666                ..Default::default()
9667            },
9668        ];
9669        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
9670        assert!(d.contains("cargo test"), "{d}");
9671        assert!(
9672            !d.contains("cargo make check"),
9673            "a passing check is not a diagnostic: {d}"
9674        );
9675        assert!(d.contains("assertion failed"), "{d}");
9676    }
9677
9678    #[test]
9679    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
9680        let mut state = run_state(RunStatus::Blocked);
9681        state.event(
9682            "land",
9683            "stopped: the fixer produced no commit while 2 check(s) were failing \
9684             (build, lint); stopping instead of looping on an unchanged tree",
9685        );
9686        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
9687        assert!(d.contains("build"), "{d}");
9688        assert!(d.contains("lint"), "{d}");
9689        assert!(d.contains("fixer produced no commit"), "{d}");
9690    }
9691
9692    #[test]
9693    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
9694        // `describe`'s output becomes `Task::last_error` verbatim, and the
9695        // phone renders that in the same alarm-styled box an ordinary
9696        // failure gets. A bare `verified_noop` there would read exactly like
9697        // the failure this status exists to be told apart from.
9698        let state = run_state(RunStatus::VerifiedNoop);
9699        let d = describe(&state);
9700        assert!(
9701            d.contains("agent-verified no-op"),
9702            "expected the display label, not the wire spelling: {d}"
9703        );
9704        assert!(!d.contains("verified_noop"), "{d}");
9705    }
9706
9707    #[test]
9708    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
9709        let mut state = run_state(RunStatus::Failed);
9710        state.gate.push(crate::run::CommandOutcome {
9711            command: "cargo test".into(),
9712            code: Some(101),
9713            output_tail: format!(
9714                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
9715                "  41: 0x1234 - backtrace frame\n".repeat(10000)
9716            ),
9717            duration_ms: 1,
9718            resource_blocked: false,
9719            ..Default::default()
9720        });
9721        let d = diagnostic(&state).unwrap();
9722        assert!(d.contains("panicked at widget.rs:12"), "{d}");
9723        assert!(d.contains("assertion failed: widget missing"));
9724        assert!(d.contains("widget log"));
9725    }
9726
9727    #[test]
9728    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
9729        // The whole point of the feature: a run held as "no candidate produced
9730        // a change" can mean the implementer actually finished the task and
9731        // only left a clean local tree behind - see AGENTS.md on this exact
9732        // failure mode. The diagnostic has to carry what the agent actually
9733        // said, not just the fact that nothing was there to judge.
9734        let mut state = run_state(RunStatus::Failed);
9735        state.candidates = vec![candidate(
9736            'A',
9737            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
9738            true,
9739            None,
9740        )];
9741        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
9742        assert!(d.contains("candidate A"), "{d}");
9743        assert!(d.contains("tagged v1.2.3"), "{d}");
9744    }
9745
9746    #[test]
9747    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
9748        let mut state = run_state(RunStatus::Failed);
9749        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
9750        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
9751        assert!(d.contains("candidate A"), "{d}");
9752        assert!(d.contains("agent timed out"), "{d}");
9753    }
9754
9755    #[test]
9756    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9757        // A viable candidate existed, the gate never ran, and nothing land
9758        // said matches - `Task::last_error` is left to explain this one alone.
9759        let mut state = run_state(RunStatus::Failed);
9760        state.candidates = vec![candidate('A', "did the work", false, None)];
9761        assert!(diagnostic(&state).is_none());
9762    }
9763
9764    #[test]
9765    fn diagnostic_is_bounded_however_much_a_run_printed() {
9766        let mut state = run_state(RunStatus::Blocked);
9767        state.gate = vec![
9768            CommandOutcome {
9769                command: "cargo test".to_owned(),
9770                code: Some(101),
9771                output_tail: "x".repeat(50_000),
9772                duration_ms: 0,
9773                resource_blocked: false,
9774                ..Default::default()
9775            },
9776            CommandOutcome {
9777                command: "cargo clippy".to_owned(),
9778                code: Some(1),
9779                output_tail: "y".repeat(50_000),
9780                duration_ms: 0,
9781                resource_blocked: false,
9782                ..Default::default()
9783            },
9784        ];
9785        state.candidates = vec![
9786            candidate('A', &"z".repeat(50_000), true, None),
9787            candidate('B', &"w".repeat(50_000), true, None),
9788        ];
9789        let d = diagnostic(&state).expect("plenty here to diagnose");
9790        assert!(
9791            d.len() <= DIAGNOSTIC_MAX,
9792            "diagnostic grew to {} bytes, unbounded",
9793            d.len()
9794        );
9795    }
9796
9797    #[test]
9798    fn selected_delivery_guards_survive_recovery_failure_accounting() {
9799        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9800            let mut t = task();
9801            let mut state = run_state(status);
9802            t.pr_recovery = Some(crate::pr_recovery::Selection {
9803                url: "url".into(),
9804                branch: format!("magi/task-{}", t.id),
9805                head: "a".repeat(40),
9806                source_head: None,
9807                source_run: None,
9808                source_proof: None,
9809                disposition: Some(crate::pr_recovery::Disposition::Land),
9810                instruction: t.instruction.clone(),
9811                approved_at: Timestamp::now(),
9812            });
9813            state.pr_recovery = t.pr_recovery.clone();
9814            t.start(state.id.clone());
9815            settle_and_diagnose(
9816                &mut t,
9817                Verdict {
9818                    status,
9819                    left_pr: false,
9820                    quota_hit: false,
9821                    parked: false,
9822                    no_viable_candidates: false,
9823                },
9824                "delivery stopped",
9825                5,
9826                &state,
9827            );
9828            assert_eq!(t.status, TaskStatus::Held);
9829            let reason = t.hold_reason.as_deref().unwrap();
9830            if status == RunStatus::Ready {
9831                assert!(reason.contains("Selected PR delivery is incomplete"));
9832                assert!(t.recovery_budget.is_none());
9833            } else {
9834                assert!(reason.contains("Selected recovery stopped"));
9835                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9836            }
9837            assert!(t.pr_recovery.is_some());
9838        }
9839    }
9840
9841    #[test]
9842    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9843        let mut state = run_state(RunStatus::Voting);
9844        state.base_sync = Some(crate::run::BaseSync {
9845            tip: "base-tip".into(),
9846            behind: 3,
9847            attempts: 4,
9848            conflict: Some("base stopped".into()),
9849            already_in: None,
9850        });
9851        state.record_base_sync_stop("candidate-head");
9852        let mut t = task();
9853        t.start(state.id.clone());
9854        let verdict = Verdict {
9855            status: RunStatus::Blocked,
9856            left_pr: false,
9857            quota_hit: false,
9858            parked: false,
9859            no_viable_candidates: false,
9860        };
9861        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9862        assert_eq!(
9863            t.status,
9864            TaskStatus::Held,
9865            "unspent task attempts cannot start another competition"
9866        );
9867        let at = t.held_at;
9868        let cause = t.hold_notice_cause.clone();
9869        state.begin_pass();
9870        t.release_operator("test-resume", None);
9871        t.start(state.id.clone());
9872        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9873        assert_eq!(t.status, TaskStatus::Held);
9874        assert_eq!(t.held_at, at);
9875        assert_eq!(t.hold_notice_cause, cause);
9876    }
9877
9878    #[test]
9879    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9880        let mut state = run_state(RunStatus::Blocked);
9881        state.gate = vec![CommandOutcome {
9882            command: "cargo test".to_owned(),
9883            code: Some(101),
9884            output_tail: "assertion failed".to_owned(),
9885            duration_ms: 0,
9886            resource_blocked: false,
9887            ..Default::default()
9888        }];
9889        let verdict = Verdict {
9890            status: RunStatus::Blocked,
9891            left_pr: false,
9892            quota_hit: false,
9893            parked: false,
9894            no_viable_candidates: false,
9895        };
9896
9897        // Attempt one of two still has a retry coming: no diagnostic yet, the
9898        // task is going to run again and this run's evidence would go stale.
9899        let mut t = task();
9900        t.start("run-1".to_owned());
9901        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9902        assert_eq!(t.status, TaskStatus::Failed);
9903        assert!(t.diagnostic.is_none());
9904
9905        // Attempt two exhausts the budget: now it is held, and the
9906        // diagnostic is what `magi task show` has to say more than one line.
9907        t.start("run-2".to_owned());
9908        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9909        assert_eq!(t.status, TaskStatus::Held);
9910        let d = t.diagnostic.expect("a held task must carry its diagnostic");
9911        assert!(d.contains("cargo test"), "{d}");
9912    }
9913
9914    fn verified_noop_run_state() -> RunState {
9915        let mut state = run_state(RunStatus::VerifiedNoop);
9916        let summary = r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"requested fix already landed","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"commit","target":"b32cfc4","method":"git merge-base --is-ancestor b32cfc4 HEAD","observed":"exit 0; b32cfc4 is on main","passed":true}],"unresolved":[]}"#;
9917        let mut c = candidate('A', summary, true, None);
9918        c.verified_noop = Some(summary.to_owned());
9919        state.candidates = vec![c];
9920        state
9921    }
9922
9923    #[test]
9924    fn a_held_task_names_the_open_question_it_is_waiting_on() {
9925        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
9926        // `magi ask` question settled Held with `hold_reason: null`, so the
9927        // notification said nothing actionable. `note_open_question` should
9928        // append the question id to whatever `handed_off` already wrote.
9929        crate::run::pin_test_home();
9930        let home = crate::run::home();
9931        let state = verified_noop_run_state();
9932        let mut q = ask::Question::new(
9933            state.id.clone(),
9934            "implement".to_owned(),
9935            "impl-A".to_owned(),
9936            "is this really a no-op?".to_owned(),
9937            String::new(),
9938            Vec::new(),
9939        );
9940        Questions::at(home.join("questions")).put(&mut q).unwrap();
9941
9942        let verdict = Verdict {
9943            status: RunStatus::VerifiedNoop,
9944            left_pr: false,
9945            quota_hit: false,
9946            parked: false,
9947            no_viable_candidates: true,
9948        };
9949        let mut t = task();
9950        t.start(state.id.clone());
9951        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9952
9953        assert_eq!(t.status, TaskStatus::Held);
9954        let reason = t.hold_reason.expect("a held task must record why");
9955        assert!(
9956            reason.starts_with("run ended agent-verified no-op"),
9957            "the original settle reason must survive unchanged: {reason}"
9958        );
9959        assert!(
9960            reason.contains(q.short()),
9961            "the open question's id must be named so the notice is actionable: {reason}"
9962        );
9963    }
9964
9965    #[test]
9966    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9967        crate::run::pin_test_home();
9968        let state = verified_noop_run_state();
9969
9970        let verdict = Verdict {
9971            status: RunStatus::VerifiedNoop,
9972            left_pr: false,
9973            quota_hit: false,
9974            parked: false,
9975            no_viable_candidates: true,
9976        };
9977        let mut t = task();
9978        t.start(state.id.clone());
9979        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9980
9981        assert_eq!(t.status, TaskStatus::Held);
9982        assert_eq!(
9983            t.hold_reason.as_deref(),
9984            Some("run ended agent-verified no-op"),
9985            "nothing to append when the question was already answered or never asked"
9986        );
9987    }
9988
9989    #[test]
9990    fn inconsistent_verified_noop_state_settles_and_reclaims_as_ordinary_failure() {
9991        crate::run::pin_test_home();
9992
9993        // Case 1: Saved `VerifiedNoop` run carrying the exact operational
9994        // regression prose instead of valid structured evidence.
9995        let mut bad = run_state(RunStatus::VerifiedNoop);
9996        let mut c = candidate(
9997            'A',
9998            "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.",
9999            true,
10000            None,
10001        );
10002        c.verified_noop = Some("Not established.".to_owned());
10003        bad.candidates = vec![c];
10004
10005        let mut t = task();
10006        t.start(bad.id.clone());
10007        let verdict = Verdict {
10008            status: RunStatus::VerifiedNoop,
10009            left_pr: false,
10010            quota_hit: true,
10011            parked: false,
10012            no_viable_candidates: true,
10013        };
10014        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 3, &bad);
10015        assert_eq!(
10016            t.status,
10017            TaskStatus::Failed,
10018            "inconsistent verified_noop must retry as Failed when attempts remain"
10019        );
10020        assert_eq!(t.attempts, 1);
10021        assert_eq!(
10022            t.last_error.as_deref(),
10023            Some("no-change result lacks verified evidence")
10024        );
10025        assert!(t.hold_reason.is_none());
10026
10027        // Case 2: Reclaim on an inconsistent `VerifiedNoop` state with
10028        // attempts exhausted holds as `failed`, never `verified_noop`, and
10029        // never auto-closes to `Done`.
10030        let mut t_exhausted = task();
10031        t_exhausted.start(bad.id.clone());
10032        reclaim(&mut t_exhausted, Some(bad.clone()), 1, "en");
10033        assert_eq!(t_exhausted.status, TaskStatus::Held);
10034        assert_eq!(t_exhausted.attempts, 1);
10035        assert_eq!(
10036            t_exhausted
10037                .hold_notice_cause
10038                .as_ref()
10039                .map(|c| c.stage.as_str()),
10040            Some("failed"),
10041            "exhausted inconsistent verified_noop must not emit a verified_noop notice cause"
10042        );
10043        let diag = t_exhausted.diagnostic.as_deref().unwrap_or("");
10044        assert!(
10045            !diag.contains("agent-verified no-op"),
10046            "diagnostic must not mislabel an invalid claim as verified no-op: {diag}"
10047        );
10048        assert!(diag.contains("Not established"), "{diag}");
10049    }
10050
10051    #[test]
10052    fn saved_noop_declaration_is_the_evidence_not_the_display_summary() {
10053        let mut state = verified_noop_run_state();
10054        let summary = state.candidates[0].summary.clone();
10055        state.candidates[0].summary = "Already satisfied.".to_owned();
10056        assert!(state.all_candidates_verified_noop());
10057
10058        state.candidates[0].summary = summary;
10059        state.candidates[0].verified_noop = Some("Historical prose only.".to_owned());
10060        assert!(!state.all_candidates_verified_noop());
10061    }
10062
10063    #[test]
10064    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
10065        crate::run::pin_test_home();
10066        let mut first = run_state(RunStatus::Blocked);
10067        first.id = "20260101-000000-sup1".to_owned();
10068        first.save().unwrap();
10069        let mut second = run_state(RunStatus::Merged);
10070        second.id = "20260101-000000-sup2".to_owned();
10071        second.save().unwrap();
10072
10073        let mut t = task();
10074        t.runs = vec![first.id.clone(), second.id.clone()];
10075        t.status = TaskStatus::Done;
10076
10077        supersede_prior_runs(&t, &crate::run::home());
10078
10079        assert_eq!(
10080            RunState::load(&first.id).unwrap().status,
10081            RunStatus::Superseded,
10082            "the first attempt's Blocked no longer needs anyone's attention"
10083        );
10084        assert_eq!(
10085            RunState::load(&second.id).unwrap().status,
10086            RunStatus::Merged,
10087            "the run that actually succeeded is left exactly as it was"
10088        );
10089    }
10090
10091    #[test]
10092    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
10093        // `is_working_on` alone only proves a *daemon* claim; a `magi run
10094        // --resume` invoked by hand outside the daemon never touches
10095        // `daemon.json` at all, so it would look identical to a genuinely
10096        // idle run without also consulting `RunState::liveness`, which reads
10097        // this run's own recorded `driver_pid` instead.
10098        crate::run::pin_test_home();
10099        let mut first = run_state(RunStatus::Blocked);
10100        first.id = "20260101-000000-sup9".to_owned();
10101        // This test process's own pid: guaranteed alive without needing a
10102        // real second process or daemon.
10103        first.driver_pid = Some(std::process::id());
10104        first.driver_started_at = Some(
10105            crate::proc::process_started_at(std::process::id())
10106                .expect("this test process's own start time must be queryable"),
10107        );
10108        first.save().unwrap();
10109        let mut second = run_state(RunStatus::Merged);
10110        second.id = "20260101-000000-supa".to_owned();
10111        second.save().unwrap();
10112
10113        let mut t = task();
10114        t.runs = vec![first.id.clone(), second.id.clone()];
10115        t.status = TaskStatus::Done;
10116
10117        supersede_prior_runs(&t, &crate::run::home());
10118
10119        assert_eq!(
10120            RunState::load(&first.id).unwrap().status,
10121            RunStatus::Blocked,
10122            "a live driver_pid means something is still actually working this run, \
10123             even though no daemon claims it - rewriting under it would just be \
10124             undone the next time that process saves"
10125        );
10126    }
10127
10128    #[test]
10129    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
10130        // The first resweep must skip a still-live attempt exactly like
10131        // `supersede_prior_runs` itself does; a later resweep, once that
10132        // process is no longer actually driving it, is what closes the gap
10133        // `supersede_prior_runs` alone leaves - a task only ever reaches
10134        // `Done` once, so nothing else would ever look at this run again.
10135        let dir = tempfile::tempdir().unwrap();
10136        let home = dir.path().to_path_buf();
10137        let queue = Queue::at(dir.path().join("queue"));
10138
10139        let mut first = run_state(RunStatus::Blocked);
10140        first.id = "20260101-000000-supd".to_owned();
10141        first.driver_pid = Some(std::process::id());
10142        first.driver_started_at = Some(
10143            crate::proc::process_started_at(std::process::id())
10144                .expect("this test process's own start time must be queryable"),
10145        );
10146        first.save_under(&home).unwrap();
10147        let mut second = run_state(RunStatus::Merged);
10148        second.id = "20260101-000000-supe".to_owned();
10149        second.save_under(&home).unwrap();
10150
10151        let mut t = task();
10152        t.runs = vec![first.id.clone(), second.id.clone()];
10153        t.status = TaskStatus::Done;
10154        queue.put(&mut t).unwrap();
10155
10156        resweep_superseded_attempts(&queue, &home);
10157        assert_eq!(
10158            RunState::load_under(&first.id, &home).unwrap().status,
10159            RunStatus::Blocked,
10160            "still live on the first pass, so still untouched"
10161        );
10162
10163        // Stand in for the manual process no longer being the one driving
10164        // this run: same pid (this test process really is still alive), but
10165        // an identity marker that no longer matches it - see
10166        // `RunState::liveness`'s own doc for why a mismatched
10167        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
10168        let mut stale = RunState::load_under(&first.id, &home).unwrap();
10169        stale.driver_started_at = Some("1".to_owned());
10170        stale.save_under(&home).unwrap();
10171
10172        resweep_superseded_attempts(&queue, &home);
10173        assert_eq!(
10174            RunState::load_under(&first.id, &home).unwrap().status,
10175            RunStatus::Superseded,
10176            "the second pass catches up what the first one correctly skipped"
10177        );
10178    }
10179
10180    #[test]
10181    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
10182        crate::run::pin_test_home();
10183        let mut first = run_state(RunStatus::Blocked);
10184        first.id = "20260101-000000-sup3".to_owned();
10185        first.save().unwrap();
10186        let mut second = run_state(RunStatus::Blocked);
10187        second.id = "20260101-000000-sup4".to_owned();
10188        second.save().unwrap();
10189
10190        let mut t = task();
10191        t.runs = vec![first.id.clone(), second.id.clone()];
10192        // Still retrying: nothing about this task's story is settled yet, so
10193        // neither Blocked run may be relabelled, even though a later attempt
10194        // already exists.
10195        t.status = TaskStatus::Failed;
10196
10197        supersede_prior_runs(&t, &crate::run::home());
10198
10199        assert_eq!(
10200            RunState::load(&first.id).unwrap().status,
10201            RunStatus::Blocked
10202        );
10203        assert_eq!(
10204            RunState::load(&second.id).unwrap().status,
10205            RunStatus::Blocked
10206        );
10207    }
10208
10209    #[test]
10210    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
10211        // `magi task done` (or the API's equivalent) can close a task with no
10212        // run of its own ever having succeeded - there is nothing here that
10213        // counts as "the attempt that finished it", so nothing is rewritten.
10214        crate::run::pin_test_home();
10215        let mut first = run_state(RunStatus::Blocked);
10216        first.id = "20260101-000000-sup5".to_owned();
10217        first.save().unwrap();
10218
10219        let mut t = task();
10220        t.runs = vec![first.id.clone()];
10221        t.status = TaskStatus::Done;
10222
10223        supersede_prior_runs(&t, &crate::run::home());
10224
10225        assert_eq!(
10226            RunState::load(&first.id).unwrap().status,
10227            RunStatus::Blocked,
10228            "a single-attempt task has no earlier run to supersede"
10229        );
10230    }
10231
10232    #[test]
10233    fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
10234        for status in [
10235            RunStatus::Blocked,
10236            RunStatus::Stalled,
10237            RunStatus::Failed,
10238            RunStatus::Ready,
10239            RunStatus::Merged,
10240        ] {
10241            let dir = tempfile::tempdir().unwrap();
10242            let home = dir.path();
10243            let mut first = run_state(RunStatus::Blocked);
10244            first.id = "20260101-000000-supb".to_owned();
10245            first.save_under(home).unwrap();
10246            let mut second = run_state(status);
10247            second.id = "20260101-000000-supc".to_owned();
10248            second.save_under(home).unwrap();
10249
10250            let mut t = task();
10251            t.runs = vec![first.id.clone(), second.id.clone()];
10252            t.hold_manual(Some("Unmerged work remains".into()));
10253            let mut context = CompletionContext::new(
10254                CompletionActor::Cli,
10255                Some("Discard the unmerged attempts".into()),
10256                home,
10257                &t,
10258            );
10259            context.discard = true;
10260            t.succeed(context);
10261            assert_eq!(t.completion_history.len(), 1);
10262
10263            supersede_prior_runs(&t, home);
10264
10265            assert_eq!(
10266                RunState::load_under(&first.id, home).unwrap().status,
10267                RunStatus::Blocked,
10268                "an audited manual close is not proof the earlier work landed"
10269            );
10270            assert_eq!(
10271                RunState::load_under(&second.id, home).unwrap().status,
10272                status,
10273                "the latest attempt retains its actual outcome"
10274            );
10275        }
10276    }
10277
10278    #[test]
10279    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
10280        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
10281        // to look" - `Failed` and `VerifiedNoop` are already their own
10282        // terminal answers and must not be relabelled into a third one.
10283        crate::run::pin_test_home();
10284        let mut failed = run_state(RunStatus::Failed);
10285        failed.id = "20260101-000000-sup6".to_owned();
10286        failed.save().unwrap();
10287        let mut noop = run_state(RunStatus::VerifiedNoop);
10288        noop.id = "20260101-000000-sup7".to_owned();
10289        noop.save().unwrap();
10290        let mut winner = run_state(RunStatus::Ready);
10291        winner.id = "20260101-000000-sup8".to_owned();
10292        winner.save().unwrap();
10293
10294        let mut t = task();
10295        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
10296        t.status = TaskStatus::Done;
10297
10298        supersede_prior_runs(&t, &crate::run::home());
10299
10300        assert_eq!(
10301            RunState::load(&failed.id).unwrap().status,
10302            RunStatus::Failed
10303        );
10304        assert_eq!(
10305            RunState::load(&noop.id).unwrap().status,
10306            RunStatus::VerifiedNoop
10307        );
10308    }
10309
10310    fn approval_question(run: &str) -> ask::Question {
10311        ask::Question::new(
10312            run.to_owned(),
10313            land::APPROVAL_NODE.to_owned(),
10314            "land".to_owned(),
10315            "merge?".to_owned(),
10316            String::new(),
10317            vec!["merge".to_owned(), "hold".to_owned()],
10318        )
10319    }
10320
10321    #[test]
10322    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
10323        crate::run::pin_test_home();
10324        let mut state = run_state(RunStatus::Landing);
10325        state.id = "20260101-000000-fre1".to_owned();
10326        state.parked = true;
10327        state.save().unwrap();
10328        ask::Questions::open()
10329            .put(&mut approval_question(&state.id))
10330            .unwrap();
10331
10332        let mut t = task();
10333        t.runs.push(state.id.clone());
10334        assert_eq!(
10335            land_resume_state(&t),
10336            LandResume::StillWaiting,
10337            "nobody has answered and the timeout has not passed"
10338        );
10339    }
10340
10341    #[test]
10342    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
10343        crate::run::pin_test_home();
10344        let mut state = run_state(RunStatus::Gating);
10345        state.id = "20260101-000000-gt01".to_owned();
10346        state.parked = true;
10347        state.config.graph.answer_timeout = 60;
10348        state.github_text = Some(crate::run::GithubTextAsk {
10349            rewrite: None,
10350            fingerprint: "f".into(),
10351            title: true,
10352            body: false,
10353            categories: vec!["title-language".into()],
10354            question: None,
10355            asks: 1,
10356            resolved: false,
10357            chosen_title: None,
10358            choice: None,
10359            publication: None,
10360        });
10361        state.save().unwrap();
10362        let store = ask::Questions::open();
10363        let mut q = ask::Question::new(
10364            state.id.clone(),
10365            crate::github_text::ASK_NODE.to_owned(),
10366            crate::github_text::ASK_SEAT.to_owned(),
10367            "s".into(),
10368            String::new(),
10369            vec!["use fallback".into()],
10370        );
10371        store.put(&mut q).unwrap();
10372        let mut t = task();
10373        t.runs.push(state.id.clone());
10374        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
10375        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10376        store.put(&mut q).unwrap();
10377        assert_eq!(land_resume_state(&t), LandResume::Ready);
10378        assert!(!store.get(&q.id).unwrap().status.open());
10379        // Once decided, a parked run is an ordinary candidate again.
10380        state.github_text.as_mut().unwrap().resolved = true;
10381        state.save().unwrap();
10382        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
10383    }
10384
10385    #[test]
10386    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
10387        // `ask::ask_and_wait`'s own deadline used to retire a question
10388        // nobody answered; land's approval bypasses that wait (see
10389        // `land::approval_gate`), so this is now the only place
10390        // `graph.answer_timeout` is enforced for a land approval at all.
10391        crate::run::pin_test_home();
10392        let mut state = run_state(RunStatus::Landing);
10393        state.id = "20260101-000000-exp1".to_owned();
10394        state.parked = true;
10395        state.config.graph.answer_timeout = 60;
10396        state.save().unwrap();
10397
10398        let store = ask::Questions::open();
10399        let mut q = approval_question(&state.id);
10400        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10401        store.put(&mut q).unwrap();
10402
10403        let mut t = task();
10404        t.runs.push(state.id.clone());
10405        assert_eq!(
10406            land_resume_state(&t),
10407            LandResume::Ready,
10408            "an expired question must not be waited on forever"
10409        );
10410
10411        let after = store.get(&q.id).unwrap();
10412        assert!(
10413            !after.status.open(),
10414            "the question is abandoned, not silently ignored"
10415        );
10416        assert!(
10417            after.resolution().is_none(),
10418            "an abandoned question is not read as a decision"
10419        );
10420    }
10421
10422    #[test]
10423    fn reclaim_settles_a_running_task_against_its_last_run() {
10424        let mut t = task();
10425        t.start("20260904-000000-4043".to_owned());
10426        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
10427        assert_eq!(
10428            t.status,
10429            TaskStatus::Done,
10430            "a run that actually finished must not stay `running` forever"
10431        );
10432    }
10433
10434    #[test]
10435    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
10436        let dir = tempfile::tempdir().unwrap();
10437        let queue = Queue::at(dir.path().join("queue"));
10438        let mut task = task();
10439        let mut run = run_state(RunStatus::Blocked);
10440        run.reserve_under(dir.path()).unwrap();
10441        run.driver_exited = true;
10442        run.save_under(dir.path()).unwrap();
10443        queue.put(&mut task).unwrap();
10444        let stale = task.clone();
10445        task.resume_override = Some(crate::queue::OperatorResume {
10446            question_id: "pending-resume".into(),
10447            at: Timestamp::now(),
10448            conductor_rehold: None,
10449            forced: true,
10450            pinned_run: Some(run.id.clone()),
10451        });
10452        task.start(run.id.clone());
10453        queue.put(&mut task).unwrap();
10454        // Discard every in-memory handoff, as a worker death before execute does.
10455        let mut recovered = queue.get(&task.id).unwrap();
10456        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
10457        reclaim(&mut recovered, Some(disk), 2, "en");
10458        queue.put(&mut recovered).unwrap();
10459        assert!(recovered.resume_override.is_none());
10460        assert_eq!(
10461            recovered.dispatched_resumes.get("pending-resume"),
10462            Some(&run.id)
10463        );
10464        let mut stale = stale;
10465        queue.put(&mut stale).unwrap();
10466        assert_eq!(
10467            stale.dispatched_resumes, recovered.dispatched_resumes,
10468            "a stale task writer cannot erase dispatch ownership"
10469        );
10470        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
10471        assert!(resumed.decision_starts.is_empty());
10472        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
10473        assert!(
10474            resumed.decision_starts.is_empty(),
10475            "handoff is not execution proof"
10476        );
10477        resumed.begin_pass();
10478        resumed.save_under(dir.path()).unwrap();
10479        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
10480        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
10481        disk.carry_dispatched_resumes(&recovered);
10482        disk.begin_pass();
10483        assert_eq!(
10484            disk.decision_starts.get("pending-resume"),
10485            Some(&0),
10486            "later execution must preserve the original pass receipt"
10487        );
10488    }
10489
10490    #[test]
10491    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
10492        let mut t = task();
10493        t.start("20260904-000000-4043".to_owned());
10494        t.last_error = Some("earlier trouble".to_owned());
10495        let mut state = run_state(RunStatus::Judging);
10496        state.parked = true;
10497        reclaim(&mut t, Some(state), 1, "en");
10498        assert_eq!(t.status, TaskStatus::Parked);
10499        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
10500        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10501        assert!(t.park_reason.is_some());
10502        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
10503        assert!(!t.fresh_start);
10504        assert!(t.status.runnable());
10505    }
10506
10507    #[test]
10508    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
10509        let mut t = task();
10510        t.start("20260904-000000-4043".to_owned());
10511        t.last_error = Some("earlier trouble".to_owned());
10512        settle(
10513            &mut t,
10514            Verdict {
10515                status: RunStatus::Judging,
10516                left_pr: false,
10517                quota_hit: false,
10518                parked: true,
10519                no_viable_candidates: false,
10520            },
10521            "parked after `judging`",
10522            1,
10523        );
10524        assert_eq!(t.status, TaskStatus::Parked);
10525        assert_eq!(t.attempts, 0);
10526        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10527        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
10528        assert_eq!(t.schema, crate::queue::SCHEMA);
10529        assert!(
10530            crate::notices::task_held(&t).is_none(),
10531            "a park is not news"
10532        );
10533        t.start("20260904-000000-4043".to_owned());
10534        assert_eq!(t.park_reason, None);
10535    }
10536
10537    #[test]
10538    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
10539        // A blocked run with attempts left goes back to `Failed`, exactly as
10540        // it would from `attempt` itself - `reclaim` must not invent a second
10541        // policy for a task a daemon merely stopped without reporting.
10542        let mut t = task();
10543        t.start("20260904-000000-4043".to_owned());
10544        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
10545        assert_eq!(t.status, TaskStatus::Failed);
10546        assert!(t.status.runnable());
10547    }
10548
10549    #[test]
10550    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
10551        let mut t = task();
10552        t.start("20260904-000000-4043".to_owned());
10553        assert_eq!(t.attempts, 1);
10554        let mut run = run_state(RunStatus::Implementing);
10555        run.id = "20260904-000000-4043".to_owned();
10556        run.begin_pass();
10557        let cause = crate::run::ParkCause::Upgrade {
10558            from: "0.121.0".to_owned(),
10559            to: Some("0.121.1".to_owned()),
10560        };
10561        run.end_pass_parked(cause.clone());
10562        run.parked = true;
10563        let verdict = Verdict {
10564            status: run.status,
10565            left_pr: false,
10566            quota_hit: false,
10567            parked: true,
10568            no_viable_candidates: false,
10569        };
10570        // A crash after the checkpoint but before queue settlement must
10571        // recover exactly the same scheduling evidence and refund.
10572        let mut orphan = t.clone();
10573        reclaim(&mut orphan, Some(run.clone()), 2, "en");
10574        assert_eq!(orphan.status, TaskStatus::Parked);
10575        assert_eq!(orphan.attempts, 0);
10576        assert_eq!(
10577            orphan.upgrade_resume_key(),
10578            Some((run.passes[0].started_at, orphan.id.as_str()))
10579        );
10580        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
10581        assert_eq!(t.attempts, 0);
10582        assert_eq!(t.passes.len(), 1);
10583        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10584        assert_eq!(t.passes[0].parked, Some(cause));
10585        assert_eq!(t.passes[0].pass_index, 0);
10586        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
10587        assert!(t.upgrade_resume_key().is_some());
10588
10589        // A resumed pass that then fails spends its attempt, and the earlier
10590        // pass's entry is untouched.
10591        t.start("20260904-000000-4043".to_owned());
10592        run.begin_pass();
10593        run.status = RunStatus::Failed;
10594        let verdict = Verdict {
10595            status: RunStatus::Failed,
10596            left_pr: false,
10597            quota_hit: false,
10598            parked: false,
10599            no_viable_candidates: false,
10600        };
10601        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
10602        assert_eq!(t.passes.len(), 2);
10603        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10604        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
10605        assert_eq!(t.passes[1].pass_index, 1);
10606        assert_eq!(t.attempts, 1);
10607    }
10608
10609    #[test]
10610    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
10611        let mut t = task();
10612        t.start("20260904-000000-4043".to_owned());
10613        reclaim(&mut t, None, 2, "en");
10614        assert_eq!(t.status, TaskStatus::Held);
10615        assert!(
10616            t.last_error
10617                .as_deref()
10618                .is_some_and(|e| e.contains("running")),
10619            "the operator needs to know why this task was held"
10620        );
10621    }
10622
10623    #[test]
10624    fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
10625        let dir = tempfile::tempdir().unwrap();
10626        let queue = Queue::at(dir.path().to_path_buf());
10627        let mut task = task();
10628        let run = "20261124-000000-dead";
10629        task.link_run(run);
10630        task.attempts = 2;
10631        task.status = TaskStatus::Running;
10632        task.sync_only = Some(crate::base_sync_only::Request {
10633            run: run.into(),
10634            at: Timestamp::now(),
10635        });
10636        queue.put(&mut task).unwrap();
10637        assert_eq!(
10638            reclaim_orphaned_running(&queue, 3, &Default::default()),
10639            vec![task.id.clone()]
10640        );
10641        let saved = queue.get(&task.id).unwrap();
10642        assert_eq!(saved.status, TaskStatus::Held);
10643        assert_eq!(saved.attempts, 2);
10644        assert_eq!(saved.execution_runs(), [run]);
10645        assert!(
10646            saved
10647                .last_error
10648                .unwrap()
10649                .contains("verification was not allowed")
10650        );
10651        assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
10652    }
10653
10654    #[test]
10655    fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
10656        use crate::base_sync_only::{Outcome, Pass, Request};
10657
10658        let mut state = run_state(RunStatus::Blocked);
10659        let mut task = task();
10660        let request = Request {
10661            run: state.id.clone(),
10662            at: Timestamp::now(),
10663        };
10664        task.start(state.id.clone());
10665        task.sync_only = Some(request.clone());
10666        // Dedicated dispatch saves Running with the pre-pass attempt count.
10667        task.attempts = 2;
10668        let mut pass = Pass::new(request, &state);
10669        pass.result = Outcome::AlreadyCurrent;
10670        state.sync_only_passes.push(pass);
10671        state.begin_pass();
10672
10673        reclaim(&mut task, Some(state), 3, "en");
10674
10675        assert_eq!(task.status, TaskStatus::Held);
10676        assert_eq!(task.attempts, 2);
10677        assert!(task.sync_only.is_none());
10678        let detail = task.hold_reason.unwrap();
10679        assert!(detail.contains("HEAD already contains the base"));
10680        assert!(detail.contains("verification was not allowed"));
10681    }
10682
10683    #[test]
10684    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
10685        let dir = tempfile::tempdir().unwrap();
10686        let queue = Queue::at(dir.path().to_path_buf());
10687
10688        // No run recorded, so this never has to touch `RunState::load`.
10689        let mut orphaned = task();
10690        orphaned.id = "20260904-000000-orph".to_owned();
10691        orphaned.status = TaskStatus::Running;
10692        orphaned.attempts = 1;
10693        queue.put(&mut orphaned).unwrap();
10694
10695        let mut alive = task();
10696        alive.id = "20260904-000000-live".to_owned();
10697        alive.status = TaskStatus::Running;
10698        alive.attempts = 1;
10699        queue.put(&mut alive).unwrap();
10700        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
10701
10702        let mut queued = task();
10703        queued.id = "20260904-000000-wait".to_owned();
10704        queue.put(&mut queued).unwrap();
10705
10706        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10707        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
10708
10709        assert_eq!(
10710            queue.get(&orphaned.id).unwrap().status,
10711            TaskStatus::Held,
10712            "nothing was driving it and there was no run to recover"
10713        );
10714        assert_eq!(
10715            queue.get(&alive.id).unwrap().status,
10716            TaskStatus::Running,
10717            "a live claim must protect the task it belongs to"
10718        );
10719        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
10720    }
10721
10722    /// Read a run.json back from an explicit `home`, the same way
10723    /// `reclaim_abandoned_runs` itself does - never through the
10724    /// process-global `RunState::load`, which this test's own `home` (an
10725    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
10726    /// use at all.
10727    fn read_run_under(home: &Path, id: &str) -> RunState {
10728        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10729        serde_json::from_str(&body).unwrap()
10730    }
10731
10732    #[test]
10733    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
10734        let dir = tempfile::tempdir().unwrap();
10735        let home = dir.path().to_path_buf();
10736        let now = Timestamp::now();
10737        let overrun_seat = || crate::run::ActiveSeat {
10738            node: "implement".to_owned(),
10739            started_at: now - jiff::SignedDuration::new(21_000, 0),
10740            timeout_secs: 3_600,
10741            attempt: 0,
10742            task: None,
10743            command: None,
10744            index: None,
10745            total: None,
10746        };
10747
10748        let mut dead = run_state(RunStatus::Implementing);
10749        dead.id = "20260101-000000-dead".to_owned();
10750        dead.active.insert("impl-A".to_owned(), overrun_seat());
10751        // A `driver_pid` the injected query below confirms gone outright —
10752        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
10753        dead.driver_pid = Some(4242);
10754        dead.save_under(&home).unwrap();
10755
10756        // Same shape, but a live daemon's heartbeat names it: must be left
10757        // exactly alone, however far past its own timeout the seat sits.
10758        let mut alive = run_state(RunStatus::Implementing);
10759        alive.id = "20260101-000000-aliv".to_owned();
10760        alive.active.insert("impl-A".to_owned(), overrun_seat());
10761        alive.save_under(&home).unwrap();
10762        let mut status = Status::new();
10763        status.current = vec![Current {
10764            worker: None,
10765            task: "20260101-000000-task".to_owned(),
10766            run: alive.id.clone(),
10767        }];
10768        write_status_to(&home.join("daemon.json"), &status).unwrap();
10769
10770        // The abandoned seat left an open question behind: nobody is left to
10771        // read an answer once the run is failed, and this must not wait for
10772        // some later daemon startup's own sweep to notice that.
10773        let questions = Questions::at(home.join("questions"));
10774        let mut q = ask::Question::new(
10775            dead.id.clone(),
10776            "implement".to_owned(),
10777            "impl-A".to_owned(),
10778            "Which storage backend?".to_owned(),
10779            String::new(),
10780            vec!["SQLite".to_owned(), "Redis".to_owned()],
10781        );
10782        questions.put(&mut q).unwrap();
10783
10784        let abandoned = reclaim_abandoned_runs_with(
10785            &home,
10786            now,
10787            |pid| if pid == 4242 { Some(false) } else { None },
10788            |_| panic!("a query answering Dead outright needs no identity corroboration"),
10789        );
10790        assert_eq!(abandoned, vec![dead.id.clone()]);
10791
10792        let reloaded = read_run_under(&home, &dead.id);
10793        assert_eq!(reloaded.status, RunStatus::Failed);
10794        assert!(reloaded.active.is_empty());
10795        assert!(
10796            !questions.get(&q.id).unwrap().status.open(),
10797            "the failed run's own open question must be settled in the same pass"
10798        );
10799
10800        let still_alive = read_run_under(&home, &alive.id);
10801        assert_eq!(
10802            still_alive.status,
10803            RunStatus::Implementing,
10804            "a live daemon's claim protects it"
10805        );
10806        assert!(!still_alive.active.is_empty());
10807    }
10808
10809    /// The exact shape a review round flagged as broken: `magi serve` running
10810    /// in this same `home` scans *every* run on disk, including a manual
10811    /// `magi review` / `magi run` this daemon never started and that
10812    /// therefore claims no heartbeat of its own. Before this scan asked
10813    /// `liveness` rather than just `is_working_on`, a manual run whose active
10814    /// seat merely ran a little past its own timeout — the CLI finishing up,
10815    /// its result still being collected — got wiped and failed by a daemon
10816    /// that had nothing to do with it, out from under a process that was
10817    /// still very much running.
10818    #[test]
10819    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
10820        let dir = tempfile::tempdir().unwrap();
10821        let home = dir.path().to_path_buf();
10822        let now = Timestamp::now();
10823
10824        let mut manual = run_state(RunStatus::Reviewing);
10825        manual.id = "20260101-000000-manl".to_owned();
10826        manual.active.insert(
10827            "review-1".to_owned(),
10828            crate::run::ActiveSeat {
10829                node: "review".to_owned(),
10830                started_at: now - jiff::SignedDuration::new(21_000, 0),
10831                timeout_secs: 3_600,
10832                attempt: 0,
10833                task: None,
10834                command: None,
10835                index: None,
10836                total: None,
10837            },
10838        );
10839        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
10840        // but a real, still-running process: `liveness` must corroborate this
10841        // as `Live`, not read the missing daemon claim as death.
10842        manual.driver_pid = Some(4242);
10843        manual.driver_started_at = Some("1790000000".to_owned());
10844        manual.save_under(&home).unwrap();
10845
10846        let abandoned = reclaim_abandoned_runs_with(
10847            &home,
10848            now,
10849            |pid| if pid == 4242 { Some(true) } else { None },
10850            |pid| {
10851                if pid == 4242 {
10852                    Some("1790000000".to_owned())
10853                } else {
10854                    None
10855                }
10856            },
10857        );
10858        assert!(
10859            abandoned.is_empty(),
10860            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
10861        );
10862
10863        let reloaded = read_run_under(&home, &manual.id);
10864        assert_eq!(reloaded.status, RunStatus::Reviewing);
10865        assert!(!reloaded.active.is_empty());
10866    }
10867
10868    #[test]
10869    fn an_already_claimed_task_is_skipped_rather_than_failed() {
10870        let dir = tempfile::tempdir().unwrap();
10871        let queue = Queue::at(dir.path().to_path_buf());
10872        let mut only = task();
10873        queue.put(&mut only).unwrap();
10874
10875        let _elsewhere = queue.claim(&only.id).unwrap();
10876        let candidates = runnable(&queue);
10877        assert_eq!(candidates.len(), 1, "the task is still runnable");
10878        assert!(
10879            queue.claim(&candidates[0].id).is_err(),
10880            "the loop cannot take a claim somebody else holds"
10881        );
10882
10883        let after = queue.get(&only.id).unwrap();
10884        assert_eq!(after.status, TaskStatus::Queued);
10885        assert_eq!(
10886            after.attempts, 0,
10887            "losing the race is not an attempt at the task"
10888        );
10889        assert_eq!(after.last_error, None);
10890    }
10891
10892    #[test]
10893    fn the_status_file_round_trips_and_its_heartbeat_advances() {
10894        let dir = tempfile::tempdir().unwrap();
10895        let path = dir.path().join("daemon.json");
10896
10897        let mut status = Status::new();
10898        status.idle = false;
10899        status.completed = 7;
10900        status.current = vec![Current {
10901            worker: None,
10902            task: "20260902-000000-t111".to_owned(),
10903            run: "20260902-000001-r111".to_owned(),
10904        }];
10905        write_status_to(&path, &status).unwrap();
10906        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10907        assert_eq!(first.schema, SCHEMA);
10908        assert_eq!(first.pid, std::process::id());
10909        assert!(!first.idle);
10910        assert_eq!(first.completed, 7);
10911        assert_eq!(first.current, status.current);
10912        assert!(
10913            !path.with_extension("json.tmp").exists(),
10914            "the temp file is renamed, not left behind"
10915        );
10916
10917        std::thread::sleep(Duration::from_millis(5));
10918        status.updated_at = Timestamp::now();
10919        status.polls = 3;
10920        write_status_to(&path, &status).unwrap();
10921        let second: Status =
10922            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10923        assert!(
10924            second.updated_at > first.updated_at,
10925            "a reader can only detect staleness if the heartbeat moves"
10926        );
10927        assert_eq!(
10928            second.started_at, first.started_at,
10929            "the start time is not a heartbeat"
10930        );
10931        assert_eq!(second.polls, 3);
10932    }
10933
10934    #[test]
10935    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
10936        let dir = tempfile::tempdir().unwrap();
10937
10938        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
10939
10940        let mut status = Status::new();
10941        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
10942        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10943        let stale = read_status(dir.path()).unwrap();
10944        assert!(
10945            !stale.running(Timestamp::now()),
10946            "a minute without a heartbeat is a dead daemon, not a busy one"
10947        );
10948        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
10949
10950        status.updated_at = Timestamp::now();
10951        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10952        let fresh = read_status(dir.path()).unwrap();
10953        assert!(fresh.running(Timestamp::now()));
10954    }
10955
10956    #[test]
10957    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
10958        let dir = tempfile::tempdir().unwrap();
10959        let now = Timestamp::now();
10960        let mine = "20260903-080619-01c2";
10961
10962        assert!(
10963            !is_working_on(dir.path(), mine, now),
10964            "no status file means nobody is working on anything"
10965        );
10966
10967        let mut status = Status::new();
10968        status.current = vec![Current {
10969            worker: None,
10970            task: "20260903-080340-0167".to_owned(),
10971            run: mine.to_owned(),
10972        }];
10973        status.updated_at = now;
10974        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10975        assert!(is_working_on(dir.path(), mine, now));
10976        assert!(
10977            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
10978            "a daemon busy with one run is not working on another"
10979        );
10980
10981        // A killed daemon stops writing heartbeats but leaves the file behind
10982        // naming the run it died in. That run must not be undeletable forever.
10983        status.updated_at = now - jiff::SignedDuration::from_secs(600);
10984        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10985        assert!(
10986            !is_working_on(dir.path(), mine, now),
10987            "a stale heartbeat is a dead daemon, so its run is a leftover"
10988        );
10989    }
10990
10991    #[test]
10992    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
10993        let dir = tempfile::tempdir().unwrap();
10994        let now = Timestamp::now();
10995
10996        assert!(
10997            !is_working_on_short(dir.path(), "01c2", now),
10998            "no status file means nobody is working on anything"
10999        );
11000
11001        let mut status = Status::new();
11002        status.current = vec![Current {
11003            worker: None,
11004            task: "20260903-080340-0167".to_owned(),
11005            run: "20260903-080619-01c2".to_owned(),
11006        }];
11007        status.updated_at = now;
11008        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11009        assert!(
11010            is_working_on_short(dir.path(), "01c2", now),
11011            "the run's short id is the last block of its full id"
11012        );
11013        assert!(
11014            !is_working_on_short(dir.path(), "3cbf", now),
11015            "a daemon busy with one worktree bay is not working on another"
11016        );
11017    }
11018
11019    #[test]
11020    fn a_newer_status_file_still_yields_a_reading() {
11021        let dir = tempfile::tempdir().unwrap();
11022        // A field this build has never heard of must not turn the reading into
11023        // nothing at all; that is the whole reason the reader is permissive.
11024        std::fs::write(
11025            dir.path().join("daemon.json"),
11026            serde_json::json!({
11027                "schema": 2,
11028                "updated_at": Timestamp::now().to_string(),
11029                "idle": true,
11030                "surprise": { "nested": [1, 2, 3] },
11031            })
11032            .to_string(),
11033        )
11034        .unwrap();
11035
11036        let reading = read_status(dir.path()).expect("a forward-compatible read");
11037        assert!(reading.running(Timestamp::now()));
11038        assert!(reading.idle);
11039        assert!(reading.current.is_empty());
11040    }
11041
11042    #[test]
11043    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
11044        // A daemon started before `current` became a list keeps writing this
11045        // shape on every heartbeat until it is restarted. A rolling upgrade
11046        // - a newer `magi web` or `magi doctor` reading an older `magi
11047        // serve`'s heartbeat - must still see the run it is on, not "no
11048        // daemon" from a type mismatch failing the whole struct.
11049        let dir = tempfile::tempdir().unwrap();
11050        std::fs::write(
11051            dir.path().join("daemon.json"),
11052            serde_json::json!({
11053                "schema": 1,
11054                "pid": 4242,
11055                "updated_at": Timestamp::now().to_string(),
11056                "idle": false,
11057                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
11058                "completed": 3,
11059                "polls": 9,
11060            })
11061            .to_string(),
11062        )
11063        .unwrap();
11064
11065        let reading = read_status(dir.path()).expect("an older shape must still parse");
11066        assert!(reading.running(Timestamp::now()));
11067        assert_eq!(
11068            reading.current,
11069            vec![Current {
11070                worker: None,
11071                task: "20260902-140501-aaaa".to_owned(),
11072                run: "20260902-140502-bbbb".to_owned(),
11073            }]
11074        );
11075    }
11076
11077    #[test]
11078    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
11079        let dir = tempfile::tempdir().unwrap();
11080        std::fs::write(
11081            dir.path().join("daemon.json"),
11082            serde_json::json!({
11083                "schema": 1,
11084                "updated_at": Timestamp::now().to_string(),
11085                "idle": true,
11086                "current": null,
11087            })
11088            .to_string(),
11089        )
11090        .unwrap();
11091        let with_null = read_status(dir.path()).expect("null must still parse");
11092        assert!(with_null.current.is_empty());
11093
11094        std::fs::write(
11095            dir.path().join("daemon.json"),
11096            serde_json::json!({
11097                "schema": 1,
11098                "updated_at": Timestamp::now().to_string(),
11099                "idle": true,
11100            })
11101            .to_string(),
11102        )
11103        .unwrap();
11104        let absent = read_status(dir.path()).expect("a missing field must still parse");
11105        assert!(absent.current.is_empty());
11106    }
11107
11108    #[test]
11109    fn a_task_without_a_repository_runs_in_the_daemons_default() {
11110        let fallback = Path::new("/default");
11111        let mut blank = task();
11112        blank.repo = PathBuf::new();
11113        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
11114        let mut dot = task();
11115        dot.repo = PathBuf::from(".");
11116        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
11117        assert_eq!(
11118            repo_for(&task(), fallback),
11119            PathBuf::from("/repo"),
11120            "a task that names a repository keeps it"
11121        );
11122    }
11123
11124    #[test]
11125    fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
11126        let dir = tempfile::tempdir().unwrap();
11127        let repo = dir.path();
11128        let path = repo.join("explicit.toml");
11129        std::fs::write(
11130            &path,
11131            "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
11132        )
11133        .unwrap();
11134        let opts = Opts {
11135            config: Some(path),
11136            ..Opts::default()
11137        };
11138        let queue = Queue::at(repo.join("queue"));
11139        let mut new = task();
11140        queue.put(&mut new).unwrap();
11141        let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
11142        assert_eq!(
11143            resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
11144            BuildCache::Isolated
11145        );
11146
11147        let mut old = task();
11148        old.schema = 22;
11149        queue.put(&mut old).unwrap();
11150        let mut old = queue.get(&old.id).unwrap();
11151        let config = resolved(&old);
11152        assert_eq!(config.verify.build_cache, BuildCache::Shared);
11153        assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
11154        old.hold_manual(Some("wait".into()));
11155        queue.put(&mut old).unwrap();
11156
11157        let mut saved = queue.get(&old.id).unwrap();
11158        assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
11159        saved
11160            .overrides
11161            .as_mut()
11162            .unwrap()
11163            .merge_over(&crate::queue::RunOverrides {
11164                build_cache: Some(BuildCache::Isolated),
11165                ..Default::default()
11166            });
11167        queue.put(&mut saved).unwrap();
11168        assert_eq!(
11169            resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
11170            BuildCache::Isolated
11171        );
11172    }
11173
11174    #[test]
11175    fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
11176        let dir = tempfile::tempdir().unwrap();
11177        let path = dir.path().join("explicit.toml");
11178        let write = |verify: &str| {
11179            std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
11180        };
11181        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
11182        let opts = Opts {
11183            config: Some(path.clone()),
11184            ..Opts::default()
11185        };
11186        let mut task = task();
11187        task.set_urgent(true).unwrap();
11188        let resolved = |task: &Task| {
11189            prepare_for(dir.path(), &opts, task)
11190                .unwrap()
11191                .verify
11192                .build_cache
11193        };
11194        assert_eq!(resolved(&task), BuildCache::Isolated);
11195        task.change_build_cache(Some(BuildCache::Shared)).unwrap();
11196        assert_eq!(resolved(&task), BuildCache::Shared);
11197        task.change_build_cache(None).unwrap();
11198        assert_eq!(resolved(&task), BuildCache::Isolated);
11199        task.set_urgent(false).unwrap();
11200        assert_eq!(resolved(&task), BuildCache::Shared);
11201
11202        // Urgent work must never be the one stopped by isolation: with no
11203        // shared cache to wait behind, or with a verification command isolated
11204        // mode cannot run, an urgent task keeps the configured mode.
11205        task.set_urgent(true).unwrap();
11206        write("e2e = [\"npm test\"]\n");
11207        assert_eq!(resolved(&task), BuildCache::Shared);
11208        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
11209        assert_eq!(resolved(&task), BuildCache::Shared);
11210        // An explicit choice stays strict and is applied as asked.
11211        task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
11212        assert_eq!(resolved(&task), BuildCache::Isolated);
11213    }
11214
11215    #[test]
11216    fn task_implementers_edit_inherits_daemon_config_and_merge() {
11217        let dir = tempfile::tempdir().unwrap();
11218        let path = dir.path().join("explicit.toml");
11219        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
11220        let opts = Opts {
11221            config: Some(path),
11222            merge: Some("none".into()),
11223            ..Default::default()
11224        };
11225        let mut t = task();
11226        t.set_implementers(
11227            2,
11228            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11229                .unwrap(),
11230        )
11231        .unwrap();
11232        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
11233        assert_eq!(cfg.graph.implementers, 2);
11234        assert_eq!(cfg.graph.judges, 1);
11235        assert_eq!(cfg.merge.mode, MergeMode::None);
11236        t.set_implementers(1, &cfg).unwrap();
11237        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
11238        apply_task_implementers(&mut cfg, &t);
11239        assert_eq!(cfg.graph.implementers, 1);
11240        assert_eq!(cfg.graph.judges, 1);
11241        assert_eq!(cfg.merge.mode, MergeMode::None);
11242    }
11243
11244    #[test]
11245    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
11246        let dir = tempfile::tempdir().unwrap();
11247        let repo = dir.path().join("repo");
11248        std::fs::create_dir(&repo).unwrap();
11249        std::fs::write(
11250            repo.join("magi.toml"),
11251            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
11252        )
11253        .unwrap();
11254        let daemon_config = dir.path().join("daemon.toml");
11255        std::fs::write(
11256            &daemon_config,
11257            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
11258        )
11259        .unwrap();
11260        let opts = Opts {
11261            config: Some(daemon_config),
11262            merge: Some("pr".into()),
11263            ..Default::default()
11264        };
11265        let q = Queue::at(dir.path().join("queue"));
11266        let validation: Config =
11267            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11268                .unwrap();
11269        // No provenance field on legacy direct tasks: both shapes stay isolated.
11270        for record in ["{}", r#"{"candidates":2}"#] {
11271            let overrides = serde_json::from_str(record).unwrap();
11272            let filing = crate::direct::Filing {
11273                instruction: "work".into(),
11274                title: "direct".into(),
11275                repo: repo.clone(),
11276                source: crate::queue::Source::Human,
11277                solo: false,
11278                overrides,
11279                review_of: None,
11280                sources: Default::default(),
11281            };
11282            let filed =
11283                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
11284            let crate::direct::Filed::Standalone {
11285                mut task,
11286                claim: _claim,
11287            } = filed
11288            else {
11289                panic!("local filing")
11290            };
11291            let before = prepare_for(&repo, &opts, &task).unwrap();
11292            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
11293            assert_eq!(
11294                before.merge.mode,
11295                MergeMode::None,
11296                "daemon --merge must not leak"
11297            );
11298            for n in [2, 1, 2] {
11299                task.set_implementers(n, &validation).unwrap();
11300                q.put(&mut task).unwrap();
11301                task = q.get(&task.id).unwrap();
11302                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
11303                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
11304                apply_task_implementers(&mut cfg, &task);
11305                assert_eq!(cfg.graph.implementers, usize::from(n));
11306                assert_eq!(cfg.graph.judges, 2);
11307                assert_eq!(cfg.merge.mode, MergeMode::None);
11308            }
11309        }
11310    }
11311
11312    #[test]
11313    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
11314        let cfg: Config =
11315            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11316                .unwrap();
11317        let mut t = task();
11318        t.review_of = Some("review-target".into());
11319        t.hold_manual(Some("retry".into()));
11320        let mut previous = RunState::new(
11321            PathBuf::from("/repo"),
11322            "main".into(),
11323            "abc1234".into(),
11324            "review".into(),
11325            cfg.clone(),
11326        );
11327        previous.config.graph.implementers = 2;
11328        for count in [1, 3] {
11329            t.set_implementers(count, &cfg).unwrap();
11330            t.release();
11331            assert_eq!(t.review_of.as_deref(), Some("review-target"));
11332            for proposed in [
11333                Starter::Resume(previous.id.clone()),
11334                Starter::Review("recovery-target".into()),
11335            ] {
11336                assert_eq!(
11337                    starter_with_implementers(&t, Some(&previous), proposed),
11338                    Starter::Review("review-target".into())
11339                );
11340            }
11341            let mut configured = cfg.clone();
11342            apply_task_implementers(&mut configured, &t);
11343            assert_eq!(configured.graph.implementers, usize::from(count));
11344            assert_eq!(previous.config.graph.implementers, 2);
11345        }
11346    }
11347
11348    #[test]
11349    fn task_implementers_dispatch_and_resume_agree() {
11350        let mut t = task();
11351        let cfg: crate::config::Config =
11352            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11353                .unwrap();
11354        let mut run = RunState::new(
11355            PathBuf::from("/repo"),
11356            "main".into(),
11357            "abc1234".into(),
11358            "work".into(),
11359            cfg.clone(),
11360        );
11361        run.config.graph.implementers = 2;
11362        for n in [2, 1, 3, 2] {
11363            t.set_implementers(n, &cfg).unwrap();
11364            let mut dispatched = cfg.clone();
11365            apply_task_implementers(&mut dispatched, &t);
11366            assert_eq!(dispatched.graph.implementers, usize::from(n));
11367            assert_eq!(implementers_match(&t, &run), n == 2);
11368            for proposed in [
11369                Starter::Resume(run.id.clone()),
11370                Starter::Review("old-branch".into()),
11371            ] {
11372                let expected = if n == 2 {
11373                    proposed.clone()
11374                } else {
11375                    Starter::Start
11376                };
11377                assert_eq!(
11378                    starter_with_implementers(&t, Some(&run), proposed),
11379                    expected
11380                );
11381            }
11382            assert_eq!(
11383                run.config.graph.implementers, 2,
11384                "history must not be rewritten"
11385            );
11386        }
11387        t.solo = false;
11388        t.overrides = None;
11389        assert!(implementers_match(&t, &run));
11390    }
11391
11392    #[test]
11393    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
11394        // Three seats said out loud. What `solo` promises is one candidate
11395        // *whatever the config asks for*, so the contrast has to be a number
11396        // this test owns - it used to be `Config::default()`'s, which became
11397        // 1 when one implementation became the default and left the two
11398        // halves of this test asserting the same thing.
11399        let mut solo_cfg = Config::default();
11400        solo_cfg.graph.implementers = 3;
11401        let mut solo_task = task();
11402        solo_task.solo = true;
11403        apply_task_implementers(&mut solo_cfg, &solo_task);
11404        assert_eq!(solo_cfg.graph.implementers, 1);
11405
11406        let mut plain_cfg = Config::default();
11407        plain_cfg.graph.implementers = 3;
11408        let plain_task = task();
11409        assert!(!plain_task.solo);
11410        apply_task_implementers(&mut plain_cfg, &plain_task);
11411        assert_eq!(
11412            plain_cfg.graph.implementers, 3,
11413            "a task that did not ask to run alone keeps the config's candidates"
11414        );
11415    }
11416
11417    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
11418        QuotaLoss {
11419            cause: crate::agent::QuotaCause::UsageLimit,
11420            agent: String::new(),
11421            seat: seat.into(),
11422            node: "judge".into(),
11423            at: at.parse().unwrap(),
11424            reset: reset.map(str::to_string),
11425        }
11426    }
11427
11428    #[test]
11429    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
11430        let now = Timestamp::now();
11431        for reset in [None, Some("in 1h")] {
11432            let auth = crate::agent::Quota {
11433                cause: crate::agent::QuotaCause::Authentication,
11434                agent: "alpha".into(),
11435                reset: reset.map(str::to_owned),
11436            };
11437            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
11438            assert_eq!(cooldown_until(&[loss], now), None);
11439        }
11440    }
11441
11442    #[test]
11443    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
11444        let old: Vec<QuotaLoss> = (1..=4)
11445            .map(|i| {
11446                loss(
11447                    &format!("judge-{i}"),
11448                    "2026-09-23T05:23:00Z",
11449                    Some("2:40pm (Asia/Tokyo)"),
11450                )
11451            })
11452            .collect();
11453        let fresh = losses_this_attempt(&old, &old);
11454        assert!(fresh.is_empty());
11455        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
11456        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
11457    }
11458
11459    #[test]
11460    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
11461        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
11462        let now = Timestamp::now();
11463        let mut after = old.clone();
11464        after.push(loss("judge-2", &now.to_string(), None));
11465        let fresh = losses_this_attempt(&old, &after);
11466        assert_eq!(fresh, vec![after[1].clone()]);
11467        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
11468        assert_eq!(
11469            until,
11470            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
11471        );
11472    }
11473
11474    #[test]
11475    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
11476        // `recover_stall` removes judge-1's loss and the retry then hits quota
11477        // again: the vector is the same length, so an index diff sees nothing.
11478        let before = vec![
11479            loss("judge-1", "2026-09-23T05:23:00Z", None),
11480            loss("judge-2", "2026-09-23T05:24:00Z", None),
11481        ];
11482        let after = vec![
11483            loss("judge-2", "2026-09-23T05:24:00Z", None),
11484            loss("judge-1", "2026-09-24T01:00:00Z", None),
11485        ];
11486        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
11487    }
11488
11489    #[test]
11490    fn merge_overrides_are_parsed_or_refused() {
11491        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
11492        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
11493        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
11494        assert!(merge_mode("squash").is_err());
11495    }
11496
11497    #[test]
11498    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
11499        let now = Timestamp::now();
11500        let fallback = Duration::from_secs(300);
11501        let cap = Duration::from_secs(1800);
11502
11503        // No reset hint at all: the fallback.
11504        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
11505
11506        // A reset ten minutes out, well inside the cap: waited for exactly.
11507        let soon = now + jiff::SignedDuration::from_secs(600);
11508        assert_eq!(
11509            quota_wait(Some(soon), now, fallback, cap),
11510            Duration::from_secs(600)
11511        );
11512
11513        // A reset already in the past is not trusted: the fallback, not a
11514        // zero or negative wait that would spin the loop right back around.
11515        let past = now - jiff::SignedDuration::from_secs(60);
11516        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
11517
11518        // A reset further out than the cap is trusted for direction but not
11519        // for magnitude: a parsing slip must not sleep the loop for a day.
11520        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
11521        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
11522    }
11523
11524    #[test]
11525    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
11526        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11527
11528        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
11529        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
11530
11531        // Same clock reading, but it has already gone by today: read as
11532        // tomorrow's, since the CLI would not still be reporting a limit past
11533        // its own stated reset.
11534        let already_past =
11535            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
11536        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
11537
11538        assert!(
11539            parse_reset_hint("session limit reached", now, now).is_none(),
11540            "free text with no recognised shape is not guessed at"
11541        );
11542        assert!(
11543            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
11544            "an unresolvable zone name is not guessed at either"
11545        );
11546    }
11547
11548    #[test]
11549    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
11550        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11551
11552        let at = parse_reset_hint(
11553            "You've hit your usage limit. Visit \
11554             https://chatgpt.com/codex/settings/usage to purchase more \
11555             credits or try again at Sep 19th, 2026 5:10 PM.",
11556            now,
11557            now,
11558        )
11559        .expect("the codex reset wording is a recognised shape");
11560        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
11561
11562        // The month is explicit, so a date already earlier in the same
11563        // sentence-implied year than `now` is trusted as written rather than
11564        // rolled forward a year the way the bracketed shape rolls a
11565        // same-day clock reading to tomorrow.
11566        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
11567            .expect("an explicit year needs no rollover");
11568        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
11569
11570        assert!(
11571            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
11572            "a two-digit year is not the documented shape and is not guessed at"
11573        );
11574        assert!(
11575            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
11576            "a four-letter month name is not the documented three-letter abbreviation"
11577        );
11578        assert!(
11579            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
11580            "an explicit zone on the dated shape is a format nobody has \
11581             documented, and is refused rather than guessed at as UTC"
11582        );
11583    }
11584
11585    #[test]
11586    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
11587        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
11588        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
11589
11590        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
11591        assert_eq!(at.as_second() - recorded.as_second(), 3769);
11592
11593        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
11594        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
11595
11596        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
11597            assert!(
11598                parse_reset_hint(bad, now, recorded).is_none(),
11599                "{bad:?} must not be guessed at"
11600            );
11601        }
11602    }
11603
11604    /// A loop whose queue lives in a temp tree and whose poll interval is far
11605    /// longer than the test's patience, so anything that waits out a poll
11606    /// instead of noticing the stop fails rather than merely being slow.
11607    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
11608        let config = dir.join("magi.toml");
11609        std::fs::write(
11610            &config,
11611            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
11612        )
11613        .unwrap();
11614        let opts = Opts {
11615            poll: Duration::from_secs(30),
11616            config: Some(config),
11617            // The explicit fixture config keeps startup cleanup from reading
11618            // machine configuration. This fictional repository likewise
11619            // keeps any best-effort git cleanup away from this checkout.
11620            repo: dir.join("repo"),
11621            ..Opts::default()
11622        };
11623        // The status file goes in a directory that does not exist yet, so its
11624        // creation is itself evidence the loop published one. `worktrees`
11625        // must be just as fictional: the janitor reclaims worktrees under it
11626        // for real, and a test that let it fall through to
11627        // `crate::run::default_worktree_root()` would have it reclaim
11628        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
11629        // which is exactly what happened before this function took the
11630        // parameter at all.
11631        let home = dir.join("home");
11632        // These control-only fixtures do not launch native workers. Give the
11633        // independently tested maintenance services a fresh cadence receipt.
11634        let stamps = home.join("service-ticks");
11635        std::fs::create_dir_all(&stamps).unwrap();
11636        for service in ["waiter", "deputies", "release-watch"] {
11637            std::fs::write(
11638                stamps.join(service),
11639                Timestamp::now().as_second().to_string(),
11640            )
11641            .unwrap();
11642        }
11643        for operation in [
11644            "conductor",
11645            "maintenance",
11646            "housekeeping",
11647            "disk-pressure",
11648            "cache",
11649            "fetch",
11650            "chat-goals",
11651        ] {
11652            std::fs::write(
11653                stamps.join(format!("daemon-{operation}")),
11654                serde_json::to_vec(&Timestamp::now()).unwrap(),
11655            )
11656            .unwrap();
11657        }
11658        let worktrees = dir.join("wt");
11659        (
11660            opts,
11661            Queue::at(dir.join("queue")),
11662            home.join("daemon.json"),
11663            home,
11664            worktrees,
11665        )
11666    }
11667
11668    #[tokio::test]
11669    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
11670        let dir = tempfile::tempdir().unwrap();
11671        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11672        let mut waiting = task();
11673        waiting.repo = opts.repo.clone();
11674        waiting.hold_machine(crate::disk::gate(1, 100));
11675        waiting.mark_disk_capacity();
11676        waiting.attempts = 2;
11677        queue.put(&mut waiting).unwrap();
11678        let mut busy = task();
11679        busy.status = TaskStatus::Running;
11680        queue.put(&mut busy).unwrap();
11681        let payload = serde_json::to_value(ServiceWorker {
11682            opts,
11683            queue: queue.root().to_owned(),
11684            worktrees_root: worktrees,
11685            operation: "maintenance".into(),
11686        })
11687        .unwrap();
11688        run_service_worker(&home, payload.clone()).await.unwrap();
11689        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
11690        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11691        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
11692        run_service_worker(&home, payload).await.unwrap();
11693        assert!(
11694            crate::worker::active(&home).unwrap().is_empty(),
11695            "monitoring only queues; normal dispatch owns launches"
11696        );
11697        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11698    }
11699
11700    #[tokio::test]
11701    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
11702        let dir = tempfile::tempdir().unwrap();
11703        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11704        let cfg = Config::default();
11705        start_service(
11706            &home,
11707            &opts,
11708            &queue,
11709            &worktrees,
11710            "housekeeping",
11711            Some(&cfg),
11712            true,
11713        )
11714        .await
11715        .unwrap();
11716        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
11717        let read = |path: &Path| -> serde_json::Value {
11718            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
11719        };
11720        assert_eq!(read(&receipt)["detail"], "cadence not due");
11721        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
11722        start_service(
11723            &home,
11724            &opts,
11725            &queue,
11726            &worktrees,
11727            "housekeeping",
11728            Some(&cfg),
11729            true,
11730        )
11731        .await
11732        .unwrap();
11733        assert_eq!(
11734            read(&receipt)["detail"],
11735            "active work or runnable task queue"
11736        );
11737        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
11738        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
11739        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
11740        start_service(
11741            &home,
11742            &opts,
11743            &queue,
11744            &worktrees,
11745            "disk-pressure",
11746            Some(&cfg),
11747            false,
11748        )
11749        .await
11750        .unwrap();
11751        assert_eq!(
11752            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
11753            "no active work; idle housekeeping owns scan"
11754        );
11755        assert!(crate::worker::active(&home).unwrap().is_empty());
11756    }
11757
11758    #[tokio::test]
11759    async fn goal_observation_service_does_not_block_scheduler_decisions() {
11760        let dir = tempfile::tempdir().unwrap();
11761        let (opts, _, _, home, worktrees) = idle_loop(dir.path());
11762        let queue = Queue::at(home.join("queue"));
11763        let mut task = task();
11764        task.repo = opts.repo.clone();
11765        task.chat = Some("decision-chat".into());
11766        task.hold_machine(Some("waiting for a decision".into()));
11767        queue.put(&mut task).unwrap();
11768        let questions = Questions::at(home.join("questions"));
11769        let mut question = action_question(&task.id, ask::ChoiceAction::Done);
11770        question.node = crate::conduct::NODE.into();
11771        question.status = ask::QuestionStatus::Open;
11772        question.answer = None;
11773        question.answered_at = None;
11774        questions.put(&mut question).unwrap();
11775        questions
11776            .update(&question.id, |q| {
11777                q.answer(ask::Answer::Choice("resume で続行する".into()))
11778            })
11779            .unwrap();
11780
11781        let talks = crate::talk::Talks::at(home.join("talks"));
11782        let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
11783        decision_chat.pending = "Keep this unsent status question".into();
11784        talks.put(&mut decision_chat).unwrap();
11785        let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
11786        talk.goals.push(serde_json::from_value(serde_json::json!({
11787            "id":"goal","purpose":"follow the retained job","scope":"one task",
11788            "condition":{"description":"land the result","kind":"runs_merged"},
11789            "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
11790            "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
11791            "started":1,"wakes":1,"last_checked":null,"fingerprint":""
11792        })).unwrap());
11793        talks.put(&mut talk).unwrap();
11794
11795        // A retained service lease models an observation still waiting on its
11796        // external dependency. Admission must neither await nor repeat it.
11797        let directory = home.join("workers/jobs/abcdef");
11798        std::fs::create_dir_all(&directory).unwrap();
11799        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11800        crate::pr_head::try_lock_file(&lease).unwrap();
11801        let mut job = crate::worker::Job {
11802            id: "abcdef".into(),
11803            sequence: 1,
11804            kind: "daemon-service".into(),
11805            key: "service:daemon-chat-goals".into(),
11806            payload: serde_json::Value::Null,
11807            generation: "fixture".into(),
11808            version: None,
11809            status: crate::worker::Status::Running,
11810            result: None,
11811            pid: Some(std::process::id()),
11812            created_at: Timestamp::now().as_second() as u64,
11813            finished_at: None,
11814        };
11815        let record = directory.join("job.json");
11816        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11817        let status = Arc::new(Mutex::new(Status::new()));
11818        let stop = Stop::new();
11819        let mut dispatch = Box::pin(poll(
11820            &opts,
11821            &queue,
11822            &status,
11823            &home,
11824            &worktrees,
11825            &stop,
11826            DispatchLimits {
11827                max_concurrent: 1,
11828                pause_for_interrupts: false,
11829                recovery_cfg: None,
11830            },
11831        ));
11832        std::future::poll_fn(|cx| {
11833            assert!(dispatch.as_mut().poll(cx).is_pending());
11834            std::task::Poll::Ready(())
11835        })
11836        .await;
11837        assert!(lock(&status).polls > 0);
11838        let saved = queue.get(&task.id).unwrap();
11839        assert_eq!(saved.status, TaskStatus::Done);
11840        assert!(saved.action_applied(&question.id));
11841        assert!(
11842            talks
11843                .get("decision-chat")
11844                .unwrap()
11845                .pending
11846                .contains("Keep this unsent status question")
11847        );
11848        let goal = talks.get(&talk.id).unwrap().goals.remove(0);
11849        assert_eq!(goal.state, crate::chat_goal::State::Runnable);
11850        assert_eq!(
11851            goal.started,
11852            Some(1),
11853            "only the observation worker may reconcile its goal"
11854        );
11855        assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
11856
11857        stop.stop();
11858        dispatch.await.unwrap();
11859        job.status = crate::worker::Status::Finished;
11860        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
11861        drop(lease);
11862    }
11863
11864    #[test]
11865    fn a_stop_is_idempotent_and_once_set_stays_set() {
11866        let stop = Stop::new();
11867        assert!(!stop.stopped());
11868
11869        stop.stop();
11870        assert!(stop.stopped());
11871        stop.stop();
11872        assert!(stop.stopped(), "a second stop is not a toggle");
11873
11874        let shared = stop.clone();
11875        assert!(
11876            shared.stopped(),
11877            "a clone is the same stop; that is how the loop and its caller share one"
11878        );
11879    }
11880
11881    #[tokio::test]
11882    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
11883        for operation in ["conductor", "maintenance", "housekeeping"] {
11884            let dir = tempfile::tempdir().unwrap();
11885            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
11886            opts.once = true;
11887            opts.poll = Duration::from_millis(1);
11888            // This test exercises answer scheduling, not explicit discard:
11889            // ordinary Done requires a completed retained execution.
11890            let mut state = run_state(RunStatus::Ready);
11891            state.reserve_under(&home).unwrap();
11892            state.save_under(&home).unwrap();
11893            let mut task = task();
11894            task.runs.push(state.id.clone());
11895            queue.put(&mut task).unwrap();
11896            let claim = queue.claim(&task.id).unwrap();
11897
11898            // Model a live service holding the task's claim across the
11899            // scheduler's dispatch scan. No real subprocess or timed race.
11900            let directory = home.join("workers/jobs/abcdef");
11901            std::fs::create_dir_all(&directory).unwrap();
11902            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11903            crate::pr_head::try_lock_file(&lease).unwrap();
11904            let mut job = crate::worker::Job {
11905                id: "abcdef".into(),
11906                sequence: 1,
11907                kind: "daemon-service".into(),
11908                key: format!("service:daemon-{operation}"),
11909                payload: serde_json::Value::Null,
11910                generation: "fixture".into(),
11911                version: None,
11912                status: crate::worker::Status::Running,
11913                result: None,
11914                pid: Some(std::process::id()),
11915                created_at: Timestamp::now().as_second() as u64,
11916                finished_at: None,
11917            };
11918            let record = directory.join("job.json");
11919            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11920
11921            let status = Arc::new(Mutex::new(Status::new()));
11922            let stop = Stop::new();
11923            let mut drain = Box::pin(poll(
11924                &opts,
11925                &queue,
11926                &status,
11927                &home,
11928                &worktrees,
11929                &stop,
11930                DispatchLimits {
11931                    max_concurrent: 1,
11932                    pause_for_interrupts: false,
11933                    recovery_cfg: None,
11934                },
11935            ));
11936            std::future::poll_fn(|cx| {
11937                use std::future::Future;
11938                assert!(
11939                    drain.as_mut().poll(cx).is_pending(),
11940                    "--once must wait for {operation} to release its queue claim"
11941                );
11942                std::task::Poll::Ready(())
11943            })
11944            .await;
11945            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
11946
11947            // An answer arrives while the service still owns the claim. A
11948            // fresh scheduling pass must apply it before declaring idle.
11949            let questions = Questions::at(home.join("questions"));
11950            let mut q = action_question(&state.id, ask::ChoiceAction::Done);
11951            questions.put(&mut q).unwrap();
11952            drop(claim);
11953            // Model services that took longer than their cadence, without a
11954            // wall-clock sleep. The final scans must not respawn them even
11955            // though their receipts now permit another periodic invocation.
11956            let expired =
11957                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
11958            for service in [operation, "housekeeping"] {
11959                std::fs::write(
11960                    home.join("service-ticks").join(format!("daemon-{service}")),
11961                    &expired,
11962                )
11963                .unwrap();
11964            }
11965            job.status = crate::worker::Status::Finished;
11966            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11967            drop(lease);
11968            tokio::time::timeout(Duration::from_secs(2), drain)
11969                .await
11970                .expect("the settled service must allow the drain to finish")
11971                .unwrap();
11972            let after = queue.get(&task.id).unwrap();
11973            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
11974            assert!(after.action_applied(&q.id));
11975            for service in [operation, "housekeeping"] {
11976                assert_eq!(
11977                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
11978                        .unwrap(),
11979                    expired,
11980                    "the final once rescan must not restart {service}"
11981                );
11982            }
11983        }
11984    }
11985
11986    #[test]
11987    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
11988        let stop = Stop::new();
11989        stop.busy.store(1, Ordering::SeqCst);
11990        assert!(
11991            !stop.finishing(),
11992            "a busy loop nobody has asked to stop is just running"
11993        );
11994
11995        stop.stop();
11996        assert!(
11997            stop.finishing(),
11998            "a stop asked for mid-run has not landed until the run is settled"
11999        );
12000
12001        stop.busy.store(0, Ordering::SeqCst);
12002        assert!(
12003            !stop.finishing(),
12004            "once the run is settled the stop has landed and there is nothing to finish"
12005        );
12006    }
12007
12008    #[test]
12009    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
12010        let stop = Stop::new();
12011        stop.busy.store(2, Ordering::SeqCst);
12012        stop.stop();
12013        assert!(stop.finishing(), "two runs still in flight");
12014
12015        stop.busy.store(1, Ordering::SeqCst);
12016        assert!(
12017            stop.finishing(),
12018            "one run finished, but a sibling is still working"
12019        );
12020
12021        stop.busy.store(0, Ordering::SeqCst);
12022        assert!(
12023            !stop.finishing(),
12024            "the last run out is what actually lands the stop"
12025        );
12026    }
12027
12028    #[tokio::test]
12029    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
12030        let dir = tempfile::tempdir().unwrap();
12031        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
12032        let stop = Stop::new();
12033        stop.stop();
12034
12035        let began = std::time::Instant::now();
12036        tokio::time::timeout(
12037            Duration::from_secs(2),
12038            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
12039        )
12040        .await
12041        .expect("a stopped loop must return, not sit out its poll interval")
12042        .expect("the loop's own setup and teardown must not fail");
12043        assert!(
12044            began.elapsed() < opts.poll,
12045            "returned only after {:?}, which is a poll interval, not a stop",
12046            began.elapsed()
12047        );
12048    }
12049
12050    #[tokio::test]
12051    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
12052        let dir = tempfile::tempdir().unwrap();
12053        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
12054        let stop = Stop::new();
12055
12056        // Asked for after the loop is already parked on its empty queue, which
12057        // is the case an operator tapping stop on a phone actually hits.
12058        let asker = {
12059            let stop = stop.clone();
12060            tokio::spawn(async move {
12061                tokio::time::sleep(Duration::from_millis(20)).await;
12062                stop.stop();
12063            })
12064        };
12065
12066        let began = std::time::Instant::now();
12067        tokio::time::timeout(
12068            Duration::from_secs(2),
12069            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
12070        )
12071        .await
12072        .expect("a stop asked for while idle must wake the wait")
12073        .expect("the loop's own setup and teardown must not fail");
12074        asker.await.unwrap();
12075        assert!(
12076            began.elapsed() < opts.poll,
12077            "returned only after {:?}, so the stop waited on the sleep",
12078            began.elapsed()
12079        );
12080    }
12081
12082    #[tokio::test]
12083    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
12084        let dir = tempfile::tempdir().unwrap();
12085        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
12086        let stop = Stop::new();
12087        stop.stop();
12088
12089        tokio::time::timeout(
12090            Duration::from_secs(2),
12091            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
12092        )
12093        .await
12094        .expect("a stopped loop must return")
12095        .expect("the loop's own setup and teardown must not fail");
12096
12097        assert!(
12098            home.is_dir(),
12099            "the loop did publish a status file, so its removal is the teardown and not an absence"
12100        );
12101        assert!(
12102            !status_file.exists(),
12103            "a stopped loop clears its status file"
12104        );
12105        assert!(
12106            read_status(&home).is_none(),
12107            "a reader must see no daemon at all, not a heartbeat that merely stopped"
12108        );
12109    }
12110
12111    #[tokio::test]
12112    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
12113        let dir = tempfile::tempdir().unwrap();
12114        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12115
12116        let mut settled = RunState::new(
12117            dir.path().join("repo"),
12118            "main".to_owned(),
12119            "abc1234".to_owned(),
12120            "fixture".to_owned(),
12121            Config::default(),
12122        );
12123        settled.status = RunStatus::Ready;
12124        let run_dir = home.join("runs").join(&settled.id);
12125        std::fs::create_dir_all(&run_dir).unwrap();
12126        std::fs::write(
12127            run_dir.join("run.json"),
12128            serde_json::to_string_pretty(&settled).unwrap(),
12129        )
12130        .unwrap();
12131        let questions = Questions::at(home.join("questions"));
12132        let mut question = ask::Question::new(
12133            settled.id.clone(),
12134            "review".to_owned(),
12135            "reviewer-1".to_owned(),
12136            "Continue?".to_owned(),
12137            String::new(),
12138            Vec::new(),
12139        );
12140        questions.put(&mut question).unwrap();
12141
12142        run_service_worker(
12143            &home,
12144            serde_json::to_value(ServiceWorker {
12145                opts,
12146                queue: queue.root().to_path_buf(),
12147                worktrees_root: worktrees,
12148                operation: "housekeeping".to_owned(),
12149            })
12150            .unwrap(),
12151        )
12152        .await
12153        .unwrap();
12154
12155        assert_eq!(
12156            questions.get(&question.id).unwrap().status,
12157            ask::QuestionStatus::Abandoned,
12158            "the independent housekeeping worker settles ended-run questions"
12159        );
12160    }
12161
12162    #[test]
12163    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
12164        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12165
12166        assert!(
12167            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
12168            "never checked before: due at once"
12169        );
12170
12171        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
12172        assert!(
12173            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
12174            "well inside the interval: not due yet"
12175        );
12176
12177        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
12178        assert!(
12179            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
12180            "exactly at the edge: not yet due, same convention as `clean::due`"
12181        );
12182
12183        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
12184        assert!(
12185            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
12186            "past the interval: due again"
12187        );
12188    }
12189
12190    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
12191    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
12192    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
12193    /// and the congestion test below both need, and must not drift apart.
12194    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
12195        let config = dir.join("magi.toml");
12196        // A literal (single-quoted) TOML string, not a basic one: the cache
12197        // path is a Windows path full of backslashes, and a basic string
12198        // would have TOML try to interpret `\U` (from `\Users\...`) as a
12199        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
12200        // `{{ vars.cache }}` rendering documents.
12201        std::fs::write(
12202            &config,
12203            format!(
12204                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
12205                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
12206                cache_dir.display()
12207            ),
12208        )
12209        .unwrap();
12210        Opts {
12211            config: Some(config),
12212            repo: dir.join("repo"),
12213            ..Opts::default()
12214        }
12215    }
12216
12217    #[tokio::test]
12218    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
12219        let dir = tempfile::tempdir().unwrap();
12220        let home = dir.path().join("home");
12221        let cache_dir = dir.path().join("cache");
12222        std::fs::create_dir_all(&cache_dir).unwrap();
12223        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12224        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12225
12226        // Nobody has asked this daemon to stop, which is the ordinary case;
12227        // the skip that a stop buys is asserted by its own test below.
12228        let running = Stop::new();
12229        let mut last_checked = None;
12230        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12231        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
12232            .await;
12233        assert_eq!(
12234            crate::disk::dir_size(&cache_dir),
12235            0,
12236            "over the cap on the first check ever: pruned at once, no idle queue required"
12237        );
12238        assert_eq!(last_checked, Some(t0));
12239
12240        // A fresh oversized file lands, but the next check is not due yet.
12241        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
12242        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
12243        maybe_prune_cache_between_runs(
12244            &opts.repo,
12245            &opts,
12246            &home,
12247            &running,
12248            &mut last_checked,
12249            too_soon,
12250        )
12251        .await;
12252        assert_eq!(
12253            crate::disk::dir_size(&cache_dir),
12254            10,
12255            "too soon since the last check: left alone rather than rescanned every call"
12256        );
12257        assert_eq!(
12258            last_checked,
12259            Some(t0),
12260            "an idle check does not reset the clock"
12261        );
12262
12263        // Once the interval elapses, the same oversized cache is caught again.
12264        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
12265        maybe_prune_cache_between_runs(
12266            &opts.repo,
12267            &opts,
12268            &home,
12269            &running,
12270            &mut last_checked,
12271            due_again,
12272        )
12273        .await;
12274        assert_eq!(
12275            crate::disk::dir_size(&cache_dir),
12276            0,
12277            "due again: pruned back under the cap"
12278        );
12279    }
12280
12281    /// A stop must not queue behind housekeeping. The prune below is a
12282    /// synchronous walk of the whole cache with no await point in it, so a
12283    /// loop that entered it could not get back to its own `stopped()` test
12284    /// until the walk finished - and because no run is in flight at this
12285    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
12286    /// the stop had already landed. The idle branch has always made this same
12287    /// check before reaching `janitor`; the between-runs path makes it too.
12288    #[tokio::test]
12289    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
12290        let dir = tempfile::tempdir().unwrap();
12291        let home = dir.path().join("home");
12292        let cache_dir = dir.path().join("cache");
12293        std::fs::create_dir_all(&cache_dir).unwrap();
12294        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12295        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12296
12297        let stop = Stop::new();
12298        stop.stop();
12299        assert!(
12300            !stop.finishing(),
12301            "no run is in flight at a between-runs boundary, so nothing else \
12302             would tell the operator this stop had not taken effect yet"
12303        );
12304
12305        let mut last_checked = None;
12306        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12307        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
12308            .await;
12309        assert_eq!(
12310            crate::disk::dir_size(&cache_dir),
12311            10,
12312            "over its cap, and due for the first check ever, but a stop outranks \
12313             it: the cap is a standing policy the next start measures again"
12314        );
12315        assert_eq!(
12316            last_checked, None,
12317            "a check that never happened must not claim the interval"
12318        );
12319    }
12320
12321    /// A backlog must not starve cache pruning. The finite cache worker runs
12322    /// independently of queue drain and must not consume any task attempts.
12323    #[tokio::test]
12324    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
12325        let dir = tempfile::tempdir().unwrap();
12326        let cache_dir = dir.path().join("cache");
12327        std::fs::create_dir_all(&cache_dir).unwrap();
12328        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
12329
12330        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
12331        opts.poll = Duration::from_millis(20);
12332        opts.max_attempts = 1_000;
12333
12334        let queue = Queue::at(dir.path().join("queue"));
12335        for i in 0..128 {
12336            let mut task = Task::new(
12337                format!("queued work {i}"),
12338                format!("queued work {i}"),
12339                opts.repo.clone(),
12340                Source::Human,
12341            );
12342            queue.put(&mut task).unwrap();
12343        }
12344
12345        let home = dir.path().join("home");
12346        let worktrees = dir.path().join("wt");
12347        run_service_worker(
12348            &home,
12349            serde_json::to_value(ServiceWorker {
12350                opts,
12351                queue: queue.root().to_path_buf(),
12352                worktrees_root: worktrees,
12353                operation: "cache".to_owned(),
12354            })
12355            .unwrap(),
12356        )
12357        .await
12358        .unwrap();
12359        let after = queue.list();
12360        assert_eq!(after.len(), 128);
12361        assert!(
12362            after
12363                .iter()
12364                .all(|task| task.status.runnable() && task.attempts == 0)
12365        );
12366
12367        assert_eq!(
12368            crate::disk::dir_size(&cache_dir),
12369            0,
12370            "an oversized cache must not be left to grow unboundedly just because the \
12371             queue kept the loop busy the whole time"
12372        );
12373    }
12374
12375    #[test]
12376    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
12377        let dir = tempfile::tempdir().unwrap();
12378        let queue = Queue::at(dir.path().join("queue"));
12379        let questions = Questions::at(dir.path().join("questions"));
12380        let mut task = task();
12381        queue.put(&mut task).unwrap();
12382
12383        let mut task_question = ask::Question::new(
12384            task.id.clone(),
12385            crate::conduct::NODE.to_owned(),
12386            "conduct".to_owned(),
12387            "Which backend?".to_owned(),
12388            String::new(),
12389            Vec::new(),
12390        );
12391        questions.put(&mut task_question).unwrap();
12392        task.block(vec![task_question.id.clone()], None);
12393        queue.put(&mut task).unwrap();
12394
12395        let mut run_question = ask::Question::new(
12396            "20260101-000000-run1".to_owned(),
12397            "review".to_owned(),
12398            "reviewer-1".to_owned(),
12399            "Run question".to_owned(),
12400            String::new(),
12401            Vec::new(),
12402        );
12403        questions.put(&mut run_question).unwrap();
12404
12405        // A question from another node whose `run` happens to equal this
12406        // task's id — the same field, filled in for an unrelated reason. Only
12407        // `crate::conduct::NODE` questions use `run` as a task id; this one
12408        // must never be touched by this reconciliation, even after release.
12409        let mut coincidental = ask::Question::new(
12410            task.id.clone(),
12411            "review".to_owned(),
12412            "reviewer-1".to_owned(),
12413            "Unrelated review question".to_owned(),
12414            String::new(),
12415            Vec::new(),
12416        );
12417        questions.put(&mut coincidental).unwrap();
12418
12419        reconcile_task_questions(&queue, &questions);
12420        assert!(questions.get(&task_question.id).unwrap().status.open());
12421        assert!(questions.get(&run_question.id).unwrap().status.open());
12422        assert!(questions.get(&coincidental.id).unwrap().status.open());
12423
12424        task.release();
12425        queue.put(&mut task).unwrap();
12426        reconcile_task_questions(&queue, &questions);
12427        assert_eq!(
12428            questions.get(&task_question.id).unwrap().status,
12429            ask::QuestionStatus::Abandoned
12430        );
12431        assert!(
12432            questions.get(&run_question.id).unwrap().status.open(),
12433            "run questions remain the run janitor's responsibility"
12434        );
12435        assert!(
12436            questions.get(&coincidental.id).unwrap().status.open(),
12437            "a non-conductor question must not be abandoned just because its \
12438             run id coincides with a task id"
12439        );
12440    }
12441
12442    #[test]
12443    fn a_freshly_started_running_task_is_never_stalled() {
12444        let dir = tempfile::tempdir().unwrap();
12445        let mut t = task();
12446        t.start("run-1".to_owned());
12447        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
12448        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
12449        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
12450    }
12451
12452    #[test]
12453    fn a_long_running_task_with_no_live_daemon_is_stalled() {
12454        let dir = tempfile::tempdir().unwrap();
12455        let mut t = task();
12456        t.start("run-1".to_owned());
12457        t.updated_at = Timestamp::now()
12458            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12459        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
12460        assert_eq!(
12461            stalled_tasks(
12462                &Queue::at(dir.path().join("q")),
12463                dir.path(),
12464                Timestamp::now()
12465            )
12466            .len(),
12467            0,
12468            "the task was never written to this queue"
12469        );
12470    }
12471
12472    #[test]
12473    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
12474        let dir = tempfile::tempdir().unwrap();
12475        let mut t = task();
12476        t.id = "20260903-080340-0167".to_owned();
12477        t.start("20260903-080619-01c2".to_owned());
12478        t.updated_at = Timestamp::now()
12479            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12480
12481        let mut status = Status::new();
12482        status.current = vec![Current {
12483            worker: None,
12484            task: t.id.clone(),
12485            run: "20260903-080619-01c2".to_owned(),
12486        }];
12487        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12488
12489        assert!(
12490            !is_stalled(&t, dir.path(), Timestamp::now()),
12491            "a live daemon's own heartbeat rules out stalled, however long the task has run"
12492        );
12493    }
12494
12495    /// Rewrite a task's `updated_at` on disk directly, bypassing
12496    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
12497    /// a fixture look like it has genuinely been `running` for a while.
12498    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
12499        let path = queue.path_of(id);
12500        let body = std::fs::read_to_string(&path).unwrap();
12501        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
12502        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
12503        v["updated_at"] = serde_json::Value::String(old.to_string());
12504        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
12505    }
12506
12507    #[test]
12508    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
12509        // The realistic `poll()` ordering, not `is_stalled` in isolation:
12510        // `reclaim_orphaned_running` runs first, on every poll, and settles
12511        // any `running` task whose claim it can actually take. For most
12512        // crashes that is immediate - a dead pid is proof enough for
12513        // `sweep_stale_claims` to drop the lock the same tick, and the very
12514        // next claim attempt succeeds. But a lock whose pid cannot be parsed
12515        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
12516        // `sweep_stale_claims`'s own doc), so the lock - and the claim
12517        // failure behind it - can legitimately outlive many polls. This is
12518        // exactly the gap `stalled_tasks` exists to surface well before that
12519        // six-hour sweep would: reclaim leaves the task `running`, and it
12520        // must still reach the conductor as stalled.
12521        let dir = tempfile::tempdir().unwrap();
12522        let queue = Queue::at(dir.path().join("queue"));
12523        let home = dir.path().join("home");
12524
12525        let mut t = task();
12526        t.id = "20260101-000001-lock".to_owned();
12527        t.start("run-1".to_owned());
12528        queue.put(&mut t).unwrap();
12529        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12530        std::fs::write(
12531            dir.path().join("queue").join(format!("{}.lock", t.id)),
12532            "not a pid",
12533        )
12534        .unwrap();
12535
12536        let now = Timestamp::now();
12537        assert!(
12538            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
12539            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
12540             and reclaim must leave the task alone"
12541        );
12542        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
12543
12544        let stalled = stalled_tasks(&queue, &home, now);
12545        assert_eq!(
12546            stalled.len(),
12547            1,
12548            "reclaim's inability to claim it yet must not hide it from the conductor"
12549        );
12550        assert_eq!(stalled[0].id, t.id);
12551    }
12552
12553    #[test]
12554    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
12555        let dir = tempfile::tempdir().unwrap();
12556        crate::run::set_home(dir.path().join("run-home"));
12557        let queue = Queue::at(dir.path().join("queue"));
12558        let home = dir.path().join("home");
12559        let questions = Questions::at(dir.path().join("questions"));
12560
12561        let mut t = task();
12562        t.id = "20260101-000003-dead".to_owned();
12563        t.start("missing-run".to_owned());
12564        queue.put(&mut t).unwrap();
12565        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12566
12567        // This is the real poll ordering: retain the deterministic stalled
12568        // input before a claim proves the owner is gone and reclaims it.
12569        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12570        assert_eq!(
12571            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
12572            [&t.id]
12573        );
12574        assert_eq!(
12575            reclaim_orphaned_running(&queue, 2, &Default::default()),
12576            [t.id.clone()]
12577        );
12578        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12579
12580        // Reclaim drops its guard before conductor decisions are applied, so
12581        // the decision for the captured stalled input has a real write path.
12582        crate::conduct::apply(
12583            &queue,
12584            &questions,
12585            &crate::conduct::Verdict {
12586                decisions: vec![crate::conduct::Decision {
12587                    id: t.id.clone(),
12588                    recovery: Some(crate::conduct::Recovery::Requeue),
12589                    ..crate::conduct::Decision::default()
12590                }],
12591            },
12592        )
12593        .unwrap();
12594        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12595    }
12596
12597    #[test]
12598    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
12599        let dir = tempfile::tempdir().unwrap();
12600        let queue = Queue::at(dir.path().join("queue"));
12601        let home = dir.path().join("home");
12602
12603        let mut fresh = task();
12604        fresh.id = "20260101-000001-aaaa".to_owned();
12605        fresh.start("run-1".to_owned());
12606        queue.put(&mut fresh).unwrap();
12607
12608        let mut old = task();
12609        old.id = "20260101-000002-bbbb".to_owned();
12610        old.start("run-2".to_owned());
12611        queue.put(&mut old).unwrap();
12612        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
12613
12614        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12615        assert_eq!(stalled.len(), 1);
12616        assert_eq!(stalled[0].id, old.id);
12617    }
12618
12619    #[test]
12620    fn queued_and_finished_task_views_partition_by_status() {
12621        let dir = tempfile::tempdir().unwrap();
12622        let queue = Queue::at(dir.path().join("queue"));
12623
12624        let mut queued = task();
12625        queued.id = "20260101-000001-aaaa".to_owned();
12626        queue.put(&mut queued).unwrap();
12627
12628        let mut failed = task();
12629        failed.id = "20260101-000002-bbbb".to_owned();
12630        failed.start("run-1".to_owned());
12631        failed.fail("gate red", 5);
12632        queue.put(&mut failed).unwrap();
12633
12634        let mut held = task();
12635        held.id = "20260101-000003-cccc".to_owned();
12636        held.hold_machine(None);
12637        queue.put(&mut held).unwrap();
12638
12639        let mut running = task();
12640        running.id = "20260101-000004-dddd".to_owned();
12641        running.start("run-2".to_owned());
12642        queue.put(&mut running).unwrap();
12643
12644        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
12645        assert_eq!(queued_ids, [queued.id.clone()]);
12646
12647        let mut finished_ids: Vec<String> =
12648            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
12649        finished_ids.sort_unstable();
12650        let mut want = vec![failed.id.clone(), held.id.clone()];
12651        want.sort_unstable();
12652        assert_eq!(finished_ids, want);
12653    }
12654
12655    #[test]
12656    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
12657        for short in [false, true] {
12658            let dir = tempfile::tempdir().unwrap();
12659            let queue = Queue::at(dir.path().join("queue"));
12660            let questions = ask::Questions::at(dir.path().join("questions"));
12661            let mut running = task();
12662            running.id = "20261013-192213-feb2".into();
12663            running.start("existing-run".into());
12664            queue.put(&mut running).unwrap();
12665            let mut middle = task();
12666            middle.id = "20261013-193611-ca5b".into();
12667            middle.block(
12668                vec![if short {
12669                    "feb2".into()
12670                } else {
12671                    running.id.clone()
12672                }],
12673                None,
12674            );
12675            queue.put(&mut middle).unwrap();
12676            let mut waiting = task();
12677            waiting.id = "20261013-202849-ee37".into();
12678            waiting.block(
12679                vec![if short {
12680                    "ca5b".into()
12681                } else {
12682                    middle.id.clone()
12683                }],
12684                Some("wait for implementation".into()),
12685            );
12686            queue.put(&mut waiting).unwrap();
12687            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
12688            let inv = crate::blockers::Inventory::load(&queue, &questions);
12689            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
12690            assert!(inv.stuck().is_empty());
12691            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12692            assert!(report.quarantined.is_empty());
12693            assert!(report.asked.is_empty());
12694            resolve_blockers(&queue, &questions);
12695            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12696            assert!(questions.list().is_empty());
12697            // Finishing the transitive prerequisite alone does not satisfy
12698            // the task's direct dependency.
12699            running.succeed(CompletionContext::new(
12700                CompletionActor::DaemonSettle,
12701                None,
12702                dir.path(),
12703                &running,
12704            ));
12705            queue.put(&mut running).unwrap();
12706            resolve_blockers(&queue, &questions);
12707            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
12708            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12709            middle = queue.get(&middle.id).unwrap();
12710            middle.succeed(CompletionContext::new(
12711                CompletionActor::DaemonSettle,
12712                None,
12713                dir.path(),
12714                &middle,
12715            ));
12716            queue.put(&mut middle).unwrap();
12717            resolve_blockers(&queue, &questions);
12718            let after = queue.get(&waiting.id).unwrap();
12719            assert_eq!(after.status, TaskStatus::Queued);
12720            assert!(after.blocked_by.is_empty());
12721            assert_eq!(after.instruction, waiting.instruction);
12722        }
12723    }
12724
12725    #[test]
12726    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
12727        for future_schema in [false, true] {
12728            let name = "20261013-193611-ca5b";
12729            let mut future = task();
12730            future.id = name.into();
12731            future.schema = crate::queue::SCHEMA + 1;
12732            let contents = if future_schema {
12733                serde_json::to_string(&future).unwrap()
12734            } else {
12735                "corrupt".into()
12736            };
12737            let dir = tempfile::tempdir().unwrap();
12738            let queue = Queue::at(dir.path().join("queue"));
12739            let questions = ask::Questions::at(dir.path().join("questions"));
12740            let mut waiting = task();
12741            waiting.id = "20261013-202849-ee37".into();
12742            waiting.block(vec!["ca5b".into()], None);
12743            queue.put(&mut waiting).unwrap();
12744            std::fs::write(queue.path_of(name), contents).unwrap();
12745            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
12746            assert!(
12747                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
12748            );
12749            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12750            assert!(report.asked.is_empty());
12751            resolve_blockers(&queue, &questions);
12752            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12753            assert!(questions.list().is_empty());
12754        }
12755        let dir = tempfile::tempdir().unwrap();
12756        let queue = Queue::at(dir.path().join("queue"));
12757        let questions = ask::Questions::at(dir.path().join("questions"));
12758        let mut waiting = task();
12759        waiting.id = "20261013-202849-ee37".into();
12760        waiting.block(vec!["ca5b".into()], None);
12761        queue.put(&mut waiting).unwrap();
12762        let mut done = task();
12763        done.id = "20261013-193611-ca5b".into();
12764        done.succeed(CompletionContext::new(
12765            CompletionActor::Cli,
12766            None,
12767            dir.path(),
12768            &done,
12769        ));
12770        queue.put(&mut done).unwrap();
12771        // An unreadable second match must not disappear from uniqueness
12772        // checks just because Queue::list skips it.
12773        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
12774        assert!(queue.get("ca5b").is_err());
12775        assert_eq!(
12776            crate::queue::dependency(&queue, &questions, "ca5b"),
12777            crate::queue::Dependency::Ambiguous
12778        );
12779        resolve_blockers(&queue, &questions);
12780        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12781        assert!(report.asked.is_empty());
12782        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12783        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
12784    }
12785
12786    #[test]
12787    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
12788        for held in [false, true] {
12789            for question in [false, true] {
12790                for reference in ["ca5b", "20261013-193611-ca5b"] {
12791                    let dir = tempfile::tempdir().unwrap();
12792                    let queue = Queue::at(dir.path().join("queue"));
12793                    let questions = ask::Questions::at(dir.path().join("questions"));
12794                    let mut prerequisite = task();
12795                    prerequisite.id = "20261013-193611-ca5b".into();
12796                    prerequisite.start("existing-run".into());
12797                    queue.put(&mut prerequisite).unwrap();
12798                    let mut waiting = task();
12799                    waiting.id = "20261013-202849-ee37".into();
12800                    if held {
12801                        waiting.hold_machine(Some("waiting for separate consent".into()));
12802                    }
12803                    queue.put(&mut waiting).unwrap();
12804                    let reason = "Deleting saved data requires separate owner consent";
12805                    crate::conduct::apply(
12806                        &queue,
12807                        &questions,
12808                        &crate::conduct::Verdict {
12809                            decisions: vec![crate::conduct::Decision {
12810                                id: waiting.id.clone(),
12811                                blocked_by: vec![reference.into()],
12812                                question: question.then(|| "May the saved data be deleted?".into()),
12813                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
12814                                reason: Some(reason.into()),
12815                                ..crate::conduct::Decision::default()
12816                            }],
12817                        },
12818                    )
12819                    .unwrap();
12820                    let before = queue.get(&waiting.id).unwrap();
12821                    if question {
12822                        assert_eq!(before.status, TaskStatus::Blocked);
12823                        let q = questions.get(&before.blocked_by[0]).unwrap();
12824                        assert_eq!(q.summary, "May the saved data be deleted?");
12825                        assert!(q.status.open());
12826                    } else {
12827                        assert_eq!(before.status, TaskStatus::Held);
12828                        let recorded_reason = before.hold_reason.as_deref().unwrap();
12829                        assert!(recorded_reason.starts_with(reason));
12830                        if held {
12831                            assert!(recorded_reason.contains("waiting for separate consent"));
12832                        }
12833                    }
12834                    prerequisite.succeed(CompletionContext::new(
12835                        CompletionActor::DaemonSettle,
12836                        None,
12837                        dir.path(),
12838                        &prerequisite,
12839                    ));
12840                    queue.put(&mut prerequisite).unwrap();
12841                    resolve_blockers(&queue, &questions);
12842                    let after = queue.get(&waiting.id).unwrap();
12843                    assert_eq!(after.status, before.status);
12844                    assert_eq!(after.blocked_by, before.blocked_by);
12845                    assert_eq!(after.hold_reason, before.hold_reason);
12846                    assert_eq!(after.instruction, waiting.instruction);
12847                    if question {
12848                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
12849                    }
12850                    assert!(
12851                        queue.next_runnable().is_none(),
12852                        "dependency completion is not consent"
12853                    );
12854                }
12855            }
12856        }
12857    }
12858
12859    #[test]
12860    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
12861        let dir = tempfile::tempdir().unwrap();
12862        let queue = Queue::at(dir.path().join("queue"));
12863        let questions = ask::Questions::at(dir.path().join("questions"));
12864
12865        let mut dep = task();
12866        dep.id = "20260101-000001-dep0".to_owned();
12867        dep.succeed(CompletionContext::new(
12868            CompletionActor::DaemonSettle,
12869            None,
12870            dir.path(),
12871            &dep,
12872        ));
12873        queue.put(&mut dep).unwrap();
12874
12875        let mut still_going = task();
12876        still_going.id = "20260101-000002-dep1".to_owned();
12877        queue.put(&mut still_going).unwrap();
12878
12879        let mut blocked = task();
12880        blocked.id = "20260101-000003-main".to_owned();
12881        blocked.block(
12882            vec![dep.id.clone(), still_going.id.clone()],
12883            Some("waits on both".to_owned()),
12884        );
12885        queue.put(&mut blocked).unwrap();
12886
12887        resolve_blockers(&queue, &questions);
12888
12889        let after = queue.get(&blocked.id).unwrap();
12890        assert_eq!(
12891            after.status,
12892            TaskStatus::Blocked,
12893            "one dependency is still outstanding"
12894        );
12895        assert_eq!(after.blocked_by, [still_going.id.clone()]);
12896    }
12897
12898    #[test]
12899    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
12900        let dir = tempfile::tempdir().unwrap();
12901        let queue = Queue::at(dir.path().join("queue"));
12902        let questions = ask::Questions::at(dir.path().join("questions"));
12903
12904        let mut q = crate::ask::Question::new(
12905            "20260101-000001-main".to_owned(),
12906            crate::conduct::NODE.to_owned(),
12907            "conduct".to_owned(),
12908            "Which backend?".to_owned(),
12909            String::new(),
12910            Vec::new(),
12911        );
12912        questions.put(&mut q).unwrap();
12913        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
12914            .unwrap();
12915        questions.put(&mut q).unwrap();
12916
12917        let mut blocked = task();
12918        blocked.id = "20260101-000001-main".to_owned();
12919        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
12920        queue.put(&mut blocked).unwrap();
12921
12922        resolve_blockers(&queue, &questions);
12923
12924        let after = queue.get(&blocked.id).unwrap();
12925        assert_eq!(
12926            after.status,
12927            TaskStatus::Queued,
12928            "the only blocker resolved"
12929        );
12930        assert_eq!(after.answers.len(), 1);
12931        assert_eq!(after.answers[0].question, "Which backend?");
12932        assert_eq!(after.answers[0].answer, "SQLite");
12933
12934        // And the run this task starts next is told about it.
12935        let instruction = instruction_for(&after);
12936        assert!(instruction.contains("Which backend?"));
12937        assert!(instruction.contains("SQLite"));
12938    }
12939
12940    #[test]
12941    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
12942        let dir = tempfile::tempdir().unwrap();
12943        let queue = Queue::at(dir.path().join("queue"));
12944        let questions = ask::Questions::at(dir.path().join("questions"));
12945
12946        let mut q = crate::ask::Question::new(
12947            "20260101-000001-main".to_owned(),
12948            crate::conduct::NODE.to_owned(),
12949            "conduct".to_owned(),
12950            "Is the setup done?".to_owned(),
12951            String::new(),
12952            Vec::new(),
12953        );
12954        q.abandon("no answer within 60s of asking");
12955        questions.put(&mut q).unwrap();
12956
12957        let mut blocked = task();
12958        blocked.id = "20260101-000001-main".to_owned();
12959        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
12960        queue.put(&mut blocked).unwrap();
12961
12962        resolve_blockers(&queue, &questions);
12963
12964        let after = queue.get(&blocked.id).unwrap();
12965        assert_eq!(
12966            after.status,
12967            TaskStatus::Held,
12968            "never left blocked on nothing"
12969        );
12970        assert!(!after.operator_held(), "a machine hold, for triage");
12971        assert!(
12972            after
12973                .hold_reason
12974                .as_deref()
12975                .unwrap_or_default()
12976                .contains("went unanswered")
12977        );
12978    }
12979
12980    #[test]
12981    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
12982        // Reproduces the reported bug (task 3958): a task held out of
12983        // attempts, blocked on a `crate::conduct` follow-up question, must
12984        // come back `held` once that question is answered - never `queued`,
12985        // whatever the answer said - or it silently re-enters the
12986        // competition queue with its attempts already exhausted.
12987        let dir = tempfile::tempdir().unwrap();
12988        let queue = Queue::at(dir.path().join("queue"));
12989        let questions = ask::Questions::at(dir.path().join("questions"));
12990
12991        let mut q = crate::ask::Question::new(
12992            "20260101-000001-main".to_owned(),
12993            crate::conduct::NODE.to_owned(),
12994            "conduct".to_owned(),
12995            "How should this be handled?".to_owned(),
12996            String::new(),
12997            Vec::new(),
12998        );
12999        questions.put(&mut q).unwrap();
13000        q.answer(crate::ask::Answer::Text(
13001            "leave it held, a human will look at it later".to_owned(),
13002        ))
13003        .unwrap();
13004        questions.put(&mut q).unwrap();
13005
13006        let mut held = task();
13007        held.id = "20260101-000001-main".to_owned();
13008        held.hold_machine(Some("out of attempts".to_owned()));
13009        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
13010        queue.put(&mut held).unwrap();
13011
13012        resolve_blockers(&queue, &questions);
13013
13014        let after = queue.get(&held.id).unwrap();
13015        assert_eq!(after.status, TaskStatus::Held);
13016        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
13017        assert_eq!(
13018            after.answers[0].answer,
13019            "leave it held, a human will look at it later"
13020        );
13021    }
13022
13023    #[test]
13024    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
13025        let dir = tempfile::tempdir().unwrap();
13026        let queue = Queue::at(dir.path().join("queue"));
13027        let questions = ask::Questions::at(dir.path().join("questions"));
13028        let mut dep = task();
13029        dep.id = "20260101-000001-gone".to_owned();
13030        queue.put(&mut dep).unwrap();
13031        let mut blocked = task();
13032        blocked.id = "20260101-000003-main".to_owned();
13033        blocked.block(vec![dep.id.clone()], None);
13034        queue.put(&mut blocked).unwrap();
13035
13036        // Claimed, so `remove` cannot rewrite it and the resolver must.
13037        let claim = queue.claim(&blocked.id).unwrap();
13038        queue.remove(&dep.id, false, &questions).unwrap();
13039        drop(claim);
13040        resolve_blockers(&queue, &questions);
13041
13042        let after = queue.get(&blocked.id).unwrap();
13043        assert_eq!(after.status, TaskStatus::Queued);
13044        assert!(after.blocked_by.is_empty());
13045    }
13046
13047    #[test]
13048    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
13049        // Reproduces the reported bug: a task blocked on a task id that was
13050        // removed (`magi task rm`, or deleted by hand) can never see that id
13051        // reach `Done`, so the ordinary per-id loop has nothing to notice and
13052        // would otherwise leave the task `blocked` forever with no way for an
13053        // operator to find out why.
13054        let dir = tempfile::tempdir().unwrap();
13055        let queue = Queue::at(dir.path().join("queue"));
13056        let questions = ask::Questions::at(dir.path().join("questions"));
13057
13058        let mut still_going = task();
13059        still_going.id = "20260101-000002-dep1".to_owned();
13060        queue.put(&mut still_going).unwrap();
13061
13062        let mut blocked = task();
13063        blocked.id = "20260101-000003-main".to_owned();
13064        blocked.block(
13065            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
13066            Some("waits on both".to_owned()),
13067        );
13068        queue.put(&mut blocked).unwrap();
13069
13070        resolve_blockers(&queue, &questions);
13071
13072        let after = queue.get(&blocked.id).unwrap();
13073        assert_eq!(
13074            after.status,
13075            TaskStatus::Held,
13076            "a missing dependency must not leave the task blocked forever"
13077        );
13078        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
13079        assert!(after.blocked_by.is_empty());
13080        let reason = after.hold_reason.as_deref().unwrap_or_default();
13081        assert!(
13082            reason.contains("20260101-000001-gone"),
13083            "the missing id must be named so an operator can tell what happened: {reason}"
13084        );
13085        assert!(
13086            reason.contains(&still_going.id),
13087            "the still-valid dependency must not silently vanish from the record: {reason}"
13088        );
13089    }
13090
13091    #[test]
13092    fn instruction_for_is_unchanged_without_any_answers() {
13093        let t = task();
13094        assert_eq!(instruction_for(&t), t.instruction);
13095    }
13096
13097    #[test]
13098    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
13099        let dir = tempfile::tempdir().unwrap();
13100        let q = Queue::at(dir.path().join("queue"));
13101        let src = dir.path().join("shot.png");
13102        std::fs::write(&src, "x").unwrap();
13103        let mut t = task();
13104        q.attach(&mut t, &[src]).unwrap();
13105        let paths = task_attachments(&q, &t).unwrap();
13106        assert_eq!(paths.len(), 1);
13107        assert!(paths[0].is_absolute() && paths[0].is_file());
13108        std::fs::remove_file(&paths[0]).unwrap();
13109        let err = task_attachments(&q, &t).unwrap_err().to_string();
13110        assert!(err.contains("shot.png"), "{err}");
13111    }
13112
13113    #[tokio::test]
13114    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
13115        let dir = tempfile::tempdir().unwrap();
13116        let queue_path = dir.path().join("queue");
13117        let queue = Queue::at(queue_path.clone());
13118        let mut t = task();
13119        t.source = Source::Agent {
13120            run: "originating-chat".into(),
13121            node: crate::queue::CHAT_NODE.into(),
13122        };
13123        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
13124            stage: "config-fetch",
13125            target: "origin/main".into(),
13126        });
13127        record_config_failure(&mut t, &fetch);
13128        t.hold_machine(Some(format!("{fetch:#}")));
13129        let fetch_key = t.chat_notice_due().unwrap();
13130        t.chat_notices.push(fetch_key.clone());
13131        queue.put(&mut t).unwrap();
13132
13133        let queue = Queue::at(queue_path);
13134        let mut t = queue.get(&t.id).unwrap();
13135        let a = dir.path().join("a.toml");
13136        let b = dir.path().join("b.toml");
13137        for (path, text, new_cause) in [
13138            (&a, "[graph", true),
13139            (&a, "[verify", false),
13140            (&a, "[graph]\nimplementers = 'invalid-type'", true),
13141            (&b, "[graph]\nimplementers = 'invalid-type'", true),
13142        ] {
13143            t.release_operator("test", None);
13144            std::fs::write(path, text).unwrap();
13145            let error = Config::discover_fetched(dir.path(), Some(path))
13146                .await
13147                .unwrap_err();
13148            record_config_failure(&mut t, &error);
13149            t.hold_machine(Some(format!("{error:#}")));
13150            let due = t.chat_notice_due();
13151            assert_eq!(due.is_some(), new_cause, "{error:#}");
13152            if let Some(key) = due {
13153                assert_ne!(key, fetch_key);
13154                t.chat_notices.push(key);
13155            }
13156        }
13157        t.succeed(CompletionContext::new(
13158            CompletionActor::DaemonSettle,
13159            None,
13160            dir.path(),
13161            &t,
13162        ));
13163        assert_eq!(
13164            t.chat_notice_due(),
13165            Some(format!(
13166                "done:{}",
13167                t.completion_history.last().unwrap().occurrence
13168            ))
13169        );
13170    }
13171
13172    #[test]
13173    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
13174        let dir = tempfile::tempdir().unwrap();
13175        let queue_path = dir.path().join("queue");
13176        let queue = Queue::at(queue_path.clone());
13177        let mut t = task();
13178        t.source = crate::queue::Source::Agent {
13179            run: "originating-chat".into(),
13180            node: crate::queue::CHAT_NODE.into(),
13181        };
13182        let a = dir.path().join("a.png");
13183        let b = dir.path().join("b.png");
13184        std::fs::write(&a, "a").unwrap();
13185        std::fs::write(&b, "b").unwrap();
13186        queue.attach(&mut t, &[a, b]).unwrap();
13187        let paths = task_attachments(&queue, &t).unwrap();
13188        for path in &paths {
13189            std::fs::remove_file(path).unwrap();
13190        }
13191        let missing = task_attachments(&queue, &t).unwrap_err();
13192        t.attempts += 1;
13193        let reason = missing.to_string();
13194        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
13195        let first = t.chat_notice_due().expect("first attachment notice");
13196        t.chat_notices.push(first.clone());
13197        queue.put(&mut t).unwrap();
13198
13199        let queue = Queue::at(queue_path.clone());
13200        let mut t = queue.get(&t.id).unwrap();
13201        assert!(t.chat_notice_due().is_none(), "restart does not replay");
13202        t.release_operator("test", None);
13203        t.attempts += 1;
13204        let missing = task_attachments(&queue, &t).unwrap_err();
13205        t.fail_startup_target(
13206            "startup-attachments",
13207            missing.name,
13208            "same missing attachment with regenerated wording",
13209            1,
13210        );
13211        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
13212
13213        std::fs::write(&paths[0], "restored").unwrap();
13214        t.release_operator("test", None);
13215        t.attempts += 1;
13216        let missing = task_attachments(&queue, &t).unwrap_err();
13217        let reason = missing.to_string();
13218        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
13219        let second = t
13220            .chat_notice_due()
13221            .expect("different attachment must notify");
13222        assert_ne!(first, second);
13223        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
13224    }
13225
13226    #[test]
13227    fn resumed_instruction_is_unchanged_without_any_answers() {
13228        let t = task();
13229        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
13230    }
13231
13232    #[test]
13233    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
13234        let mut t = task();
13235        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13236        // The run's own instruction on disk predates the answer: it is the
13237        // plain original text `Runner::start` saved before the operator was
13238        // ever asked anything.
13239        let old = t.instruction.clone();
13240
13241        let refreshed = resumed_instruction(&old, &t);
13242        assert!(refreshed.starts_with(&old), "the original text is kept");
13243        assert!(refreshed.contains("Which backend?"));
13244        assert!(refreshed.contains("SQLite"));
13245    }
13246
13247    #[test]
13248    fn resumed_instruction_keeps_an_original_answers_heading() {
13249        let mut t = task();
13250        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
13251        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13252
13253        let refreshed = resumed_instruction(&t.instruction, &t);
13254
13255        assert!(
13256            refreshed.starts_with(&t.instruction),
13257            "an answers heading in the original instruction is not the appended block"
13258        );
13259        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
13260        assert!(refreshed.contains("Which backend?"));
13261        assert!(refreshed.contains("SQLite"));
13262
13263        let repeated = resumed_instruction(&refreshed, &t);
13264        assert_eq!(
13265            repeated, refreshed,
13266            "only the final appended block is refreshed"
13267        );
13268    }
13269
13270    #[test]
13271    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
13272        let mut t = task();
13273        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13274
13275        // A first resume appends the block; a second resume of the same run,
13276        // with no new answer in between, must reproduce exactly the same
13277        // text rather than appending the block a second time.
13278        let once = resumed_instruction(&t.instruction, &t);
13279        let twice = resumed_instruction(&once, &t);
13280        assert_eq!(once, twice);
13281        assert_eq!(once.matches("Which backend?").count(), 1);
13282
13283        // A later answer replaces the block wholesale rather than growing it.
13284        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
13285        let refreshed = resumed_instruction(&once, &t);
13286        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
13287        assert!(refreshed.contains("Which backend?"));
13288        assert!(refreshed.contains("Which cache?"));
13289    }
13290
13291    #[test]
13292    fn prepare_instruction_covers_all_three_starters() {
13293        let mut t = task();
13294        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13295
13296        // Start: a fresh run gets the task text plus every answer so far —
13297        // exactly `instruction_for`.
13298        assert_eq!(
13299            prepare_instruction(&Starter::Start, None, &t),
13300            Some(instruction_for(&t))
13301        );
13302
13303        // Resume: the run's prior instruction is refreshed with the answer,
13304        // not discarded and not left stale.
13305        let old = t.instruction.clone();
13306        assert_eq!(
13307            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
13308            Some(resumed_instruction(&old, &t))
13309        );
13310
13311        // Review: a review-only pass builds its own instruction from the
13312        // branch's history in `crate::graph`, with no task statement at all -
13313        // this boundary must leave it alone.
13314        assert_eq!(
13315            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
13316            None
13317        );
13318    }
13319
13320    #[test]
13321    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
13322        assert_eq!(
13323            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
13324            Starter::Review("magi/eba2/A".to_owned())
13325        );
13326    }
13327
13328    #[test]
13329    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
13330        assert_eq!(
13331            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
13332            Starter::Start,
13333            "a vanished review branch must not fall back to resuming the old run either"
13334        );
13335    }
13336
13337    #[test]
13338    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
13339        let mut t = task();
13340        t.start("old-run".to_owned());
13341        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
13342        t.release();
13343        let branch = t.review_branch.take();
13344        assert_eq!(
13345            choose_starter(branch.as_deref(), true, Some("old-run")),
13346            Starter::Review("magi/eba2/A".to_owned()),
13347            "a review wins over resuming the old run"
13348        );
13349    }
13350
13351    #[test]
13352    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
13353        assert_eq!(
13354            choose_starter(None, false, Some("some-run")),
13355            Starter::Resume("some-run".to_owned())
13356        );
13357        assert_eq!(choose_starter(None, false, None), Starter::Start);
13358    }
13359
13360    #[test]
13361    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
13362        let mut released = task();
13363        released.start("stalled-run".to_owned());
13364        released.requeue();
13365        let unfinished = (!released.fresh_start)
13366            .then(|| Some("stalled-run".to_owned()))
13367            .flatten();
13368        assert_eq!(
13369            choose_starter(None, false, unfinished.as_deref()),
13370            Starter::Start,
13371            "release keeps run history but must not resume it"
13372        );
13373        assert_eq!(released.runs, ["stalled-run"]);
13374    }
13375
13376    #[test]
13377    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
13378        let dir = tempfile::tempdir().unwrap();
13379        let queue = Queue::at(dir.path().join("queue"));
13380        let mut state = run_state(RunStatus::Blocked);
13381        state.merge_decision = Some(crate::merge_decision::Decision {
13382            question: "hold-inquiry".into(),
13383            target: crate::merge_decision::Target {
13384                pr: "https://example.test/pull/1".into(),
13385                head: "reviewed-head".into(),
13386                language: "en".into(),
13387            },
13388            choice: land::HOLD.into(),
13389            closed: false,
13390            replacement_run: None,
13391            replacement_pr: None,
13392        });
13393        let mut t = task();
13394        t.start(state.id.clone());
13395        settle_and_diagnose(
13396            &mut t,
13397            Verdict {
13398                status: RunStatus::Blocked,
13399                left_pr: true,
13400                quota_hit: false,
13401                parked: false,
13402                no_viable_candidates: false,
13403            },
13404            "held",
13405            2,
13406            &state,
13407        );
13408        queue.put(&mut t).unwrap();
13409        t.release_operator("chat", None);
13410        t.edit("revised".into(), "revised instruction".into())
13411            .unwrap();
13412        queue.put(&mut t).unwrap();
13413        drop(state);
13414        assert_eq!(
13415            queue
13416                .get(&t.id)
13417                .unwrap()
13418                .decision_effects
13419                .get("hold-inquiry"),
13420            Some(&format!("decision: {}", land::HOLD))
13421        );
13422    }
13423
13424    fn stopped_public_run(status: RunStatus) -> RunState {
13425        let mut state = run_state(status);
13426        state.driver_exited = true;
13427        state.config.graph.land = true;
13428        state.config.graph.review_rounds = 1;
13429        state.reviews = vec![review_round(1)];
13430        state.merge = Some(crate::run::MergeOutcome {
13431            mode: MergeMode::Pr,
13432            ok: false,
13433            detail: "landing stopped".into(),
13434            empty: false,
13435        });
13436        state.pr = Some(crate::run::PrRecord {
13437            url: "https://example.test/pull/1".into(),
13438            number: 1,
13439            state: "open".into(),
13440            checks: "red".into(),
13441            round: 1,
13442            rounds: 1,
13443            red_at_merge: Vec::new(),
13444        });
13445        state
13446    }
13447
13448    #[test]
13449    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
13450        for status in [RunStatus::Blocked, RunStatus::Gating] {
13451            let home = tempfile::tempdir().unwrap();
13452            let mut state = stopped_public_run(status);
13453            state.save_under(home.path()).unwrap();
13454            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
13455            assert!(!exhausted_review_budget(&state));
13456            let mut task = held_task_with(&state.id);
13457            task.release();
13458            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13459            assert_eq!(
13460                choose_starter(None, false, unfinished.as_deref()),
13461                Starter::Resume(state.id.clone())
13462            );
13463            let question = action_question(&state.id, resume_action(&state.id));
13464            assert_eq!(
13465                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13466                    state.clone()
13467                )),
13468                ActionDecision::Resume(state.id.clone())
13469            );
13470            // The control-plane command uses this same preflight before pinning.
13471            assert_eq!(
13472                crate::resume::validate(home.path(), &state.id).unwrap().id,
13473                state.id
13474            );
13475            let queue = Queue::at(home.path().join("queue"));
13476            let mut controlled = Task::new(
13477                "resume land".into(),
13478                state.instruction.clone(),
13479                state.repo.clone(),
13480                Source::Agent {
13481                    run: "talk".into(),
13482                    node: crate::queue::CHAT_NODE.into(),
13483                },
13484            );
13485            controlled.runs.push(state.id.clone());
13486            controlled.hold_machine(Some("land stopped".into()));
13487            queue.put(&mut controlled).unwrap();
13488            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13489            assert_eq!(resumed.status, TaskStatus::Queued);
13490            assert_eq!(
13491                resumed.resume_override.unwrap().pinned_run,
13492                Some(state.id.clone())
13493            );
13494            assert_eq!(resumed.attempts, 0);
13495        }
13496    }
13497
13498    #[test]
13499    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
13500        for review_rounds in [0, 1] {
13501            let home = tempfile::tempdir().unwrap();
13502            let mut state = run_state(RunStatus::Blocked);
13503            state.config.graph.review_rounds = review_rounds;
13504            if review_rounds > 0 {
13505                let mut review = review_round(1);
13506                review.clean = true;
13507                state.reviews = vec![review];
13508            }
13509            state.gate_ran = true;
13510            state.gate = vec![crate::run::CommandOutcome {
13511                command: "verify".into(),
13512                code: Some(1),
13513                output_tail: "gate failed after repair budget exhausted".into(),
13514                duration_ms: 0,
13515                resource_blocked: false,
13516                ..Default::default()
13517            }];
13518            state.save_under(home.path()).unwrap();
13519            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13520            assert!(exhausted_review_budget(&state));
13521            let mut task = held_task_with(&state.id);
13522            task.release();
13523            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
13524            let question = action_question(&state.id, resume_action(&state.id));
13525            assert_ne!(
13526                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13527                    state.clone()
13528                )),
13529                ActionDecision::Resume(state.id.clone())
13530            );
13531            let error = crate::resume::validate(home.path(), &state.id)
13532                .unwrap_err()
13533                .to_string();
13534            assert!(!error.contains("review budget exhausted"), "{error}");
13535            assert!(
13536                error.contains(if review_rounds == 0 {
13537                    "review is disabled"
13538                } else {
13539                    "gate already ran"
13540                }),
13541                "{error}"
13542            );
13543
13544            // An unexecuted gate still has work to do with or without reviews.
13545            state.gate_ran = false;
13546            state.gate.clear();
13547            assert!(!exhausted_review_budget(&state));
13548            assert_eq!(
13549                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
13550                Some(state.id)
13551            );
13552        }
13553    }
13554
13555    #[test]
13556    fn sequencer_resource_resume_keeps_the_reserved_run_after_review_exhaustion() {
13557        let home = tempfile::tempdir().unwrap();
13558        let mut state = run_state(RunStatus::Blocked);
13559        state.config.graph.review_rounds = 1;
13560        let mut unresolved = review_round(1);
13561        unresolved.blocking = 1;
13562        unresolved.e2e.push(crate::run::CommandOutcome {
13563            command: "verify".into(),
13564            code: Some(1),
13565            output_tail: "previous verification failed".into(),
13566            duration_ms: 0,
13567            resource_blocked: false,
13568            ..Default::default()
13569        });
13570        state.reviews.push(unresolved);
13571        state.base_sync = Some(crate::run::BaseSync {
13572            tip: "base".into(),
13573            behind: 1,
13574            attempts: 0,
13575            conflict: None,
13576            already_in: None,
13577        });
13578        state.reserve_base_operation("winner", "base");
13579        state.resource_block = Some(crate::run::ResourceBlock {
13580            cause: crate::run::ResourceBlockCause::Other,
13581            node: "rebase".into(),
13582            kind: crate::rebase::SEQUENCER_INFRASTRUCTURE.into(),
13583            detail: "recording exec failed".into(),
13584            at: jiff::Timestamp::now(),
13585        });
13586        state.save_under(home.path()).unwrap();
13587        assert_eq!(
13588            crate::resume::validate(home.path(), &state.id).unwrap().id,
13589            state.id
13590        );
13591        assert_eq!(
13592            crate::repair_budget::legacy::classify(&state, "winner", "base").class,
13593            crate::repair_budget::legacy::Class::SequencerInfrastructure
13594        );
13595        state.finish_base_operation(None);
13596        state.save_under(home.path()).unwrap();
13597        assert!(crate::resume::validate(home.path(), &state.id).is_err());
13598    }
13599
13600    #[test]
13601    fn resource_blocked_verification_resumes_the_same_run() {
13602        for (kind, stage) in [
13603            ("cache", "clean"),
13604            ("coordination", "clean"),
13605            ("cache", "review-e2e"),
13606            ("coordination", "no-reviews"),
13607            ("coordination", "handoff"),
13608        ] {
13609            let home = tempfile::tempdir().unwrap();
13610            let mut state = run_state(RunStatus::Blocked);
13611            state.config.graph.review_rounds = 1;
13612            let mut review = review_round(1);
13613            review.clean = true;
13614            state.reviews = vec![review];
13615            if stage == "review-e2e" {
13616                let review = &mut state.reviews[0];
13617                review.clean = false;
13618                review.blocking = 1;
13619                review.e2e = vec![crate::run::CommandOutcome {
13620                    command: "verify".into(),
13621                    code: None,
13622                    output_tail: "resource wait expired".into(),
13623                    duration_ms: 0,
13624                    resource_blocked: true,
13625                    ..Default::default()
13626                }];
13627            } else if stage == "no-reviews" {
13628                state.config.graph.review_rounds = 0;
13629                state.reviews.clear();
13630            } else if stage == "handoff" {
13631                // A completed final verification can hand off to the gate
13632                // even when the review still carries contested findings.
13633                let review = &mut state.reviews[0];
13634                review.clean = false;
13635                review.blocking = 1;
13636                review.e2e = vec![crate::run::CommandOutcome {
13637                    command: "verify".into(),
13638                    code: Some(0),
13639                    output_tail: String::new(),
13640                    duration_ms: 0,
13641                    resource_blocked: false,
13642                    ..Default::default()
13643                }];
13644            }
13645            state.gate_ran = false;
13646            state.resource_block = Some(crate::run::ResourceBlock {
13647                cause: crate::run::ResourceBlockCause::Other,
13648                node: if stage == "review-e2e" {
13649                    "review"
13650                } else {
13651                    "gate"
13652                }
13653                .into(),
13654                kind: kind.into(),
13655                detail: "resource wait expired".into(),
13656                at: jiff::Timestamp::now(),
13657            });
13658            state.save_under(home.path()).unwrap();
13659            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13660            assert!(!exhausted_review_budget(&state));
13661            let mut task = held_task_with(&state.id);
13662            task.release();
13663            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13664            assert_eq!(
13665                choose_starter(None, false, unfinished.as_deref()),
13666                Starter::Resume(state.id.clone())
13667            );
13668            let question = action_question(&state.id, resume_action(&state.id));
13669            assert_eq!(
13670                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13671                    state.clone()
13672                )),
13673                ActionDecision::Resume(state.id.clone())
13674            );
13675            assert_eq!(
13676                crate::resume::validate(home.path(), &state.id).unwrap().id,
13677                state.id
13678            );
13679            let queue = Queue::at(home.path().join("queue"));
13680            let mut controlled = Task::new(
13681                "resume verification".into(),
13682                state.instruction.clone(),
13683                state.repo.clone(),
13684                Source::Agent {
13685                    run: "talk".into(),
13686                    node: crate::queue::CHAT_NODE.into(),
13687                },
13688            );
13689            controlled.runs.push(state.id.clone());
13690            controlled.hold_machine(Some("verification resource unavailable".into()));
13691            queue.put(&mut controlled).unwrap();
13692            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13693            assert_eq!(resumed.status, TaskStatus::Queued);
13694            assert_eq!(
13695                resumed.resume_override.unwrap().pinned_run,
13696                Some(state.id.clone())
13697            );
13698            assert_eq!(resumed.attempts, 0);
13699
13700            // A genuinely unresolved final review still exhausts the budget.
13701            state.config.graph.review_rounds = 1;
13702            let mut unresolved = review_round(1);
13703            unresolved.blocking = 1;
13704            state.reviews = vec![unresolved];
13705            state.resource_block = None;
13706            state.save_under(home.path()).unwrap();
13707            assert!(exhausted_review_budget(&state));
13708            assert!(crate::resume::validate(home.path(), &state.id).is_err());
13709        }
13710    }
13711
13712    #[tokio::test]
13713    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
13714        if !crate::standalone_test(
13715            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
13716        ) {
13717            return;
13718        }
13719        let home = tempfile::tempdir().unwrap();
13720        let mut owner = stopped_public_run(RunStatus::Blocked);
13721        owner.save_under(home.path()).unwrap();
13722        let history = vec![owner.id.clone()];
13723        let repo = owner.repo.clone();
13724        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
13725        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
13726        let initial =
13727            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
13728        assert!(
13729            initial.is_pending(),
13730            "a busy record must not hold or resume the task"
13731        );
13732        owner.retired_to = Some("20260101-000001-bbbb".into());
13733        owner.save_under(home.path()).unwrap();
13734        drop(lock);
13735        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
13736            .await
13737            .expect("ownership lock released")
13738            .expect("read settled owner");
13739        assert!(
13740            result.is_none(),
13741            "the retired owner must not be resumed from a stale read"
13742        );
13743    }
13744
13745    #[tokio::test]
13746    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
13747        if !crate::standalone_test(
13748            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
13749        ) {
13750            return;
13751        }
13752        let home = tempfile::tempdir().unwrap();
13753        let mut owner = stopped_public_run(RunStatus::Blocked);
13754        let repo = tempfile::tempdir().unwrap();
13755        crate::git::git(repo.path(), &["init"]).await.unwrap();
13756        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
13757        owner.id = "20260101-000000-aaaa".into();
13758        owner.save_under(home.path()).unwrap();
13759        let mut successor = run_state(RunStatus::Blocked);
13760        successor.id = "20260101-000001-bbbb".into();
13761        successor.save_under(home.path()).unwrap();
13762        let runs = vec![owner.id.clone(), successor.id.clone()];
13763        assert_eq!(
13764            public_resume_owner(home.path(), &runs, &owner.repo)
13765                .await
13766                .unwrap()
13767                .unwrap()
13768                .id,
13769            owner.id
13770        );
13771        let subdir = owner.repo.join("nested");
13772        std::fs::create_dir(&subdir).unwrap();
13773        assert_eq!(
13774            public_resume_owner(home.path(), &runs, &subdir)
13775                .await
13776                .unwrap()
13777                .unwrap()
13778                .id,
13779            owner.id
13780        );
13781        #[cfg(unix)]
13782        {
13783            let alias = home.path().join("repo-alias");
13784            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
13785            assert_eq!(
13786                public_resume_owner(home.path(), &runs, &alias.join("nested"))
13787                    .await
13788                    .unwrap()
13789                    .unwrap()
13790                    .id,
13791                owner.id
13792            );
13793        }
13794        let different = tempfile::tempdir().unwrap();
13795        crate::git::git(different.path(), &["init"]).await.unwrap();
13796        assert!(
13797            public_resume_owner(home.path(), &runs, different.path())
13798                .await
13799                .is_err()
13800        );
13801        std::fs::remove_file(
13802            home.path()
13803                .join("runs")
13804                .join(&successor.id)
13805                .join("run.json"),
13806        )
13807        .unwrap();
13808        assert!(
13809            public_resume_owner(home.path(), &runs, &owner.repo)
13810                .await
13811                .is_err()
13812        );
13813    }
13814
13815    #[test]
13816    fn an_ordinary_release_keeps_a_resumable_run_available() {
13817        let mut released = task();
13818        released.start("stalled-run".to_owned());
13819        released.release();
13820        let unfinished = (!released.fresh_start)
13821            .then(|| Some("stalled-run".to_owned()))
13822            .flatten();
13823        assert_eq!(
13824            choose_starter(None, false, unfinished.as_deref()),
13825            Starter::Resume("stalled-run".to_owned()),
13826            "manual release must preserve the normal resume path"
13827        );
13828    }
13829
13830    #[test]
13831    fn resume_refusals_explain_admission_without_changing_task_or_run() {
13832        use crate::handover::{ResumeRefusal, resume_refusal_under};
13833        let home = tempfile::tempdir().unwrap();
13834        let mut exhausted = run_state(RunStatus::Blocked);
13835        exhausted.driver_exited = true;
13836        exhausted.config.graph.review_rounds = 3;
13837        exhausted.reviews = (1..=3).map(review_round).collect();
13838        for refusal in [
13839            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
13840            ResumeRefusal::Status(RunStatus::Ready),
13841            ResumeRefusal::Released("20261022-000000-aaaa".into()),
13842            ResumeRefusal::Retired("retirement-successor".into()),
13843            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
13844        ] {
13845            let mut state = exhausted.clone();
13846            let expected = match refusal {
13847                ResumeRefusal::Status(_) => {
13848                    state.status = RunStatus::Ready;
13849                    "status `ready`"
13850                }
13851                ResumeRefusal::Released(ref target) => {
13852                    state.released_to = Some(target.clone());
13853                    "execution was released"
13854                }
13855                ResumeRefusal::Retired(ref target) => {
13856                    state.retired_to = Some(target.clone());
13857                    "execution was retired"
13858                }
13859                ResumeRefusal::OwnershipTransferred(ref target) => {
13860                    state.pr_taken_over_by = Some(target.clone());
13861                    "PR ownership was transferred"
13862                }
13863                _ => "review budget exhausted (3/3 rounds used)",
13864            };
13865            assert_eq!(
13866                resume_refusal_under(&state, Some(home.path())),
13867                Some(refusal.clone())
13868            );
13869            assert_eq!(
13870                refusal.successor(),
13871                state
13872                    .released_to
13873                    .as_deref()
13874                    .or(state.retired_to.as_deref())
13875                    .or(state.pr_taken_over_by.as_deref())
13876            );
13877            state.save_under(home.path()).unwrap();
13878            let queue = Queue::at(home.path().join("queue"));
13879            let mut task = Task::new(
13880                "retained implementation".into(),
13881                state.instruction.clone(),
13882                state.repo.clone(),
13883                Source::Agent {
13884                    run: "talk".into(),
13885                    node: crate::queue::CHAT_NODE.into(),
13886                },
13887            );
13888            task.runs.push(state.id.clone());
13889            task.hold_machine(Some("stopped".into()));
13890            queue.put(&mut task).unwrap();
13891            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
13892            let before_run = serde_json::to_value(&state).unwrap();
13893            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
13894                .unwrap_err()
13895                .to_string();
13896            assert!(error.contains(expected), "{error}");
13897            assert!(!error.contains("only a stalled or blocked"), "{error}");
13898            if matches!(refusal, ResumeRefusal::Status(_)) {
13899                assert!(
13900                    error.contains("is final; there is nothing left to resume"),
13901                    "{error}"
13902                );
13903            }
13904            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
13905                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
13906                assert!(error.contains("review-only successor with a new review budget"));
13907                assert!(error.contains("does not resume this run"));
13908            }
13909            for target in [
13910                &state.released_to,
13911                &state.retired_to,
13912                &state.pr_taken_over_by,
13913            ]
13914            .into_iter()
13915            .flatten()
13916            {
13917                let short = if state.retired_to.as_ref() == Some(target) {
13918                    target.as_str()
13919                } else {
13920                    crate::run::short_of(target)
13921                };
13922                assert!(
13923                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
13924                    "{error}"
13925                );
13926                if short != target {
13927                    assert!(!error.contains(target), "full successor id leaked: {error}");
13928                }
13929            }
13930            assert_eq!(
13931                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
13932                before_task
13933            );
13934            assert_eq!(
13935                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
13936                    .unwrap(),
13937                before_run
13938            );
13939            let question = action_question(&state.id, resume_action(&state.id));
13940            for phrases in [&PHRASES_EN, &PHRASES_JA] {
13941                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
13942                    RunState::load_under(id, home.path())
13943                });
13944                let ActionDecision::Refuse(detail) = decision else {
13945                    panic!(
13946                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
13947                        state.id,
13948                        home.path().display()
13949                    );
13950                };
13951                assert!(detail.contains(expected), "{detail}");
13952            }
13953        }
13954        // Preserve predicate ordering, while keeping every recorded destination visible.
13955        exhausted.status = RunStatus::Ready;
13956        exhausted.released_to = Some("released".into());
13957        exhausted.retired_to = Some("retired".into());
13958        exhausted.pr_taken_over_by = Some("owner".into());
13959        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
13960        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
13961        let detail = reason.diagnostic(&exhausted);
13962        for target in ["released", "retired", "owner"] {
13963            assert!(detail.contains(&format!("magi show {target}")));
13964        }
13965    }
13966
13967    #[test]
13968    fn resume_action_ignores_question_checkpoints_in_another_home() {
13969        crate::run::pin_test_home();
13970        let home = tempfile::tempdir().unwrap();
13971        let mut state = run_state(RunStatus::Blocked);
13972        // The private directory reserves this fixture's identity even while
13973        // other tests write questions into the process-wide store.
13974        state.id = format!(
13975            "resume-context-{}",
13976            home.path().file_name().unwrap().to_str().unwrap()
13977        );
13978        state.driver_exited = true;
13979        state.config.graph.review_rounds = 1;
13980        state.reviews = vec![review_round(1)];
13981        state.save_under(home.path()).unwrap();
13982        let task = held_task_with(&state.id);
13983        let answer = action_question(&state.id, resume_action(&state.id));
13984        let mut checkpoint = approval_question(&state.id);
13985        let foreign = Questions::open();
13986        foreign.put(&mut checkpoint).unwrap();
13987        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
13988        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13989            RunState::load_under(id, home.path())
13990        });
13991        let matching: Vec<_> = foreign
13992            .list()
13993            .into_iter()
13994            .filter(|q| q.run == state.id && q.status.open())
13995            .collect();
13996        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
13997        assert!(
13998            matches!(decision, ActionDecision::Refuse(_)),
13999            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
14000            state.id,
14001            home.path().display(),
14002            crate::run::test_home().display()
14003        );
14004        assert_eq!(
14005            refusal,
14006            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
14007        );
14008        let local = Questions::at(home.path().join("questions"));
14009        for status in [
14010            ask::QuestionStatus::Open,
14011            ask::QuestionStatus::Answered,
14012            ask::QuestionStatus::Abandoned,
14013        ] {
14014            let mut question = checkpoint.clone();
14015            match status {
14016                ask::QuestionStatus::Open => {}
14017                ask::QuestionStatus::Answered => {
14018                    question
14019                        .answer(ask::Answer::Choice(question.choices[0].clone()))
14020                        .unwrap();
14021                }
14022                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
14023            }
14024            local.put(&mut question).unwrap();
14025            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
14026                RunState::load_under(id, home.path())
14027            });
14028            if status.open() {
14029                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
14030            } else {
14031                assert!(
14032                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
14033                    "status={status:?}, decision={decision:?}"
14034                );
14035            }
14036        }
14037    }
14038
14039    #[test]
14040    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
14041        let home = tempfile::tempdir().unwrap();
14042        let mut state = run_state(RunStatus::Stalled);
14043        state.id = format!(
14044            "resume-driver-{}",
14045            home.path().file_name().unwrap().to_str().unwrap()
14046        );
14047        state.driver_claimed = Some(false);
14048        state.save_under(home.path()).unwrap();
14049        let task = held_task_with(&state.id);
14050        let question = action_question(&state.id, resume_action(&state.id));
14051        let decide = || {
14052            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
14053                RunState::load_under(id, home.path())
14054            })
14055        };
14056        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
14057        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
14058        assert_eq!(
14059            decide(),
14060            ActionDecision::Refuse("run already has a live driver".into())
14061        );
14062        drop(lease);
14063        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
14064    }
14065
14066    #[test]
14067    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
14068        let home = tempfile::tempdir().unwrap();
14069        let mut state = run_state(RunStatus::Blocked);
14070        state.driver_exited = true;
14071        state.config.graph.review_rounds = 1;
14072        state.reviews = vec![review_round(1)];
14073        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
14074        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
14075            let mut saved = state.clone();
14076            match checkpoint {
14077                "publication" => saved.pr_publication_pending = true,
14078                "approval" => {
14079                    saved.land_approval = Some(crate::run::LandApproval {
14080                        question: "approval".into(),
14081                        head: "head".into(),
14082                    })
14083                }
14084                "armed" => saved.land_armed_head = Some("head".into()),
14085                "landing" => saved.status = RunStatus::Landing,
14086                _ => {
14087                    let mut question = ask::Question::new(
14088                        saved.id.clone(),
14089                        "review".into(),
14090                        "review-1".into(),
14091                        "continue?".into(),
14092                        String::new(),
14093                        vec!["continue".into()],
14094                    );
14095                    ask::Questions::at(home.path().join("questions"))
14096                        .put(&mut question)
14097                        .unwrap();
14098                }
14099            }
14100            saved.save_under(home.path()).unwrap();
14101            assert!(
14102                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
14103                "{checkpoint}"
14104            );
14105            assert!(
14106                crate::resume::validate(home.path(), &saved.id).is_ok(),
14107                "{checkpoint}"
14108            );
14109        }
14110    }
14111
14112    #[test]
14113    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
14114        let mut state = run_state(RunStatus::Blocked);
14115        state.config.graph.review_rounds = 3;
14116        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
14117        assert!(exhausted_review_budget(&state));
14118
14119        // One round still unused: resuming can still ask a reviewer something.
14120        state.reviews.pop();
14121        assert!(!exhausted_review_budget(&state));
14122
14123        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
14124        // count: only a `Blocked` run re-enters the review loop on resume.
14125        let mut stalled = run_state(RunStatus::Stalled);
14126        stalled.config.graph.review_rounds = 1;
14127        stalled.reviews = vec![review_round(1)];
14128        assert!(!exhausted_review_budget(&stalled));
14129    }
14130
14131    fn review_round(round: usize) -> crate::run::ReviewRound {
14132        crate::run::ReviewRound {
14133            round,
14134            head: "deadbeef".to_owned(),
14135            verified_head: None,
14136            verified_at: None,
14137            reviews: Vec::new(),
14138            e2e: Vec::new(),
14139            verify_retried: false,
14140            e2e_deferred: false,
14141            e2e_defer_reason: None,
14142            fix: None,
14143            blocking: 0,
14144            answered: 1,
14145            expected: 1,
14146            clean: false,
14147            progressed: true,
14148            vote_split: false,
14149            reconsideration: Vec::new(),
14150            verdict: None,
14151        }
14152    }
14153
14154    #[test]
14155    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
14156        let mut run = RunState::new(
14157            PathBuf::from("/repo"),
14158            "main".to_owned(),
14159            "abc1234def".to_owned(),
14160            "add retries".to_owned(),
14161            Config::default(),
14162        );
14163        run.status = RunStatus::Judging;
14164        run.parked = true;
14165        let mut task = Task::new(
14166            "add retries".to_owned(),
14167            "add retries".to_owned(),
14168            PathBuf::from("/repo"),
14169            crate::queue::Source::Human,
14170        );
14171        task.status = TaskStatus::Failed;
14172        task.runs = vec![run.id.clone()];
14173        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
14174        assert!(with(&task, &run), "parked after judging is the case");
14175        let mut parked_task = task.clone();
14176        parked_task.status = TaskStatus::Parked;
14177        assert!(with(&parked_task, &run), "the Parked status is the case");
14178
14179        let mut not_parked = run.clone();
14180        not_parked.parked = false;
14181        not_parked.status = RunStatus::Stalled;
14182        assert!(!with(&task, &not_parked), "a stall is the conductor's");
14183
14184        let mut fresh = task.clone();
14185        fresh.fresh_start = true;
14186        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
14187
14188        let mut review = task.clone();
14189        review.review_branch = Some("magi/x/A".to_owned());
14190        assert!(!with(&review, &run), "review is ranked before resume");
14191
14192        let mut held = task.clone();
14193        held.status = TaskStatus::Held;
14194        assert!(!with(&held, &run), "a hold stays visible to the conductor");
14195
14196        let mut released = run.clone();
14197        released.released_to = Some("20260901-000000-new1".to_owned());
14198        assert!(!with(&task, &released), "nothing left to resume into");
14199
14200        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
14201            "unreadable"
14202        )));
14203    }
14204
14205    #[test]
14206    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
14207        let mut released = RunState::new(
14208            PathBuf::from("/repo"),
14209            "main".to_owned(),
14210            "abc1234def".to_owned(),
14211            "add retries".to_owned(),
14212            Config::default(),
14213        );
14214        released.status = RunStatus::Blocked;
14215        assert_eq!(
14216            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
14217            Some(released.id.clone())
14218        );
14219        released.released_to = Some("20260901-000000-new1".to_owned());
14220        assert_eq!(
14221            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
14222            None,
14223            "there is nothing left to resume it into"
14224        );
14225    }
14226
14227    #[test]
14228    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
14229        // Mirrors the failure this exists to close: a task's last run ended
14230        // `Blocked` with the review budget spent, `crate::conduct` chose
14231        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
14232        // evidence), and without this check `attempt` would go on treating
14233        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
14234        // review loop iterates zero times over an already-spent budget, so
14235        // the resumed run settles right back to `Blocked` having asked nobody
14236        // anything, and `Requeue`'s promised fresh competition never happens.
14237        let mut exhausted = RunState::new(
14238            PathBuf::from("/repo"),
14239            "main".to_owned(),
14240            "abc1234def".to_owned(),
14241            "add retries".to_owned(),
14242            Config::default(),
14243        );
14244        exhausted.status = RunStatus::Blocked;
14245        exhausted.config.graph.review_rounds = 1;
14246        exhausted.reviews = vec![review_round(1)];
14247
14248        assert_eq!(
14249            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
14250            None,
14251            "an exhausted `Blocked` run must not be offered as resumable"
14252        );
14253
14254        // A `Blocked` run with rounds still unused is genuinely worth
14255        // resuming, and must still be found.
14256        let mut has_budget_left = RunState::new(
14257            PathBuf::from("/repo"),
14258            "main".to_owned(),
14259            "abc1234def".to_owned(),
14260            "add retries".to_owned(),
14261            Config::default(),
14262        );
14263        has_budget_left.status = RunStatus::Blocked;
14264        has_budget_left.config.graph.review_rounds = 3;
14265        has_budget_left.reviews = vec![review_round(1)];
14266
14267        assert_eq!(
14268            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
14269                Ok(has_budget_left.clone())
14270            }),
14271            Some(has_budget_left.id.clone())
14272        );
14273    }
14274
14275    #[test]
14276    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
14277        let mut run = RunState::new(
14278            PathBuf::from("/repo"),
14279            "main".to_owned(),
14280            "abc1234def".to_owned(),
14281            "add retries".to_owned(),
14282            Config::default(),
14283        );
14284        run.status = RunStatus::Blocked;
14285        run.config.graph.review_rounds = 1;
14286        run.reviews = vec![review_round(1)];
14287        run.pr_publication_pending = true;
14288        assert_eq!(
14289            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
14290            Some(run.id.clone()),
14291            "a spent review budget must not turn a failed publication into a re-competition"
14292        );
14293    }
14294
14295    #[test]
14296    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
14297        let mut task = Task::new(
14298            "recover work".into(),
14299            "recover work".into(),
14300            PathBuf::from("/repo"),
14301            crate::queue::Source::Human,
14302        );
14303        let mut history = std::collections::BTreeMap::new();
14304        for index in 0..8 {
14305            let mut run = run_state(RunStatus::Blocked);
14306            run.id = format!("20260101-000000-{index:04}");
14307            run.base_commit = format!("upstream-{index}");
14308            // Seven empty newer attempts must not erase the old recovery owner.
14309            if index > 0 {
14310                run.candidates.clear();
14311            }
14312            task.runs.extend([run.id.clone(), run.id.clone()]);
14313            history.insert(run.id.clone(), run);
14314            task.requeue();
14315        }
14316        let check = |task: &Task, starter: &Starter, limit| {
14317            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
14318        };
14319        assert!(
14320            check(&task, &Starter::Start, 8)
14321                .unwrap()
14322                .contains("8 unretired")
14323        );
14324        assert!(check(&task, &Starter::Start, 9).is_none());
14325        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
14326        task.release_operator("owner", None);
14327        assert_eq!(task.attempts, 0);
14328        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14329        assert!(check(&restored, &Starter::Start, 8).is_some());
14330        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
14331        assert!(check(&restored, &Starter::Start, 0).is_none());
14332    }
14333
14334    #[test]
14335    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
14336        let tmp = tempfile::tempdir().unwrap();
14337        let mut task = Task::new(
14338            "recover selected PR".into(),
14339            "preserve implementation".into(),
14340            tmp.path().join("repo"),
14341            crate::queue::Source::Human,
14342        );
14343        let mut failed = run_state(RunStatus::Failed);
14344        failed.id = "20260101-000000-fail".into();
14345        failed.candidates.clear();
14346        failed.prep_complete = Some(false);
14347        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
14348        failed.startup = Some(crate::run::Startup {
14349            kind: "pr-recovery".into(),
14350            branch: Some("selected-public-head".into()),
14351            stage: "worktree-setup".into(),
14352            complete: false,
14353            failure: Some("setup modified a tracked file and failed".into()),
14354        });
14355        // Setup may fail before a candidate is recorded; its dirty worktree
14356        // still needs protection and consumes the independent retained bound.
14357        let worktree = failed.worktree_root().join("under-review");
14358        std::fs::create_dir_all(&worktree).unwrap();
14359        let retained_edit = worktree.join("implementation");
14360        std::fs::write(&retained_edit, "retained setup edit").unwrap();
14361        task.record_startup_failure(crate::run::StartupFailure {
14362            run: failed.id.clone(),
14363            stage: "worktree-setup".into(),
14364        });
14365        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14366        assert!(task.runs.is_empty() && task.passes.is_empty());
14367        assert_eq!(task.attempts, 0);
14368        let starter = Starter::Review("selected-public-head".into());
14369        assert!(
14370            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
14371                .unwrap()
14372                .contains("1 unretired")
14373        );
14374        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
14375        assert!(
14376            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
14377                .unwrap()
14378                .contains("Cannot verify")
14379        );
14380        // Older or mixed writers can link the same reservation in both lists.
14381        let mut mixed = task.clone();
14382        mixed.runs.push(failed.id.clone());
14383        mixed
14384            .startup_failures
14385            .push(task.startup_failures[0].clone());
14386        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
14387        failed.retired_to = Some("verified-recovery-owner".into());
14388        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
14389        assert!(
14390            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
14391                panic!("resuming the existing owner must not allocate a new attempt")
14392            })
14393            .is_none()
14394        );
14395        assert_eq!(
14396            std::fs::read_to_string(retained_edit).unwrap(),
14397            "retained setup edit"
14398        );
14399        assert!(task.runs.is_empty() && task.passes.is_empty());
14400        assert_eq!(task.attempts, 0);
14401    }
14402
14403    #[test]
14404    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
14405        let mut task = Task::new(
14406            "recover work".into(),
14407            "recover work".into(),
14408            PathBuf::from("/repo"),
14409            crate::queue::Source::Human,
14410        );
14411        let mut run = run_state(RunStatus::Superseded);
14412        run.candidates.clear();
14413        task.runs.push(run.id.clone());
14414        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
14415        run.retired_to = Some("authority".into());
14416        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14417        run.retired_to = None;
14418        run.released_to = Some("authority".into());
14419        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14420        assert!(
14421            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
14422                .unwrap()
14423                .contains("Cannot verify")
14424        );
14425        // Resuming an existing owner needs no new inventory or worktree budget.
14426        assert!(
14427            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
14428                panic!("resume must not load historical attempts")
14429            })
14430            .is_none()
14431        );
14432    }
14433
14434    #[test]
14435    fn retired_resume_requires_a_valid_same_repository_authority() {
14436        let mut source = run_state(RunStatus::Blocked);
14437        let mut empty = run_state(RunStatus::Blocked);
14438        empty.retired_to = Some(source.id.clone());
14439        let runs = vec![source.id.clone(), empty.id.clone()];
14440        let resolve = |source: &RunState, empty: &RunState| {
14441            unfinished_run_with(&runs, "fixture", |id| {
14442                if id == source.id {
14443                    Ok(source.clone())
14444                } else if id == empty.id {
14445                    Ok(empty.clone())
14446                } else {
14447                    bail!("unreadable authority")
14448                }
14449            })
14450        };
14451        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
14452        assert_eq!(
14453            choose_starter(None, false, resolve(&source, &empty).as_deref()),
14454            Starter::Resume(source.id.clone())
14455        );
14456        source.retired_to = Some(empty.id.clone());
14457        assert!(
14458            resolve(&source, &empty).is_none(),
14459            "cycles do not revive obsolete runs"
14460        );
14461        source.retired_to = None;
14462        source.repo = PathBuf::from("/another-repository");
14463        assert!(resolve(&source, &empty).is_none());
14464        source.repo = empty.repo.clone();
14465        source.released_to = Some("later".into());
14466        assert!(resolve(&source, &empty).is_none());
14467        empty.retired_to = Some("unlisted-run".into());
14468        assert!(resolve(&source, &empty).is_none());
14469    }
14470
14471    #[test]
14472    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
14473        // A task whose history holds an *older* run that still looks
14474        // resumable (say, a competition `Runner::review` was started
14475        // alongside after that older run went `Stalled`) and a *newest* run
14476        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
14477        // on this task must mean a fresh competition — falling back to the
14478        // stale, superseded `Stalled` run instead would resurrect history
14479        // nothing asked to revisit and silently defeat the requeue.
14480        let mut older_stalled = RunState::new(
14481            PathBuf::from("/repo"),
14482            "main".to_owned(),
14483            "abc1234def".to_owned(),
14484            "add retries".to_owned(),
14485            Config::default(),
14486        );
14487        older_stalled.status = RunStatus::Stalled;
14488
14489        let mut newest_exhausted = RunState::new(
14490            PathBuf::from("/repo"),
14491            "main".to_owned(),
14492            "abc1234def".to_owned(),
14493            "add retries".to_owned(),
14494            Config::default(),
14495        );
14496        newest_exhausted.status = RunStatus::Blocked;
14497        newest_exhausted.config.graph.review_rounds = 1;
14498        newest_exhausted.reviews = vec![review_round(1)];
14499
14500        assert_eq!(
14501            unfinished_run_with(
14502                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
14503                "t",
14504                |_| Ok(newest_exhausted.clone())
14505            ),
14506            None,
14507            "the newest run is exhausted, so nothing here is worth resuming - \
14508             least of all the older, already-superseded run"
14509        );
14510    }
14511
14512    #[test]
14513    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
14514        assert_eq!(
14515            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
14516                Err(anyhow::anyhow!("fixture is absent"))
14517            }),
14518            None
14519        );
14520    }
14521
14522    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
14523        let mut q = ask::Question::new(
14524            run.to_owned(),
14525            "implement".to_owned(),
14526            "impl-A".to_owned(),
14527            "continue?".to_owned(),
14528            String::new(),
14529            vec!["resume で続行する".to_owned(), "other".to_owned()],
14530        );
14531        q.actions.insert("resume で続行する".to_owned(), action);
14532        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
14533            .unwrap();
14534        q
14535    }
14536
14537    fn held_task_with(run: &str) -> Task {
14538        let mut t = task();
14539        t.runs = vec![run.to_owned()];
14540        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
14541        t
14542    }
14543
14544    fn resume_action(run: &str) -> ask::ChoiceAction {
14545        ask::ChoiceAction::Resume { run: run.into() }
14546    }
14547
14548    #[test]
14549    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
14550        let home = crate::run::test_home();
14551        for parked in [false, true] {
14552            let mut t = task();
14553            t.start("A".into());
14554            t.start("B".into());
14555            assert_eq!(t.runs, vec!["A", "B"]);
14556            t.start("A".into());
14557            let mut resumed = run_state(RunStatus::Blocked);
14558            resumed.id = "A".into();
14559            resumed.parked = parked;
14560            resumed.driver_exited = true;
14561            t.hold_machine(Some("resumed run stopped".into()));
14562            let q = action_question("A", resume_action("A"));
14563            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14564            assert_eq!(
14565                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
14566                    assert_eq!(id, "A");
14567                    Ok(resumed.clone())
14568                }),
14569                ActionDecision::Resume("A".into())
14570            );
14571            assert_eq!(
14572                action_standing(&t, &action_question("B", resume_action("B"))),
14573                ActionStanding::Stale
14574            );
14575            t.release_operator("cli", None);
14576            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
14577                assert_eq!(id, "A");
14578                Ok(resumed.clone())
14579            });
14580            assert_eq!(
14581                choose_starter(None, false, unfinished.as_deref()),
14582                Starter::Resume("A".into())
14583            );
14584            assert_eq!(t.runs, vec!["B", "A"]);
14585        }
14586    }
14587
14588    #[test]
14589    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
14590        let home = crate::run::test_home();
14591        let mut state = crate::land::tests::repair_state(true, true);
14592        state.status = RunStatus::Landing;
14593        state.parked = true;
14594        state.driver_exited = true;
14595        let mut q = ask::Question::new(
14596            state.id.clone(),
14597            land::APPROVAL_NODE.into(),
14598            "land".into(),
14599            "Merge?".into(),
14600            String::new(),
14601            vec![land::APPROVE.into(), land::HOLD.into()],
14602        );
14603        q.id = state.id.clone();
14604        state.land_approval = Some(crate::run::LandApproval {
14605            question: q.id.clone(),
14606            head: "current-head".into(),
14607        });
14608        assert!(land::upgrade_repair_choice(&mut q, &state));
14609        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14610        let mut task = held_task_with(&state.id);
14611        task.status = TaskStatus::Parked;
14612        assert_eq!(
14613            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14614            ActionDecision::Resume(state.id.clone())
14615        );
14616        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14617        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
14618        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
14619        assert_eq!(
14620            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14621            ActionDecision::Resume(state.id.clone()),
14622            "a repair answer newer than the manual hold resumes the existing owner"
14623        );
14624        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14625        for answered_at in [q.answered_at, None] {
14626            let mut older = q.clone();
14627            older.answered_at = answered_at;
14628            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
14629                panic!("a later manual hold must prevent dispatch")
14630            });
14631            let ActionDecision::Refuse(reason) = refused else {
14632                panic!("expected an actionable refusal, got {refused:?}");
14633            };
14634            assert!(reason.contains("later operator decision"));
14635            assert!(reason.contains(&format!("magi task release {}", task.id)));
14636        }
14637        task.operator_decided_at = None;
14638        let mut superseded = state.clone();
14639        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
14640        assert_eq!(
14641            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
14642            ActionDecision::Stale
14643        );
14644        for case in 1..4 {
14645            let mut changed = state.clone();
14646            match case {
14647                1 => changed.status = RunStatus::Blocked,
14648                2 => changed.released_to = Some("new-owner".into()),
14649                _ => changed.land_approval.as_mut().unwrap().head.clear(),
14650            }
14651            assert!(matches!(
14652                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
14653                ActionDecision::Refuse(_)
14654            ));
14655        }
14656        assert!(matches!(
14657            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
14658                "missing owner"
14659            )),
14660            ActionDecision::Refuse(_)
14661        ));
14662        task.runs.push("replacement".into());
14663        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14664        assert_eq!(
14665            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
14666                "old owner must not load"
14667            )),
14668            ActionDecision::Stale
14669        );
14670    }
14671
14672    #[test]
14673    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
14674        let mut state = crate::land::tests::repair_state(true, true);
14675        state.status = RunStatus::Landing;
14676        state.parked = true;
14677        state.driver_exited = true;
14678        let mut q = ask::Question::new(
14679            state.id.clone(),
14680            land::APPROVAL_NODE.into(),
14681            "land".into(),
14682            "Merge?".into(),
14683            String::new(),
14684            vec![land::APPROVE.into(), land::HOLD.into()],
14685        );
14686        q.id = state.id.clone();
14687        state.land_approval = Some(crate::run::LandApproval {
14688            question: q.id.clone(),
14689            head: "current-head".into(),
14690        });
14691        state.save().unwrap();
14692        land::upgrade_repair_choice(&mut q, &state);
14693        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14694        Questions::open().put(&mut q).unwrap();
14695        let tmp = tempfile::tempdir().unwrap();
14696        let queue = Queue::at(tmp.path().join("queue"));
14697        let mut task = held_task_with(&state.id);
14698        task.status = TaskStatus::Parked;
14699        queue.put(&mut task).unwrap();
14700        let empty = Arc::new(tokio::sync::Semaphore::new(0));
14701        let free = Arc::new(tokio::sync::Semaphore::new(1));
14702        assert!(matches!(
14703            claim_dispatch(&queue, &task, false, &empty, &free),
14704            Err(SkipReason::OrdinaryCapacity)
14705        ));
14706        assert!(matches!(
14707            claim_dispatch(&queue, &task, true, &free, &free),
14708            Err(SkipReason::CoolingDown)
14709        ));
14710        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
14711        assert!(claim.permit.is_some());
14712        assert!(matches!(
14713            claim_dispatch(&queue, &task, false, &free, &free),
14714            Err(SkipReason::ClaimUnavailable)
14715        ));
14716        drop(claim);
14717        Questions::open()
14718            .update(&q.id, |q| {
14719                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
14720                Ok(())
14721            })
14722            .unwrap();
14723        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
14724        assert!(claim.permit.is_none());
14725        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
14726    }
14727
14728    #[test]
14729    fn decide_action_resumes_only_the_latest_resumable_run() {
14730        let home = crate::run::test_home();
14731        let t = held_task_with("r1");
14732        let q = action_question("r1", resume_action("r1"));
14733        let load = |s: RunState| move |_: &str| Ok(s);
14734        assert_eq!(
14735            decide_action(
14736                &home,
14737                &t,
14738                &q,
14739                &PHRASES_EN,
14740                load(run_state(RunStatus::Blocked))
14741            ),
14742            ActionDecision::Resume("r1".into())
14743        );
14744        // Not the latest run of the task.
14745        let q_other = action_question("r1", resume_action("r0"));
14746        assert!(matches!(
14747            decide_action(
14748                &home,
14749                &t,
14750                &q_other,
14751                &PHRASES_EN,
14752                load(run_state(RunStatus::Blocked))
14753            ),
14754            ActionDecision::Refuse(_)
14755        ));
14756        // A finished run cannot make progress.
14757        assert!(matches!(
14758            decide_action(
14759                &home,
14760                &t,
14761                &q,
14762                &PHRASES_EN,
14763                load(run_state(RunStatus::Ready))
14764            ),
14765            ActionDecision::Refuse(_)
14766        ));
14767        // A released one either.
14768        let mut released = run_state(RunStatus::Blocked);
14769        released.released_to = Some("elsewhere".into());
14770        assert!(matches!(
14771            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
14772            ActionDecision::Refuse(_)
14773        ));
14774        // Unreadable state is a refusal, never a fresh competition.
14775        assert!(matches!(
14776            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
14777            ActionDecision::Refuse(_)
14778        ));
14779    }
14780
14781    #[test]
14782    fn decide_action_ignores_a_question_about_an_earlier_run() {
14783        let home = crate::run::test_home();
14784        let mut t = held_task_with("r1");
14785        t.runs.push("r2".to_owned());
14786        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14787        assert_eq!(
14788            decide_action(
14789                &home,
14790                &t,
14791                &action_question("r1", ask::ChoiceAction::Done),
14792                &PHRASES_EN,
14793                never
14794            ),
14795            ActionDecision::Stale
14796        );
14797    }
14798
14799    #[test]
14800    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
14801        let home = crate::run::test_home();
14802        let mut t = held_task_with("r1");
14803        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14804        assert_eq!(
14805            decide_action(
14806                &home,
14807                &t,
14808                &action_question("r1", ask::ChoiceAction::Requeue),
14809                &PHRASES_EN,
14810                never
14811            ),
14812            ActionDecision::Requeue
14813        );
14814        let done_q = action_question("r1", ask::ChoiceAction::Done);
14815        assert_eq!(
14816            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14817            ActionDecision::Done
14818        );
14819        t.mark_action_applied(&done_q.id);
14820        assert_eq!(
14821            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14822            ActionDecision::Skip
14823        );
14824
14825        // A plain answer (no action for that label) does nothing.
14826        let mut plain = action_question("r1", ask::ChoiceAction::Done);
14827        plain.actions.clear();
14828        assert_eq!(
14829            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
14830            ActionDecision::Skip
14831        );
14832        // A running task is left alone.
14833        let mut running = held_task_with("r1");
14834        running.status = TaskStatus::Running;
14835        assert_eq!(
14836            decide_action(
14837                &home,
14838                &running,
14839                &action_question("r1", ask::ChoiceAction::Done),
14840                &PHRASES_EN,
14841                never
14842            ),
14843            ActionDecision::Skip
14844        );
14845    }
14846
14847    #[test]
14848    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
14849        crate::run::pin_test_home();
14850        for legacy in [false, true] {
14851            let dir = tempfile::tempdir().unwrap();
14852            let queue = Queue::at(dir.path().join("queue"));
14853            let questions = Questions::at(dir.path().join("questions"));
14854            let run = "20260101-000000-hold";
14855            let mut task = held_task_with(run);
14856            task.status = TaskStatus::Parked;
14857            let mut q = ask::Question::new(
14858                run.into(),
14859                land::APPROVAL_NODE.into(),
14860                "land".into(),
14861                "Repair?".into(),
14862                String::new(),
14863                vec![land::REPAIR.into()],
14864            );
14865            q.actions.insert(land::REPAIR.into(), resume_action(run));
14866            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14867            // Deterministically order the answer before the actual manual hold.
14868            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14869            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
14870            questions.put(&mut q).unwrap();
14871            task.hold_manual(Some("Keep this PR paused".into()));
14872            if legacy {
14873                task.hold_source = None;
14874            }
14875            queue.put(&mut task).unwrap();
14876
14877            apply_task_choice_actions(&queue, &questions, dir.path());
14878            let after = queue.get(&task.id).unwrap();
14879            assert!(after.operator_held());
14880            assert_eq!(after.hold_source, task.hold_source);
14881            assert_eq!(after.operator_decided_at, task.operator_decided_at);
14882            assert_eq!(after.runs, task.runs);
14883            assert_eq!(after.instruction, task.instruction);
14884            assert!(after.resume_override.is_none());
14885            assert!(after.action_applied(&q.id));
14886            let reason = after.hold_reason.as_deref().unwrap();
14887            assert!(reason.starts_with("Keep this PR paused"));
14888            assert!(reason.contains("later operator decision"));
14889            assert!(reason.contains(&format!("magi task release {}", task.id)));
14890
14891            for recovery in [
14892                crate::conduct::Recovery::Review,
14893                crate::conduct::Recovery::Requeue,
14894            ] {
14895                crate::conduct::apply(
14896                    &queue,
14897                    &questions,
14898                    &crate::conduct::Verdict {
14899                        decisions: vec![crate::conduct::Decision {
14900                            id: task.id.clone(),
14901                            recovery: Some(recovery),
14902                            ..Default::default()
14903                        }],
14904                    },
14905                )
14906                .unwrap();
14907            }
14908            // Reconciliation is idempotent, and automatic recovery cannot
14909            // reopen this owner after it observes the rejected repair answer.
14910            apply_task_choice_actions(&queue, &questions, dir.path());
14911            let still_held = queue.get(&task.id).unwrap();
14912            assert!(still_held.operator_held());
14913            assert_eq!(still_held.hold_reason, after.hold_reason);
14914            assert_eq!(still_held.runs, task.runs);
14915            assert!(still_held.review_branch.is_none());
14916            assert!(!still_held.fresh_start);
14917            assert!(queue.next_runnable().is_none());
14918        }
14919    }
14920
14921    #[test]
14922    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
14923        for held in [false, true] {
14924            for retry in [false, true] {
14925                let dir = tempfile::tempdir().unwrap();
14926                let queue = Queue::at(dir.path().join("queue"));
14927                let questions = Questions::at(dir.path().join("questions"));
14928                let home = dir.path().join("home");
14929                let mut t = task();
14930                if held {
14931                    t.hold_machine(Some("driver state unknown".into()));
14932                }
14933                queue.put(&mut t).unwrap();
14934                let verdict = serde_json::from_value(serde_json::json!({
14935                    "decisions": [{
14936                        "id": t.id,
14937                        "question": "Driver state unknown; retry the checks or hold?",
14938                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
14939                        "actions": {
14940                            "daemon: recheck and retry": {"do": "requeue"},
14941                            "daemon: hold the task": {"do": "hold"}
14942                        }
14943                    }]
14944                }))
14945                .unwrap();
14946                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
14947                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14948                let mut q = questions.list().pop().unwrap();
14949                let choice = if retry {
14950                    "daemon: recheck and retry"
14951                } else {
14952                    "daemon: hold the task"
14953                };
14954                assert_eq!(q.actions.len(), 2);
14955                q.answer(ask::Answer::Choice(choice.into())).unwrap();
14956                questions.put(&mut q).unwrap();
14957
14958                // A Web answer does not remove the deputy's fresh lease.
14959                questions.beat(&q.id, ask::WaiterKind::Deputy);
14960                for _ in 0..2 {
14961                    resolve_blockers(&queue, &questions);
14962                    apply_task_choice_actions(&queue, &questions, &home);
14963                    let waiting = queue.get(&t.id).unwrap();
14964                    assert_eq!(waiting.status, TaskStatus::Blocked);
14965                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
14966                    assert!(waiting.answers.is_empty());
14967                    assert!(!waiting.action_applied(&q.id));
14968                    assert!(runnable(&queue).is_empty());
14969                    let free = Arc::new(tokio::sync::Semaphore::new(1));
14970                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
14971                }
14972                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14973
14974                // Releasing the blocker and applying the operation share one save.
14975                resolve_blockers(&queue, &questions);
14976                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14977                apply_task_choice_actions(&queue, &questions, &home);
14978                let after = queue.get(&t.id).unwrap();
14979                assert_eq!(
14980                    after.status,
14981                    if retry {
14982                        TaskStatus::Queued
14983                    } else {
14984                        TaskStatus::Held
14985                    }
14986                );
14987                assert!(after.action_applied(&q.id));
14988                assert_eq!(after.operator_held(), !retry);
14989                assert_eq!(after.answers.len(), 1);
14990
14991                // A later operator decision must not replay this answer.
14992                let mut changed = after;
14993                if retry {
14994                    changed.hold_manual(Some("later hold".into()));
14995                } else {
14996                    changed.release_operator("test", None);
14997                }
14998                let expected = changed.status;
14999                queue.put(&mut changed).unwrap();
15000                apply_task_choice_actions(&queue, &questions, &home);
15001                assert_eq!(queue.get(&t.id).unwrap().status, expected);
15002            }
15003        }
15004    }
15005
15006    #[test]
15007    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
15008        let dir = tempfile::tempdir().unwrap();
15009        let queue = Queue::at(dir.path().join("queue"));
15010        let questions = Questions::at(dir.path().join("questions"));
15011        let home = dir.path().join("home");
15012        let mut state = run_state(RunStatus::Blocked);
15013        state.id = "20260101-000000-act1".to_owned();
15014        state.save_under(&home).unwrap();
15015
15016        let mut t = held_task_with(&state.id);
15017        queue.put(&mut t).unwrap();
15018        let mut q = action_question(&state.id, resume_action(&state.id));
15019        questions.put(&mut q).unwrap();
15020
15021        apply_task_choice_actions(&queue, &questions, &home);
15022        let after = queue.get(&t.id).unwrap();
15023        assert_eq!(after.status, TaskStatus::Queued);
15024        assert!(!after.fresh_start);
15025        assert!(after.action_applied(&q.id));
15026        let pin = after.resume_override.clone().unwrap();
15027        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
15028        assert!(pin.forced);
15029
15030        // Held again later: the same answer does not release it a second time.
15031        let mut again = queue.get(&t.id).unwrap();
15032        again.hold_machine(Some("later".into()));
15033        queue.put(&mut again).unwrap();
15034        apply_task_choice_actions(&queue, &questions, &home);
15035        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15036    }
15037
15038    #[test]
15039    fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
15040        let dir = tempfile::tempdir().unwrap();
15041        let home = dir.path();
15042        let queue = Queue::at(home.join("queue"));
15043        let questions = Questions::at(home.join("questions"));
15044        let mut state = run_state(RunStatus::Blocked);
15045        state.save_under(home).unwrap();
15046        let mut task = held_task_with(&state.id);
15047        queue.put(&mut task).unwrap();
15048        let mut question = action_question(&state.id, ask::ChoiceAction::Done);
15049        questions.put(&mut question).unwrap();
15050
15051        apply_task_choice_actions(&queue, &questions, home);
15052
15053        let after = queue.get(&task.id).unwrap();
15054        assert_eq!(after.status, TaskStatus::Held);
15055        assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
15056        assert_eq!(after.runs, task.runs);
15057        assert!(after.completion_history.is_empty());
15058        assert!(!after.decision_effects.contains_key(&question.id));
15059        assert_eq!(
15060            RunState::load_under(&state.id, home).unwrap().status,
15061            RunStatus::Blocked
15062        );
15063    }
15064
15065    #[test]
15066    fn a_delivered_answer_is_still_acted_on_exactly_once() {
15067        let dir = tempfile::tempdir().unwrap();
15068        let queue = Queue::at(dir.path().join("queue"));
15069        let questions = Questions::at(dir.path().join("questions"));
15070        let home = dir.path().join("home");
15071        let mut state = run_state(RunStatus::Blocked);
15072        state.id = "20260101-000000-act2".to_owned();
15073        state.save_under(&home).unwrap();
15074
15075        let mut t = held_task_with(&state.id);
15076        queue.put(&mut t).unwrap();
15077        let mut q = action_question(&state.id, resume_action(&state.id));
15078        q.answer_delivered = true;
15079        questions.put(&mut q).unwrap();
15080
15081        // Delivered, and the agent then died: the task is still held, so the
15082        // chosen action applies.
15083        apply_task_choice_actions(&queue, &questions, &home);
15084        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
15085        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
15086
15087        // Held again: the same answer does nothing a second time.
15088        let mut again = queue.get(&t.id).unwrap();
15089        again.hold_machine(Some("later".into()));
15090        queue.put(&mut again).unwrap();
15091        apply_task_choice_actions(&queue, &questions, &home);
15092        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15093    }
15094
15095    #[test]
15096    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
15097        let dir = tempfile::tempdir().unwrap();
15098        let queue = Queue::at(dir.path().join("queue"));
15099        let questions = Questions::at(dir.path().join("questions"));
15100        let home = dir.path().join("home");
15101        let mut state = run_state(RunStatus::Blocked);
15102        state.id = "20260101-000000-act3".to_owned();
15103        state.save_under(&home).unwrap();
15104        let mut t = held_task_with(&state.id);
15105        queue.put(&mut t).unwrap();
15106        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
15107        questions.put(&mut q).unwrap();
15108
15109        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
15110        apply_task_choice_actions(&queue, &questions, &home);
15111        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15112
15113        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
15114        apply_task_choice_actions(&queue, &questions, &home);
15115        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
15116    }
15117
15118    #[test]
15119    fn action_standing_tells_the_reasons_apart() {
15120        let mut t = held_task_with("r1");
15121        let q = action_question("r1", ask::ChoiceAction::Requeue);
15122        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
15123        let mut plain = q.clone();
15124        plain.actions.clear();
15125        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
15126
15127        // Applied wins over everything, even a running task.
15128        t.mark_action_applied(&q.id);
15129        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
15130
15131        // A newer attempt running: the old question is Stale, not Busy.
15132        let mut t = held_task_with("r1");
15133        t.start("r2".to_owned());
15134        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
15135        // The same question about the latest run just waits.
15136        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
15137        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
15138        t.status = TaskStatus::Blocked;
15139        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
15140
15141        // A conductor question is keyed by the task, never stale.
15142        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
15143        c.node = crate::conduct::NODE.to_owned();
15144        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
15145        assert!(!ActionStanding::Busy.daemon_owns());
15146    }
15147
15148    #[test]
15149    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
15150        let dir = tempfile::tempdir().unwrap();
15151        let queue = Queue::at(dir.path().join("queue"));
15152        let questions = Questions::at(dir.path().join("questions"));
15153        let home = dir.path().join("home");
15154        // Execution finished before task settlement; Done is not a discard.
15155        let mut state = run_state(RunStatus::Ready);
15156        state.id = "20260101-000000-act4".to_owned();
15157        state.save_under(&home).unwrap();
15158        let mut t = held_task_with(&state.id);
15159        t.status = TaskStatus::Running;
15160        queue.put(&mut t).unwrap();
15161        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
15162        q.cwd = Some(dir.path().display().to_string());
15163        questions.put(&mut q).unwrap();
15164
15165        // While the task runs the daemon will not act, so the waiter still
15166        // delivers the word to the dead asker's seat ...
15167        let running = queue.get(&t.id).unwrap();
15168        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
15169        assert!(matches!(
15170            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
15171            crate::waiter::Action::Deliver(_)
15172        ));
15173        // ... and the daemon waits while the task runs, then applies once.
15174        apply_task_choice_actions(&queue, &questions, &home);
15175        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
15176        let mut back = queue.get(&t.id).unwrap();
15177        back.hold_machine(Some("later".into()));
15178        queue.put(&mut back).unwrap();
15179        apply_task_choice_actions(&queue, &questions, &home);
15180        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
15181        let mut again = queue.get(&t.id).unwrap();
15182        again.hold_machine(Some("again".into()));
15183        queue.put(&mut again).unwrap();
15184        apply_task_choice_actions(&queue, &questions, &home);
15185        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15186    }
15187}