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::{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 decision = decide_action(home, &task, &q, phrases(&language), |id| {
1633            RunState::load_under(id, home)
1634        });
1635        let ran = matches!(
1636            decision,
1637            ActionDecision::Resume(_)
1638                | ActionDecision::Requeue
1639                | ActionDecision::Hold
1640                | ActionDecision::Done
1641        );
1642        if ran && asker_may_still_read(questions, &q, home) {
1643            // The asking process or its seat can still take the word; act
1644            // once it has gone quiet. Bound on the remaining window: the
1645            // check is not atomic with the write below, so an asker that
1646            // takes the word in between (at most one poll, never more than
1647            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1648            // and `Task::actions_applied` under the claim keeps the action to
1649            // one application. The waiter does not deliver an answer that
1650            // carries an action (`waiter::decide_owned`), so it cannot race.
1651            continue;
1652        }
1653        let done = matches!(decision, ActionDecision::Done);
1654        // Resume owes an execution pass; only these task-local effects finish
1655        // in this write. Stale/refused actions never acquire an effect receipt.
1656        let completed = matches!(
1657            decision,
1658            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1659        );
1660        match decision {
1661            ActionDecision::Skip => continue,
1662            ActionDecision::Resume(run) => {
1663                task.release_operator("choice", Some(&q.id));
1664                task.resume_override = Some(crate::queue::OperatorResume {
1665                    question_id: q.id.clone(),
1666                    at: Timestamp::now(),
1667                    conductor_rehold: None,
1668                    forced: true,
1669                    pinned_run: Some(run),
1670                });
1671            }
1672            ActionDecision::Stale => {}
1673            ActionDecision::Requeue => {
1674                task.release_operator("choice-requeue", Some(&q.id));
1675                task.requeue();
1676            }
1677            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1678            ActionDecision::Done => task.succeed(),
1679            ActionDecision::Refuse(why) => {
1680                let _ =
1681                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1682                if task.operator_held() {
1683                    // A rejected answer does not release the operator's hold
1684                    // or reclassify it as recoverable by the conductor.
1685                    task.hold_reason = Some(match task.hold_reason.take() {
1686                        Some(reason) => format!("{reason}\n\n{why}"),
1687                        None => why,
1688                    });
1689                } else {
1690                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1691                    task.hold_machine(Some(why));
1692                }
1693                notices::raise(
1694                    Notice::warn(
1695                        &format!("action:{}", q.id),
1696                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1697                    )
1698                    .link(Link::Task {
1699                        id: task.id.clone(),
1700                    }),
1701                );
1702            }
1703        }
1704        task.mark_action_applied(&q.id);
1705        if completed {
1706            task.decision_effects.insert(
1707                q.id.clone(),
1708                format!("decision: {}", q.resolution().expect("answered action")),
1709            );
1710        }
1711        // The applied id travels with the transition, so a failed save loses
1712        // neither and the answer is acted on at the next poll.
1713        record(queue, &mut task);
1714        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1715            supersede_prior_runs(&task, home);
1716        }
1717        // Delivery is only a note of who has read the answer; the task's own
1718        // mark above is the authority. Best effort.
1719        let _ = questions.update_in(&q.id, &ownership, |r| {
1720            r.answer_delivered = true;
1721            Ok(())
1722        });
1723    }
1724}
1725
1726/// Whether something may still read the answer to `q`: a fresh lease, or the
1727/// asking seat still listed as active in its run (its CLI can outlive the
1728/// `magi ask` that was killed).
1729fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1730    let now = Timestamp::now();
1731    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1732        return true;
1733    }
1734    q.node != crate::conduct::NODE
1735        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1736            s.seats_active()
1737                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1738        })
1739}
1740
1741/// Retire an unanswered conductor question after its task no longer refers to
1742/// it. Conductor questions use the task id in `Question::run`, so run-based
1743/// cleanup cannot observe a manual release or completion.
1744///
1745/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1746/// own question also carries a `run`, and a run id that happens to collide
1747/// with some task's id is not this loop's business — only a conductor
1748/// question actually uses the task id that way. One `Questions::list()` scan
1749/// is taken up front and matched against the in-memory task set, rather than
1750/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1751fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1752    let tasks = queue.list();
1753    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1754    let by_id: std::collections::BTreeMap<&str, &Task> =
1755        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1756    let referenced: Vec<&str> = tasks
1757        .iter()
1758        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1759        .collect();
1760
1761    for mut question in questions.list_for_effects_in(&ownership) {
1762        if !question.status.open()
1763            || question.node != crate::conduct::NODE
1764            || questions.held_reply_in(&question.id, &ownership)
1765        {
1766            continue;
1767        }
1768        // Keep questions a task still names, including when the reference
1769        // moved to a dependent task.
1770        // Preserve even ambiguous references: retiring a possibly referenced
1771        // question is unsafe until the operator disambiguates it.
1772        if referenced
1773            .iter()
1774            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1775        {
1776            continue;
1777        }
1778        let Some(task) = by_id.get(question.run.as_str()) else {
1779            continue;
1780        };
1781        question.abandon(format!(
1782            "task {} no longer waits for this answer",
1783            task.short()
1784        ));
1785        if let Err(e) = questions.put_in(&mut question, &ownership) {
1786            tracing::warn!(
1787                "could not retire question {} for task {}: {e:#}",
1788                question.short(),
1789                task.short()
1790            );
1791        }
1792    }
1793}
1794
1795/// What a finished run tells the queue about the task it came from.
1796///
1797/// A struct rather than a fourth and fifth boolean argument: the two flags
1798/// answer different questions about the same run, and a call site passing
1799/// `(…, true, false)` is one transposition away from refunding attempts
1800/// forever.
1801#[derive(Debug, Clone, Copy)]
1802pub struct Verdict {
1803    /// Where the graph stopped.
1804    pub status: RunStatus,
1805    /// The run opened a pull request.
1806    pub left_pr: bool,
1807    /// At least one seat was lost to a rate limit.
1808    pub quota_hit: bool,
1809    /// The run parked at a node boundary because it was asked to.
1810    pub parked: bool,
1811    /// The run never produced a single candidate a judge could look at.
1812    ///
1813    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1814    /// still have another candidate worth judging, in which case the loss was
1815    /// not the reason nothing came of the run. This is `true` only when the
1816    /// implement wave ended with nothing viable at all.
1817    pub no_viable_candidates: bool,
1818}
1819
1820/// Record a finished run against the task it came from.
1821///
1822/// Kept pure and separate from the loop because this mapping *is* the retry
1823/// policy, and a policy that can only be exercised by spawning a graph is a
1824/// policy nobody checks. The table:
1825///
1826/// | run status                           | task becomes        | attempt spent |
1827/// |---------------------------------------|---------------------|---------------|
1828/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1829/// | `Merged`, `Ready`                      | `Done`               | yes          |
1830/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1831/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1832/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1833/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1834/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1835/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1836/// | `Blocked` with a PR                    | `Held`               | yes          |
1837/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1838/// | `VerifiedNoop`                          | `Held`               | yes          |
1839/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1840///
1841/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1842/// deliberately: every candidate agreeing there is nothing to write is not a
1843/// machine fact about a rate limit, it is an unverified claim about the
1844/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1845/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1846/// claim could be wrong (a misread instruction, a stale check), and closing
1847/// the task automatically on an implementer's say-so would be the exact
1848/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1849/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1850/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1851/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1852/// claim regardless of whether the one already-spent attempt is refunded, and
1853/// [`Task::release`] resets the count to zero anyway the moment a human looks
1854/// at the evidence and lets it run again.
1855///
1856/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1857/// twice, together. A quorum lost to rate limits is a property of the machine
1858/// and not of the task, so the attempt is refunded and a reset quota picks
1859/// the work up where it stopped — and that is just as true when every
1860/// implement seat lost the same race and `after_implement` bails with nothing
1861/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1862/// machine fact. The `no_viable_candidates` guard is what keeps that row
1863/// narrow: a `Failed` run that produced a real candidate which then lost for
1864/// some other reason still spends the attempt, exactly like the quorum lost
1865/// to judges that answered with the wrong shape is ordinary flakiness, and
1866/// refunding *that* takes the bound off the retry loop entirely: run e633
1867/// stalled with `quota: []` after two judges wrote unusable JSON, was
1868/// refunded, and the next attempt paid for a fresh hour-long implement wave
1869/// before it could fail the same way. `max_attempts` exists precisely so
1870/// that cannot repeat forever.
1871///
1872/// A non-terminal status means `execute` returned while the graph was still
1873/// mid-flight, which is a bug rather than a verdict; it is treated as a
1874/// failure so that a task cannot loop on it either.
1875///
1876/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1877/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1878pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1879    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1880}
1881
1882/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1883fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1884    // A parked run is the operator's own doing, and its work is intact on
1885    // disk. The task goes back in line with its attempt refunded so the next
1886    // loop resumes the same run - which `one_task` prefers over competing
1887    // again - and so that swapping the binary a few times cannot exhaust a
1888    // budget meant for agents that actually misbehaved.
1889    if verdict.parked {
1890        task.park(detail);
1891        return;
1892    }
1893    match verdict.status {
1894        RunStatus::Merged | RunStatus::Ready
1895            if task.pr_recovery.as_ref().is_some_and(|s| {
1896                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1897            }) =>
1898        {
1899            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()));
1900        }
1901        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1902        RunStatus::AlreadyInBase => task.already_landed(detail),
1903        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1904        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1905            task.stall(detail)
1906        }
1907        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1908        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1909        RunStatus::Blocked => task.fail(detail, max_attempts),
1910        RunStatus::VerifiedNoop => task.handed_off(detail),
1911        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1912    }
1913}
1914
1915/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1916/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1917/// itself has actually finished *and* its own last attempt is provably why:
1918/// this loads that run and requires `Merged`/`Ready` before touching
1919/// anything earlier in `runs`, since `Task::succeed` can also be called
1920/// directly on a task whose last attempt never landed at all.
1921///
1922/// Called right after whatever call set `task.status` to
1923/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1924/// `reclaim`'s, but also every other place a task can be closed by hand
1925/// without the loop ever settling it itself: `magi task done`
1926/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1927/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1928/// GitHub merge, say, exactly the workflow this repository's own
1929/// "Landing a run's winner by hand" documents — is just as much "this task's
1930/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1931/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1932/// forever, which is the exact backlog this status exists to clear. `pub`
1933/// for those two out-of-module callers; everything else about this stays
1934/// internal bookkeeping.
1935///
1936/// A run something is still actually driving is left alone: a
1937/// task cannot be `Done` while one of its *own* attempts is still in flight,
1938/// so a live one at this point can only be an unrelated process — a manual
1939/// `--resume` of this old, now-moot run — and rewriting under it would just
1940/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1941/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1942/// pair `run_report`/`run_detail` use for the same question elsewhere:
1943/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1944/// --resume` invoked by hand outside it, which `liveness` also checks via
1945/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1946/// (already terminal in some other way, or itself mid-run) is left untouched
1947/// too.
1948///
1949/// Best-effort, like the rest of this module's bookkeeping: a load or save
1950/// failure here is a `tracing::warn`, not a failed settle, and the next time
1951/// this same task's completion is recorded — or a daemon restart replays
1952/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1953/// separate reconciliation pass; if that gap ever matters in practice, one
1954/// can be added then.
1955///
1956/// `home` is a parameter, not the process-global [`crate::run::home`], for
1957/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1958/// calls this with `ui.home`, which is `crate::run::home()` in a real
1959/// process but a fixture's own directory under test — falling through to
1960/// the global there would read and write through whichever home some other
1961/// test in the same binary happened to pin into that `OnceLock` first, not
1962/// the run this call actually means.
1963pub fn supersede_prior_runs(task: &Task, home: &Path) {
1964    let now = Timestamp::now();
1965    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1966    // right behind a `Merged`/`Ready` verdict) from one set directly by
1967    // `magi task done`/its web equivalent/the conductor on a task whose last
1968    // recorded attempt never actually landed - that requires reading the
1969    // run itself, which is exactly what this does before trusting anything
1970    // in `runs` is safe to relabel.
1971    let last_run_succeeded = task
1972        .runs
1973        .last()
1974        .and_then(|id| RunState::load_under(id, home).ok())
1975        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1976    for id in task.superseded_attempts(last_run_succeeded) {
1977        let mut state = match RunState::load_under(id, home) {
1978            Ok(s) => s,
1979            Err(e) => {
1980                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1981                continue;
1982            }
1983        };
1984        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1985            continue;
1986        }
1987        let daemon_claims = is_working_on(home, id, now);
1988        if state.liveness(daemon_claims) == Liveness::Live {
1989            continue;
1990        }
1991        state.status = RunStatus::Superseded;
1992        if let Err(e) = state.save_under(home) {
1993            tracing::warn!("could not mark run {id} superseded: {e:#}");
1994        }
1995    }
1996}
1997
1998/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1999/// finish the moment it was called, because one of its earlier attempts was
2000/// still live then - a `magi run --resume` invoked by hand on an old run,
2001/// most likely.
2002///
2003/// That skip is correct at the time (rewriting under a run something is
2004/// still actively saving would just be undone), but a task only ever
2005/// reaches `Done` once, so without this nothing would ever look at it
2006/// again: if that manual process later ends anywhere other than
2007/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
2008/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
2009/// backlog this status exists to clear. Called on the same idle-only
2010/// cadence as [`janitor`], next to it rather than folded into it: this
2011/// walks `queue` and `janitor` never otherwise needs one.
2012///
2013/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
2014/// more than one attempt, every pass: each call is a handful of local file
2015/// reads bounded by that task's own attempt count, the same order of cost
2016/// [`clean::fold_due`] already pays scanning every run on disk on the same
2017/// cadence, and a task already fully resolved costs one failed liveness
2018/// check turned no-op the moment its lingering attempt is no longer live.
2019fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2020    for task in queue.list() {
2021        if task.status != TaskStatus::Done || task.runs.len() < 2 {
2022            continue;
2023        }
2024        supersede_prior_runs(&task, home);
2025    }
2026}
2027
2028/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
2029/// task ends up held.
2030///
2031/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
2032/// dead daemon never got back to) share this, so the two cannot drift into
2033/// disagreeing about which held tasks get a diagnostic.
2034fn settle_and_diagnose(
2035    task: &mut Task,
2036    verdict: Verdict,
2037    detail: &str,
2038    max_attempts: usize,
2039    state: &RunState,
2040) {
2041    let p = phrases(&state.config.graph.language);
2042    // Shared by normal completion and crash recovery, under the task claim.
2043    // No new attempt can own the task until the old driver has exited.
2044    if let Some(d) = &state.merge_decision {
2045        use crate::merge_decision as md;
2046        if task
2047            .execution_runs()
2048            .last()
2049            .is_some_and(|id| id != &state.id)
2050        {
2051            return;
2052        }
2053        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2054            task.succeed();
2055        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2056            if state.liveness(false) != Liveness::Dead {
2057                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2058                return;
2059            }
2060            let replacement = md::Replacement {
2061                question: d.question.clone(),
2062                run: state.id.clone(),
2063                pr: d.target.pr.clone(),
2064                agent: agent.to_owned(),
2065                context: format!(
2066                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2067                    d.target.pr,
2068                    state.id,
2069                    serde_json::to_string(&state.reviews).unwrap_or_default()
2070                ),
2071            };
2072            task.requeue();
2073            task.pr_recovery = None;
2074            task.review_of = None;
2075            task.replacement = Some(replacement);
2076        } else {
2077            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2078                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2079            } 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())) }));
2080        }
2081        task.mark_action_applied(&d.question);
2082        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2083            task.decision_effects
2084                .insert(d.question.clone(), format!("decision: {}", d.choice));
2085        }
2086        if let Some(pass) = state.passes.last() {
2087            task.record_pass_at(
2088                &state.id,
2089                pass.index,
2090                Some(pass.started_at),
2091                task.attempts,
2092                None,
2093            );
2094        }
2095        return;
2096    }
2097    if let Some(replacement) = &task.replacement
2098        && !state.parked
2099        && state.resource_block.is_none()
2100        && (state.viable().is_empty()
2101            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2102    {
2103        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)));
2104        return;
2105    }
2106    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2107        let mut agents: Vec<_> = state
2108            .quota
2109            .iter()
2110            .filter(|q| {
2111                q.cause == crate::agent::QuotaCause::Authentication
2112                    && state
2113                        .passes
2114                        .last()
2115                        .is_none_or(|pass| q.at >= pass.started_at)
2116            })
2117            .map(|q| q.agent.as_str())
2118            .collect();
2119        agents.sort_unstable();
2120        agents.dedup();
2121        if !agents.is_empty() {
2122            task.stall(detail);
2123            task.notice_cause("agent-authentication", None, None);
2124            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2125            return;
2126        }
2127    }
2128    let attempts_before = task.attempts;
2129    // A run that stopped because a shared resource stayed busy was never a
2130    // failure of the task or of an agent. Earlier nodes may have run; only
2131    // the blocked operation lacks a result. The attempt is
2132    // refunded and the task is held by the machine, under a reason `triage`
2133    // can re-check, so the same run resumes with the same agents once the
2134    // resource is free. A park request still wins (it is the operator's).
2135    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2136        let disk_checked_at = task.disk_checked_at;
2137        task.notice_cause(
2138            &format!("resource:{}:{}", block.kind, block.node),
2139            None,
2140            None,
2141        );
2142        task.last_error = Some(detail.to_owned());
2143        task.diagnostic = None;
2144        task.attempts = task.attempts.saturating_sub(1);
2145        if block.kind == "agent authentication" {
2146            task.hold_machine(Some(format!(
2147                "[authentication] {}; no attempt was spent",
2148                block.detail
2149            )));
2150        } else if block.kind == "agent usage limit" {
2151            // Usage limits keep the existing cooldown-and-resume policy.
2152            if let Some(agent) = &state.config.graph.selected_implementer {
2153                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.")));
2154            } else {
2155                task.status = TaskStatus::Failed;
2156                task.last_error = Some(block.detail.clone());
2157            }
2158        } else if block.kind == "disk pressure" {
2159            task.hold_machine(Some(format!(
2160                "{}{}",
2161                crate::disk::RUNNING_PRESSURE,
2162                block.detail
2163            )));
2164        } else {
2165            task.hold_machine(Some(format!(
2166                "{}{}; no attempt was spent; resume to retry the affected operation",
2167                crate::cache::RESOURCE_HOLD,
2168                block.description()
2169            )));
2170        }
2171        if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2172            && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2173        {
2174            task.mark_disk_capacity();
2175            task.disk_checked_at = disk_checked_at;
2176        }
2177        if let Some(pass) = state.passes.last() {
2178            task.record_pass_at(
2179                &state.id,
2180                pass.index,
2181                Some(pass.started_at),
2182                attempts_before,
2183                None,
2184            );
2185        }
2186        return;
2187    }
2188    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2189        state.parked
2190            && state.status == RunStatus::Landing
2191            && state
2192                .pr_pushed_head
2193                .as_ref()
2194                .is_none_or(|h| h == &hold.head)
2195            && task.execution_runs().last() == Some(&state.id)
2196    }) {
2197        // Settlement and crash recovery share this idempotency key. A later
2198        // explicit resume is a new pass and may refund its own attempt once.
2199        let pass = state.passes.last().map_or(0, |p| p.index);
2200        if !task
2201            .passes
2202            .iter()
2203            .any(|p| p.run == state.id && p.pass_index == pass)
2204        {
2205            task.attempts = task.attempts.saturating_sub(1);
2206        }
2207        task.hold_machine(Some(format!(
2208            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2209            hold.question
2210        )));
2211        task.last_error = Some(detail.to_owned());
2212        task.diagnostic = None;
2213        task.record_pass_at(
2214            &state.id,
2215            pass,
2216            state.passes.last().map(|p| p.started_at),
2217            attempts_before,
2218            Some(crate::run::ParkCause::Question),
2219        );
2220        return;
2221    }
2222    let unresolved = task.hold_notice_cause.clone();
2223    if state.base_sync_blocked() {
2224        // No automatic retry may turn a retained sync stop into a new competition.
2225        task.hold_machine(Some(detail.to_owned()));
2226        task.last_error = Some(detail.to_owned());
2227    } else if !verdict.parked
2228        && task
2229            .pr_recovery
2230            .as_ref()
2231            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2232        && matches!(
2233            verdict.status,
2234            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2235        )
2236    {
2237        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2238            task.succeed();
2239        } else {
2240            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()));
2241        }
2242    } else if !verdict.parked
2243        && task.pr_recovery.is_some()
2244        && matches!(
2245            verdict.status,
2246            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2247        )
2248        && !verdict.quota_hit
2249    {
2250        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.")));
2251    } else {
2252        settle_in(task, verdict, detail, max_attempts, p);
2253    }
2254    if !verdict.parked
2255        && !verdict.quota_hit
2256        && matches!(
2257            verdict.status,
2258            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2259        )
2260    {
2261        task.recovery_failed(state);
2262    }
2263    if state.prep_failure.is_some() {
2264        // Minting a run whose candidates could not be prepared is not work
2265        // on a newly approved attempt. Keep the unresolved outcome anchor.
2266        task.hold_notice_cause = unresolved;
2267        task.startup_notice_cause("startup-candidates");
2268    }
2269    // Written here, where the refund (or not) is decided, so the history is a
2270    // fact and not a later guess from the run's status.
2271    if let Some(pass) = state.passes.last() {
2272        let parked = match &pass.end {
2273            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2274            _ => None,
2275        };
2276        task.record_pass_at(
2277            &state.id,
2278            pass.index,
2279            Some(pass.started_at),
2280            attempts_before,
2281            parked,
2282        );
2283    }
2284    if task.status == TaskStatus::Held {
2285        if state.base_sync_blocked() {
2286            task.base_sync_notice(state);
2287        } else if state.prep_failure.is_none() {
2288            task.notice_cause(
2289                label(verdict.status),
2290                Some(&state.id),
2291                state.passes.last().map(|p| p.index),
2292            );
2293        }
2294        task.diagnostic = diagnostic(state);
2295        note_open_question(task, &state.id, p);
2296    }
2297}
2298
2299/// If `task` is held with a `magi ask` question still open on `run`, name the
2300/// question in [`Task::hold_reason`] rather than leaving the hold reading
2301/// only [`describe`]'s run summary.
2302///
2303/// This is the shape task 20260928-191407-05fd left underspecified: an
2304/// implementer settled a verified no-op and filed a question for the
2305/// operator, and the hold that followed said nothing about the question
2306/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2307/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2308/// marker) and must keep seeing it unchanged.
2309///
2310/// Best-effort: an unreadable question store must not stop a run from
2311/// settling, so this is a no-op rather than a propagated error when
2312/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2313fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2314    let Some(home) = crate::run::try_home() else {
2315        return;
2316    };
2317    let open = Questions::at(home.join("questions")).open_for(run);
2318    let Some(q) = open.first() else {
2319        return;
2320    };
2321    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2322    decisions.sort_unstable();
2323    task.notice_cause(
2324        &format!("questions:{}", decisions.join(",")),
2325        Some(run),
2326        None,
2327    );
2328    let base = task.hold_reason.clone().unwrap_or_default();
2329    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2330}
2331
2332/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2333/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2334/// by some other means entirely, like a manual `magi run` resume that
2335/// finishes the graph outside the queue's bookkeeping.
2336///
2337/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2338/// `settle` is separate from `attempt`: a task recovered this way must land
2339/// exactly where a live daemon would have put it — the same policy table,
2340/// not a second one that quietly drifts from it — and that is only checkable
2341/// without spawning a real run.
2342fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2343    if let Some(request) = task.sync_only.clone() {
2344        crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2345        return;
2346    }
2347    match last_run {
2348        Some(state) => {
2349            let verdict = Verdict {
2350                status: state.status,
2351                left_pr: state.pr.is_some(),
2352                quota_hit: state.quota.iter().any(|loss| {
2353                    state
2354                        .passes
2355                        .last()
2356                        .is_none_or(|pass| loss.at >= pass.started_at)
2357                }),
2358                parked: state.parked,
2359                no_viable_candidates: state.viable().is_empty(),
2360            };
2361            let detail = format!(
2362                "{}{}",
2363                phrases(&state.config.graph.language).recovered_running,
2364                describe(&state)
2365            );
2366            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2367        }
2368        None => {
2369            // No run, so no config of its own: `language` is the task's
2370            // repository's setting, read by the caller.
2371            let why = phrases(language).no_run_to_recover;
2372            task.last_error = Some(why.to_owned());
2373            // The phone shows `hold_reason`, so a task held by the machine
2374            // says why there too and not only in `last_error`.
2375            task.notice_cause("missing-run", None, None);
2376            task.hold_machine(Some(why.to_owned()));
2377        }
2378    }
2379}
2380
2381/// Find every task left at `running` that no live process is actually
2382/// driving, and settle each one against whatever its last run became.
2383///
2384/// # Why a claim is proof, not a guess
2385///
2386/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2387/// `running`, and the guard is held for the task's whole time in that status:
2388/// `attempt` does not return, and the loop does not move past the scope
2389/// holding the claim, until the run has settled. So a `running` task whose
2390/// lock is gone cannot have a live owner — this process or any other —
2391/// without needing a staleness threshold or a pid check the way
2392/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2393/// task that never got as far as `running` at all. Taking the claim here is
2394/// the whole test: it either fails, because something really does hold it
2395/// and the task is left alone, or it succeeds, which is the proof — and it is
2396/// kept for the rest of the decision so nothing else can start a competing
2397/// run while this one is being written.
2398///
2399/// Called on every poll, not only at startup, for the reason
2400/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2401/// keep noticing this, not only on the one morning it happened to restart.
2402fn reclaim_orphaned_running(
2403    queue: &Queue,
2404    max_attempts: usize,
2405    live_workers: &std::collections::BTreeSet<String>,
2406) -> Vec<String> {
2407    let mut reclaimed = Vec::new();
2408    for listed in queue.list() {
2409        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2410            continue;
2411        }
2412        let Ok(_claim) = queue.claim(&listed.id) else {
2413            continue;
2414        };
2415        // Re-read under the claim: a release or an edit landed by a human
2416        // between the listing above and the claim just taken must not be
2417        // clobbered by a decision based on the stale copy.
2418        let Ok(mut task) = queue.get(&listed.id) else {
2419            continue;
2420        };
2421        if task.status != TaskStatus::Running {
2422            continue;
2423        }
2424        let last_run = task
2425            .execution_runs()
2426            .last()
2427            .and_then(|id| RunState::load(id).ok());
2428        // `execute` normally abandons a run's own open questions the moment
2429        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2430        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2431        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2432        // with the question still `open`, because the process died before
2433        // reaching that call. `reclaim` itself stays pure on purpose (see its
2434        // own doc), so the same cleanup runs here instead, against the run
2435        // this reclaim is already reading. `settle_run` costs nothing when
2436        // `execute` already got there first.
2437        if let Some(state) = &last_run
2438            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2439        {
2440            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2441        }
2442        let language = if last_run.is_none() {
2443            language_of(&task, Path::new("."))
2444        } else {
2445            String::new()
2446        };
2447        reclaim(&mut task, last_run, max_attempts, &language);
2448        if task.status == TaskStatus::Done {
2449            supersede_prior_runs(&task, &crate::run::home());
2450        }
2451        record(queue, &mut task);
2452        reclaimed.push(task.id.clone());
2453    }
2454    reclaimed
2455}
2456
2457/// Find every run whose `run.json` is provably dead — every seat it still
2458/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2459/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2460/// not merely "no daemon claims it" — and fail it, clearing the leftover
2461/// active seats so the run stops reading as `implementing` (or whichever
2462/// node) forever.
2463///
2464/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2465/// `running`, using whatever `run.json` already says — but nothing in that
2466/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2467/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2468/// never got back to sits exactly where it was left: `active` full of seats
2469/// nobody will ever answer for, `status` stuck on whatever node was in
2470/// flight. `magi show` already tells an operator this in prose (`no live
2471/// daemon claims this run right now`); this is what makes that fact durable
2472/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2473/// stay stuck once nothing is driving it.
2474///
2475/// Runs on every poll, not only at startup, for the reason
2476/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2477/// daemon up for days must keep noticing a run some other, now-dead, daemon
2478/// left behind just as readily as one it trips over on the way up.
2479///
2480/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2481/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2482/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2483/// `runs` directory instead: `home` here is a parameter precisely so a test
2484/// can point it away from the operator's real history (see [`drive`]'s own
2485/// doc), and a scan that fell through to the global home anyway would walk
2486/// whichever directory some *other* process or test pinned into that
2487/// `OnceLock` first — mutating runs this call was never handed.
2488fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2489    reclaim_abandoned_runs_with(
2490        home,
2491        now,
2492        crate::proc::pid_status,
2493        crate::proc::process_started_at,
2494    )
2495}
2496
2497/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2498/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2499/// for the identical reason: this sweep's real damage (wiping a run's active
2500/// seats and failing it) has to be provable against an injected answer in a
2501/// test, not just the real process table.
2502fn reclaim_abandoned_runs_with<F, G>(
2503    home: &Path,
2504    now: Timestamp,
2505    query: F,
2506    identity: G,
2507) -> Vec<String>
2508where
2509    F: Fn(u32) -> Option<bool>,
2510    G: Fn(u32) -> Option<String>,
2511{
2512    let mut abandoned = Vec::new();
2513    for entry in std::fs::read_dir(home.join("runs"))
2514        .into_iter()
2515        .flatten()
2516        .flatten()
2517    {
2518        let id = entry.file_name().to_string_lossy().into_owned();
2519        if !crate::run::is_run_id(&id) {
2520            continue;
2521        }
2522        // Serialize the proof and save with claims and takeover: a new
2523        // execution must not be overwritten after the liveness observation.
2524        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2525            continue;
2526        };
2527        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2528        // that module's docs for why a run this cannot parse is left alone
2529        // rather than guessed at. A different schema number is not that: this
2530        // touches only `status` and `active`, never a field whose meaning a
2531        // schema bump changed, so an old record's values serve this exactly
2532        // as well as a current one's (see `clean::read_state`'s own doc for
2533        // the same reasoning applied to folding).
2534        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2535            continue;
2536        };
2537        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2538            continue;
2539        };
2540        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2541            continue;
2542        }
2543        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2544        // it", which is also the normal, healthy shape of a manual `magi
2545        // run` / `magi review` sharing this same home — this scan walks
2546        // every run on disk, not only ones this daemon itself started. Such
2547        // a run's active seats can legitimately sit past their own timeout
2548        // for a little while (the CLI finishing up, its result still being
2549        // collected) without the process driving it having died. `liveness`
2550        // is what actually tells the two apart, by corroborating
2551        // `driver_pid` against the process it names — see its own doc. Only
2552        // its strongest, provable answer licenses wiping this run's active
2553        // seats and failing it out from under whatever is still running it.
2554        let daemon_claims = is_working_on(home, &id, now);
2555        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2556            != crate::run::Liveness::Dead
2557        {
2558            continue;
2559        }
2560        state.abandon("daemon");
2561        if let Err(e) = state.save_under(home) {
2562            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2563            continue;
2564        }
2565        // This run never passes through `Runner::execute` again, so its end
2566        // is announced here.
2567        if let Some(notice) = notices::run_ended(&state) {
2568            notices::raise_in(home, notice);
2569        }
2570        // The seat that asked is gone for good now, exactly like any other
2571        // door `graph::Runner::settle_questions` closes the moment `status`
2572        // lands somewhere non-resumable - see that method's own doc. Nothing
2573        // else reaches this one before the next `janitor()` startup pass
2574        // (`clean::abandon_settled_questions`), and a daemon that stays up
2575        // for days must not leave an open question badging the operator
2576        // until it happens to restart.
2577        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2578            tracing::warn!("abandon questions for {id}: {e:#}");
2579        }
2580        abandoned.push(id);
2581    }
2582    abandoned
2583}
2584
2585#[derive(Debug, Clone, Serialize, Deserialize)]
2586struct TaskWorker {
2587    opts: Opts,
2588    queue: PathBuf,
2589    task: String,
2590    #[serde(default)]
2591    lane: PermitKind,
2592    #[serde(default)]
2593    standalone: bool,
2594}
2595
2596fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2597    Ok(crate::worker::active(home)?
2598        .into_iter()
2599        .filter(|job| job.kind == "task")
2600        .collect())
2601}
2602
2603fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2604    task_jobs(home)?
2605        .into_iter()
2606        .filter_map(
2607            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2608                Ok(request) if !request.standalone => Some(Ok(job)),
2609                Ok(_) => None,
2610                Err(error) => Some(Err(error.into())),
2611            },
2612        )
2613        .collect()
2614}
2615
2616/// Whether an independent scheduler can be controlled without its web parent.
2617#[must_use]
2618pub fn managed(home: &Path) -> bool {
2619    match crate::worker::active(home) {
2620        Err(error) => {
2621            tracing::error!("cannot determine scheduler ownership: {error:#}");
2622            true
2623        }
2624        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2625        Ok(_) => {
2626            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2627                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2628        }
2629    }
2630}
2631
2632/// Start a detached, singleton scheduler using this executable generation.
2633pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2634    anyhow::ensure!(
2635        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2636        "the scheduler is stopping; wait for retirement before starting it again"
2637    );
2638    crate::worker::spawn(
2639        home,
2640        "scheduler",
2641        "scheduler",
2642        serde_json::to_value(opts.absolute()?)?,
2643    )
2644    .await
2645}
2646
2647fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2648    home.join("worker-parks").join(format!("{}.json", job.id))
2649}
2650
2651fn request_task_park(
2652    home: &Path,
2653    job: &crate::worker::Job,
2654    cause: crate::run::ParkCause,
2655) -> Result<()> {
2656    let path = park_request_path(home, job);
2657    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2658    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2659    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2660}
2661
2662/// Stop dispatch immediately; only an explicit park reaches existing workers.
2663pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2664    if control == crate::worker::Control::Park {
2665        for job in owned_task_jobs(home)? {
2666            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2667        }
2668    }
2669    crate::worker::request(home, "scheduler", control)
2670}
2671
2672/// Replace the scheduler, leaving all active task and conversation jobs alone.
2673pub async fn restart_detached(home: &Path) -> Result<()> {
2674    let active = crate::worker::active(home)?;
2675    let prior = active.into_iter().find(|job| job.kind == "scheduler");
2676    if prior.is_none() && !managed(home) {
2677        return Ok(());
2678    }
2679    let opts: Opts = match prior {
2680        Some(job) => serde_json::from_value(job.payload)?,
2681        None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2682    };
2683    request_control(home, crate::worker::Control::Stop)?;
2684    loop {
2685        let reserved = crate::worker::active(home)?
2686            .iter()
2687            .any(|job| job.kind == "scheduler");
2688        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2689            break;
2690        }
2691        tokio::time::sleep(Duration::from_millis(100)).await;
2692    }
2693    spawn_detached(home, &opts).await?;
2694    Ok(())
2695}
2696
2697/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2698pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2699    let opts: Opts = serde_json::from_value(payload)?;
2700    let _ = home;
2701    serve_until(opts, Stop::new()).await
2702}
2703
2704/// Execute and settle one task with the queue claim owned by this process.
2705pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2706    let request: TaskWorker = serde_json::from_value(payload)?;
2707    let queue = Queue::at(request.queue);
2708    let key = format!("task:{}", request.task);
2709    let job = task_jobs(home)?
2710        .into_iter()
2711        .find(|job| job.key == key)
2712        .context("task worker reservation is missing")?;
2713    let park_path = park_request_path(home, &job);
2714    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2715    // our durable reservation. Never execute before that ownership hand-off.
2716    let _claim = loop {
2717        match queue.claim(&request.task) {
2718            Ok(claim) => break claim,
2719            // Only contention (the claim file exists) is worth waiting out; an
2720            // I/O failure must end this worker instead of pinning its lane.
2721            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2722                return Err(e.context("claim the task for its worker"));
2723            }
2724            Err(_) => {
2725                sweep_stale_claims(&queue, STALE_CLAIM);
2726                tokio::time::sleep(Duration::from_millis(50)).await;
2727            }
2728        }
2729    };
2730    let mut task = queue.get(&request.task)?;
2731    if !task.status.runnable()
2732        || (!request.standalone
2733            && request.lane
2734                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2735    {
2736        return Ok(());
2737    }
2738    let stop = Stop::new();
2739    let watcher = {
2740        let home = home.to_path_buf();
2741        let stop = stop.clone();
2742        let park_path = park_path.clone();
2743        tokio::spawn(async move {
2744            loop {
2745                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2746                    let cause = std::fs::read(&park_path)
2747                        .ok()
2748                        .and_then(|body| serde_json::from_slice(&body).ok())
2749                        .unwrap_or(crate::run::ParkCause::Operator);
2750                    stop.park(cause);
2751                    return;
2752                }
2753                tokio::time::sleep(Duration::from_millis(200)).await;
2754            }
2755        })
2756    };
2757    let quota = if request.standalone {
2758        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2759    } else {
2760        let status = Arc::new(Mutex::new(Status::new()));
2761        Box::pin(attempt(
2762            &request.opts,
2763            &queue,
2764            &status,
2765            &stop,
2766            crate::graph::Pause::new(),
2767            &mut task,
2768        ))
2769        .await
2770    };
2771    watcher.abort();
2772    let _ = std::fs::remove_file(park_path);
2773    persist_cooldown(home, &quota).await?;
2774    Ok(())
2775}
2776
2777/// Launch the standalone task worker with a claim-to-reservation handoff.
2778/// Returns only after the worker owns a durable execution reservation.
2779pub async fn spawn_claimed(
2780    home: &Path,
2781    opts: &Opts,
2782    queue: &Queue,
2783    task: &Task,
2784    claim: crate::queue::Claim,
2785) -> Result<crate::worker::Job> {
2786    let request = TaskWorker {
2787        opts: opts.absolute()?,
2788        queue: std::path::absolute(queue.root())?,
2789        task: task.id.clone(),
2790        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2791        standalone: true,
2792    };
2793    let job = crate::worker::spawn(
2794        home,
2795        "task",
2796        &format!("task:{}", task.id),
2797        serde_json::to_value(request)?,
2798    )
2799    .await?;
2800    drop(claim);
2801    Ok(job)
2802}
2803
2804/// Transfer a standalone caller's claim only after the detached worker is live,
2805/// then follow that worker to its final (non-automatically-retrying) outcome.
2806pub async fn run_detached_claimed(
2807    opts: &Opts,
2808    queue: &Queue,
2809    task: &mut Task,
2810    claim: crate::queue::Claim,
2811) -> Result<()> {
2812    let home = crate::run::home();
2813    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2814    loop {
2815        // Reconcile execution leases even without a scheduler. A dead worker
2816        // must become a reported failure, never an infinite persisted wait.
2817        crate::worker::active(&home)?;
2818        let current = crate::worker::get(&home, &job.id)?;
2819        if matches!(
2820            current.status,
2821            crate::worker::Status::Finished | crate::worker::Status::Failed
2822        ) {
2823            *task = queue.get(&task.id)?;
2824            anyhow::ensure!(
2825                current.status != crate::worker::Status::Failed,
2826                "task worker failed: {}",
2827                current.result.as_deref().unwrap_or("unknown failure")
2828            );
2829            return Ok(());
2830        }
2831        tokio::time::sleep(Duration::from_millis(200)).await;
2832    }
2833}
2834
2835async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2836    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2837        let _lease = loop {
2838            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2839                break lease;
2840            }
2841            tokio::time::sleep(Duration::from_millis(10)).await;
2842        };
2843        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2844            let path = home.join("task-quota-cooldown.json");
2845            let temporary = path.with_extension("json.tmp");
2846            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2847            std::fs::rename(temporary, path)?;
2848        }
2849    }
2850    Ok(())
2851}
2852
2853fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2854    match std::fs::read(home.join("task-quota-cooldown.json")) {
2855        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2856        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2857        Err(error) => Err(error.into()),
2858    }
2859}
2860
2861/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2862///
2863/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2864/// sets, so there is one loop body rather than two that drift apart the first
2865/// time the retry policy changes on only one of them.
2866pub async fn serve(opts: Opts) -> Result<()> {
2867    tracing::info!(
2868        "automatic update and restart requires magi web; standalone serve does not restart"
2869    );
2870    serve_until(opts, Stop::new()).await
2871}
2872
2873/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2874///
2875/// A stop retires dispatch promptly, including while a worker launch is being
2876/// acknowledged. Already reserved workers own their attempts independently and
2877/// finish with their started executable. Explicit park additionally forwards
2878/// durable park requests; neither scheduler retirement nor update does so.
2879///
2880/// While the queue is empty the stop is honoured within one wakeup rather than
2881/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2882/// caller that taps stop does not sit through the remainder of a sleep.
2883pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2884    let opts = opts.absolute()?;
2885    let home = crate::run::home();
2886    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2887        .context("another scheduler already owns this home")?;
2888    if let Some(reading) = read_status(&home)
2889        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2890    {
2891        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2892    }
2893    if !crate::worker::active(&home)?
2894        .iter()
2895        .any(|job| job.kind == "scheduler")
2896    {
2897        crate::worker::clear_control(&home, "scheduler")?;
2898    }
2899    std::fs::write(
2900        home.join("scheduler-options.json"),
2901        serde_json::to_vec(&opts)?,
2902    )?;
2903    let control = {
2904        let home = home.clone();
2905        let stop = stop.clone();
2906        tokio::spawn(async move {
2907            loop {
2908                match crate::worker::control(&home, "scheduler").ok().flatten() {
2909                    Some(crate::worker::Control::Park) => {
2910                        let _ = request_control(&home, crate::worker::Control::Park);
2911                        stop.park(crate::run::ParkCause::Operator);
2912                        break;
2913                    }
2914                    Some(crate::worker::Control::Stop) => {
2915                        stop.stop();
2916                        break;
2917                    }
2918                    None => {}
2919                }
2920                tokio::time::sleep(Duration::from_millis(100)).await;
2921            }
2922        })
2923    };
2924    let signal = {
2925        let stop = stop.clone();
2926        tokio::spawn(async move {
2927            if tokio::signal::ctrl_c().await.is_ok() {
2928                stop.stop();
2929                tracing::info!("scheduler shutdown requested; independent workers continue");
2930            }
2931        })
2932    };
2933
2934    let worktrees_root = opts
2935        .worktrees_root
2936        .clone()
2937        .unwrap_or_else(crate::run::default_worktree_root);
2938    let outcome = drive(
2939        &opts,
2940        &Queue::open(),
2941        &status_path(),
2942        &crate::run::home(),
2943        &worktrees_root,
2944        &stop,
2945    )
2946    .await;
2947
2948    signal.abort();
2949    control.abort();
2950    outcome
2951}
2952
2953/// The loop proper: setup, poll, teardown, with the queue and the status file
2954/// supplied rather than discovered.
2955///
2956/// All three of `home`, `worktrees_root` and the queue/status paths are
2957/// parameters rather than resolved here, for the same reason:
2958/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2959/// so a unit test that pinned it would fight every other test in the binary,
2960/// and a loop that resolved its own worktree bay could only be exercised
2961/// against the operator's real `~/wt/<repo>` - publishing over a live
2962/// daemon's status file, claiming tasks out of a live backlog, and, since
2963/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2964/// whatever the operator actually has on disk.
2965async fn drive(
2966    opts: &Opts,
2967    queue: &Queue,
2968    status_file: &Path,
2969    home: &Path,
2970    worktrees_root: &Path,
2971    stop: &Stop,
2972) -> Result<()> {
2973    // The status file is a *snapshot*, not a stream of events: a reader only
2974    // ever wants the latest values, and every tick rewrites the whole file
2975    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2976    // while an mpsc channel would force the loop to re-send unchanged fields on
2977    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2978    // for no gain. The lock is only ever held across a field assignment, never
2979    // across an await.
2980    let recovery_cfg = prepare(&opts.repo, opts).ok();
2981    let daemon_cfg = recovery_cfg
2982        .as_ref()
2983        .map(|c| c.daemon.clone())
2984        .unwrap_or_default();
2985    let reconciled = crate::driver::reconcile(home);
2986    if !reconciled.is_empty() {
2987        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2988    }
2989    let mut initial_status = Status::new();
2990    let owned = owned_task_jobs(home)?;
2991    initial_status.current = current_work(home, Timestamp::now())
2992        .into_iter()
2993        .filter(|current| {
2994            owned
2995                .iter()
2996                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2997        })
2998        .collect();
2999    initial_status.idle = initial_status.current.is_empty();
3000    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3001        recovery_cfg.as_ref(),
3002        daemon_cfg.max_deputies,
3003    ));
3004    let status = Arc::new(Mutex::new(initial_status));
3005    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3006    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3007
3008    // Read once at startup, not per task: how many runs this loop drives at
3009    // once is a property of the machine running it, not of whichever
3010    // repository a given task happens to name - see
3011    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
3012    // fact in the same sense the agent roster is.
3013    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3014
3015    tracing::info!(
3016        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3017        queue.root().display(),
3018        opts.poll.as_secs(),
3019        opts.max_attempts,
3020        concurrency,
3021        if daemon_cfg.pause_for_interrupts {
3022            ", interrupts enabled"
3023        } else {
3024            ""
3025        }
3026    );
3027
3028    let outcome = tokio::select! {
3029        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3030            max_concurrent: concurrency,
3031            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3032            recovery_cfg,
3033        }) => outcome,
3034        () = async {
3035            while !stop.stopped() {
3036                tokio::time::sleep(Duration::from_millis(25)).await;
3037            }
3038        } => {
3039            if stop.parking() {
3040                request_control(home, crate::worker::Control::Park)?;
3041            }
3042            Ok(())
3043        }
3044    };
3045
3046    stop.busy.store(0, Ordering::SeqCst);
3047    beat.abort();
3048    clear_status_at(status_file);
3049    outcome
3050}
3051
3052/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3053/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3054pub(crate) fn release_watch_settings_from_config(
3055    home: &Path,
3056    repo: &Path,
3057    cfg: &Config,
3058) -> (Vec<PathBuf>, u64) {
3059    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3060        .into_iter()
3061        .map(|r| r.path)
3062        .collect();
3063    // Repositories the daemon has worked in, wherever they live: a task may
3064    // name one outside `[repos] roots`, and its release PR must be watched too.
3065    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3066        .list()
3067        .into_iter()
3068        .map(|t| t.repo)
3069        .collect();
3070    let runs = home.join("runs");
3071    for id in crate::run::list_ids_in(&runs) {
3072        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3073            .ok()
3074            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3075            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3076        known.extend(repo);
3077    }
3078    for k in known {
3079        let k = k.canonicalize().unwrap_or(k);
3080        if k.join(".git").exists() && !paths.contains(&k) {
3081            paths.push(k);
3082        }
3083    }
3084    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3085    if !paths.contains(&own) {
3086        paths.push(own);
3087    }
3088    (paths, cfg.daemon.release_stall_minutes)
3089}
3090
3091/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3092const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3093
3094/// Refresh the status file on a fixed tick.
3095///
3096/// Separate from the loop because a run takes tens of minutes: a status file
3097/// written only between tasks would look stale for the whole of every run, and
3098/// a reader would report the daemon dead exactly while it was busiest.
3099async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3100    loop {
3101        tokio::time::sleep(HEARTBEAT).await;
3102        let snapshot = {
3103            let mut guard = lock(&status);
3104            guard.updated_at = Timestamp::now();
3105            guard.clone()
3106        };
3107        if let Err(e) = write_status_to(&path, &snapshot) {
3108            // A failed heartbeat must not take the daemon down: the loop is the
3109            // product, the status file is only the window onto it.
3110            tracing::warn!("could not refresh the daemon status file: {e:#}");
3111        }
3112    }
3113}
3114
3115/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3116/// if so, whether that wait is over.
3117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3118enum LandResume {
3119    /// The task's last run is not parked on a land approval; schedule it
3120    /// like any other candidate.
3121    NotLanding,
3122    /// Parked in `land`, waiting on a question nobody has answered yet.
3123    /// Left alone: attempting it now would only re-observe the same pull
3124    /// request and park again, spending a `gh` call on a decision that has
3125    /// not changed since the last time this was checked.
3126    StillWaiting,
3127    /// Parked in `land`, and the question is settled - answered or
3128    /// abandoned. Resuming this is the one kind of candidate that must not
3129    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3130    Ready,
3131}
3132
3133/// Classify a runnable candidate by whether it is parked on a land-merge
3134/// approval. Read-only - no claim taken, nothing written - so it is cheap
3135/// enough to call on every candidate, every poll.
3136fn land_resume_state(task: &Task) -> LandResume {
3137    if task.sync_only.is_some() {
3138        return LandResume::NotLanding;
3139    }
3140    let Some(run_id) = task.execution_runs().last() else {
3141        return LandResume::NotLanding;
3142    };
3143    let Ok(state) = RunState::load(run_id) else {
3144        return LandResume::NotLanding;
3145    };
3146    if !state.parked {
3147        return LandResume::NotLanding;
3148    }
3149    if state.status == RunStatus::Landing
3150        && state.land_approval.as_ref().is_some_and(|binding| {
3151            ask::Questions::open()
3152                .get_for_effects(&binding.question)
3153                .is_ok_and(|q| {
3154                    q.run == state.id
3155                        && q.resolution()
3156                            .as_deref()
3157                            .is_some_and(crate::merge_decision::stops)
3158                })
3159        })
3160    {
3161        return LandResume::Ready;
3162    }
3163    if !implementers_match(task, &state) {
3164        return LandResume::NotLanding;
3165    }
3166    // Parked in `land` on the merge approval, or at `merge` on the owner's
3167    // word about a title/body the posting gate withheld. Told apart by the
3168    // run's own record, not by a status both can share.
3169    let node = if state.status == RunStatus::Landing {
3170        land::APPROVAL_NODE
3171    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3172        crate::github_text::ASK_NODE
3173    } else {
3174        return LandResume::NotLanding;
3175    };
3176    let store = ask::Questions::open();
3177    let waiting = store
3178        .list_for_effects()
3179        .into_iter()
3180        .filter(|q| &q.run == run_id && q.node == node)
3181        .max_by(|a, b| a.id.cmp(&b.id));
3182    let Some(mut q) = waiting else {
3183        return LandResume::Ready;
3184    };
3185    if !q.status.open() {
3186        // Repair spends agent resources and must obey concurrency and quota
3187        // waits; only a merge/hold decision may use the decision-only lane.
3188        if q.resolution().as_deref() == Some(land::REPAIR) {
3189            return if state.liveness(false) == Liveness::Live {
3190                LandResume::StillWaiting
3191            } else {
3192                LandResume::NotLanding
3193            };
3194        }
3195        return LandResume::Ready;
3196    }
3197    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3198    // nobody ever answered; land's approval bypasses that wait entirely (see
3199    // `land::approval_gate`), so the same deadline has to be enforced here
3200    // instead, or `graph.answer_timeout` silently stops meaning anything for
3201    // a land approval and a run can sit `StillWaiting` forever with nobody
3202    // told to look at it.
3203    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3204    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3205    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3206        q.abandon(format!(
3207            "no answer within {}s of asking",
3208            timeout.as_secs().max(1)
3209        ));
3210        // If this can't be persisted, do not treat the wait as settled on a
3211        // guess: fall through and try again next poll.
3212        if store.put(&mut q).is_ok() {
3213            return LandResume::Ready;
3214        }
3215    }
3216    LandResume::StillWaiting
3217}
3218
3219/// How often the loop rechecks for new work while something it already
3220/// started is still running, rather than sleeping out the whole
3221/// [`Opts::poll`] interval.
3222///
3223/// Short on purpose: this is what lets a land-merge approval that comes back
3224/// while another task is mid-competition be noticed and resumed within a
3225/// fraction of a second, not within the next multi-second poll.
3226const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3227
3228/// How often [`poll`] rechecks the shared build cache against its cap at a
3229/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3230/// waiting for the queue to run dry.
3231///
3232/// A queue that never empties means the `janitor` call at the bottom of this
3233/// loop's fully-idle branch can go unreached for as long as the backlog
3234/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3235/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3236/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3237/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3238/// backlog of short tasks does not pay for that walk on every poll.
3239const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3240
3241/// State of [`poll`]'s own interrupt-scheduling sequence - see
3242/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3243/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3244/// both kept free of `Task`'s non-identity fields on purpose: every decision
3245/// here turns only on task ids and which ones are in flight, so the "never
3246/// more than one run at once" and "exactly one resume" invariants can be
3247/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3248/// queue - which is exactly the coverage this feature's first two attempts
3249/// were missing.
3250///
3251/// Persisted after every transition, so scheduler replacement preserves the
3252/// interrupt's exclusive turn and the interrupted task's priority resume.
3253#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3254enum Interrupt {
3255    /// No interrupt sequence in progress. Ordinary dispatch applies.
3256    Idle,
3257    /// `interrupt_task` is runnable and exactly one other run is in flight;
3258    /// `parked` names that one task's id. Dispatch is withheld from
3259    /// everyone, including `interrupt_task` itself, until it has left
3260    /// flight - only then is `interrupt_task` let through.
3261    ///
3262    /// `parked` is a `Vec` rather than a bare id for symmetry with
3263    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3264    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3265    /// when exactly one run is in flight, so it is guaranteed to hold
3266    /// exactly one entry in practice - see that branch's own doc for why
3267    /// more than one is deliberately never attempted.
3268    Parking {
3269        parked: Vec<String>,
3270        interrupt_task: String,
3271    },
3272    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3273    /// withheld from everyone until it leaves flight - merged, failed, held,
3274    /// it makes no difference - at which point the sequence moves to
3275    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3276    /// going straight to `Idle` would hand `parked` back to ordinary
3277    /// priority-order dispatch, where a higher-priority task filed in the
3278    /// meantime could start ahead of it.
3279    Running {
3280        parked: Vec<String>,
3281        interrupt_task: String,
3282    },
3283    /// `interrupt_task` left flight; `parked` still names the one run this
3284    /// sequence owes a resume. Dispatch is withheld from everyone except
3285    /// that task - see [`interrupt_gate`] - so the resume this feature
3286    /// promises is never raced by, or run alongside, an unrelated candidate.
3287    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3288    /// own doc on abandonment - the moment it is no longer runnable at all.
3289    Resuming { parked: Vec<String> },
3290}
3291
3292/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3293/// and `runnable` are read-only snapshots of this tick's reality, and the
3294/// only side effect the caller still owes the world is asking whichever
3295/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3296/// site.
3297///
3298/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3299/// accepted rather than a narrower type because that is what [`poll`] already
3300/// has on hand from [`runnable`], and building a second, smaller list on
3301/// every tick just to satisfy this signature would cost more than it proves.
3302///
3303/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3304/// back to a task they are waiting on no longer being [`runnable`] - held,
3305/// blocked, deleted, or finished by some other means entirely, all of which
3306/// an operator can do to a task sitting in the queue with no claim on it at
3307/// all, at any moment, interrupt sequence or not. Without this check the
3308/// sequence would wait forever for a dispatch that can never come, and
3309/// `interrupt_gate` would withhold every other task in the queue right along
3310/// with it - a single `magi task hold` on the wrong id turning into a
3311/// daemon that never dispatches anything again.
3312fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3313    match state {
3314        Interrupt::Idle => {
3315            // Not just "something to interrupt": exactly one thing. More
3316            // than one run in flight only happens above the default
3317            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3318            // one resume, never run alongside anything else" only because
3319            // it is only ever seeded with exactly one id - see
3320            // `Interrupt::Resuming`'s own doc on why releasing more than one
3321            // parked id back to ordinary dispatch cannot be made safe
3322            // against that same setting's own extra concurrency slots.
3323            // Waiting here for the herd to settle to one is the
3324            // simplification this feature's own constraints ask for rather
3325            // than a second concurrency model to reconcile with the first.
3326            if in_flight.len() != 1 {
3327                return Interrupt::Idle;
3328            }
3329            match runnable.iter().find(|t| t.interrupt) {
3330                Some(t) => Interrupt::Parking {
3331                    parked: in_flight.to_vec(),
3332                    interrupt_task: t.id.clone(),
3333                },
3334                None => Interrupt::Idle,
3335            }
3336        }
3337        Interrupt::Parking {
3338            parked,
3339            interrupt_task,
3340        } => {
3341            if in_flight.iter().any(|id| parked.contains(id)) {
3342                // Still waiting for what was in flight to actually stop.
3343                Interrupt::Parking {
3344                    parked,
3345                    interrupt_task,
3346                }
3347            } else if in_flight.contains(&interrupt_task) {
3348                Interrupt::Running {
3349                    parked,
3350                    interrupt_task,
3351                }
3352            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3353                // The parked run(s) are gone, but the interrupt task has not
3354                // been dispatched yet on this tick - `interrupt_gate` is
3355                // what lets it through next.
3356                Interrupt::Parking {
3357                    parked,
3358                    interrupt_task,
3359                }
3360            } else {
3361                // The interrupt task itself is no longer runnable - see this
3362                // function's own doc on abandonment. The parked run(s) still
3363                // get their guaranteed resume; there is simply no interrupt
3364                // to run ahead of them any longer.
3365                Interrupt::Resuming { parked }
3366            }
3367        }
3368        Interrupt::Running {
3369            parked,
3370            interrupt_task,
3371        } => {
3372            if in_flight.contains(&interrupt_task) {
3373                Interrupt::Running {
3374                    parked,
3375                    interrupt_task,
3376                }
3377            } else {
3378                // The interrupt task's own run reached a terminal status,
3379                // whichever one - this is the *only* trigger that moves the
3380                // sequence on, driven straight off the same in-flight
3381                // bookkeeping `poll` already reaps every tick, not a second,
3382                // independent poll of anything.
3383                Interrupt::Resuming { parked }
3384            }
3385        }
3386        Interrupt::Resuming { parked } => {
3387            if in_flight.iter().any(|id| parked.contains(id)) {
3388                // One of the parked runs has been dispatched - the resume
3389                // this sequence owed is fulfilled. Whatever else is left in
3390                // `parked` (ordinarily nothing, at the default concurrency
3391                // of one) rejoins ordinary priority-order dispatch, same as
3392                // any other runnable task.
3393                Interrupt::Idle
3394            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3395                Interrupt::Resuming { parked }
3396            } else {
3397                // Abandonment (see this function's own doc): nothing left in
3398                // `parked` is even runnable any longer.
3399                Interrupt::Idle
3400            }
3401        }
3402    }
3403}
3404
3405/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3406/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3407/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3408/// indistinguishable from any other runnable task - exactly the "off does
3409/// nothing" this feature promises.
3410fn advance_interrupt_tick(
3411    enabled: bool,
3412    state: Interrupt,
3413    in_flight: &[String],
3414    runnable: &[Task],
3415) -> Interrupt {
3416    if !enabled {
3417        return Interrupt::Idle;
3418    }
3419    advance_interrupt(state, in_flight, runnable)
3420}
3421
3422/// Which of this tick's runnable candidates the interrupt sequence actually
3423/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3424/// each half is assertable on its own: this is the half that keeps a
3425/// competition and an interrupt from ever running at the same moment.
3426fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3427    match state {
3428        Interrupt::Idle => candidates,
3429        Interrupt::Parking {
3430            parked,
3431            interrupt_task,
3432        } => {
3433            if in_flight.iter().any(|id| parked.contains(id)) {
3434                Vec::new()
3435            } else {
3436                candidates
3437                    .into_iter()
3438                    .filter(|t| &t.id == interrupt_task)
3439                    .collect()
3440            }
3441        }
3442        Interrupt::Running { .. } => Vec::new(),
3443        // At most one: even if `parked` names more than one id (more than
3444        // one run was in flight when the sequence began, only possible
3445        // above the default `max_concurrent_runs = 1`), only the first match
3446        // is offered. Capping this to a single candidate - not merely to
3447        // `parked`'s own ids - is what makes "exactly one resume, never two
3448        // dispatched together" true regardless of how many ordinary slots
3449        // happen to be free this tick.
3450        Interrupt::Resuming { parked } => candidates
3451            .into_iter()
3452            .find(|t| parked.contains(&t.id))
3453            .into_iter()
3454            .collect(),
3455    }
3456}
3457
3458/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3459/// bundled into one parameter so `poll`'s own signature stays readable -
3460/// see [`drive`]'s call site for where these are actually read.
3461struct DispatchLimits {
3462    /// How many *ordinary* candidates run at once. See
3463    /// [`crate::config::Daemon::max_concurrent_runs`].
3464    max_concurrent: usize,
3465    /// See [`crate::config::Daemon::pause_for_interrupts`].
3466    pause_for_interrupts: bool,
3467    recovery_cfg: Option<Config>,
3468}
3469
3470/// Which semaphore, if any, dispatching a candidate should draw its permit
3471/// from.
3472///
3473/// Pure and separate from [`poll`]'s loop body for the same reason
3474/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3475/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3476/// exactly the policy this feature adds, and a policy only exercisable by
3477/// running the whole loop is a policy nobody checks.
3478#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3479enum PermitKind {
3480    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3481    /// Checked first - a task can be both a land resume and marked
3482    /// [`Task::urgent`], and the resume's own "must not queue behind
3483    /// anything" guarantee takes precedence.
3484    None,
3485    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3486    /// (never in addition to trying) the ordinary pool. This is what lets
3487    /// an urgent task dispatch while every ordinary slot is already checked
3488    /// out, and what stops a second urgent task from opening a third run: it
3489    /// waits on this same one-slot semaphore rather than falling through to
3490    /// the ordinary one.
3491    Urgent,
3492    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3493    /// above.
3494    #[default]
3495    Ordinary,
3496}
3497
3498/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3499/// own boolean, already computed by the caller from [`land_resume_state`].
3500fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3501    if priority {
3502        PermitKind::None
3503    } else if urgent {
3504        PermitKind::Urgent
3505    } else {
3506        PermitKind::Ordinary
3507    }
3508}
3509
3510fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3511    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3512        (0usize, 0usize),
3513        |(ordinary, urgent), request| match request.lane {
3514            PermitKind::Ordinary => (ordinary + 1, urgent),
3515            PermitKind::Urgent => (ordinary, urgent + 1),
3516            PermitKind::None => (ordinary, urgent),
3517        },
3518    );
3519    (
3520        limit.saturating_sub(ordinary),
3521        1usize.saturating_sub(urgent),
3522    )
3523}
3524
3525/// Why a runnable candidate was not dispatched. This does not alter policy.
3526#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3527enum SkipReason {
3528    ClaimUnavailable,
3529    RereadFailed,
3530    NoLongerRunnable,
3531    WaitingOnLanding,
3532    CoolingDown,
3533    OrdinaryCapacity,
3534    UrgentCapacity,
3535    InterruptGate,
3536}
3537
3538impl SkipReason {
3539    fn key(self) -> &'static str {
3540        match self {
3541            Self::ClaimUnavailable => "claim_unavailable",
3542            Self::RereadFailed => "reread_failed",
3543            Self::NoLongerRunnable => "no_longer_runnable",
3544            Self::WaitingOnLanding => "waiting_on_landing",
3545            Self::CoolingDown => "cooling_down",
3546            Self::OrdinaryCapacity => "ordinary_capacity",
3547            Self::UrgentCapacity => "urgent_capacity",
3548            Self::InterruptGate => "interrupt_gate",
3549        }
3550    }
3551
3552    fn describe(self) -> &'static str {
3553        match self {
3554            Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3555            Self::RereadFailed => "could not re-read it",
3556            Self::NoLongerRunnable => "no longer runnable",
3557            Self::WaitingOnLanding => "waiting on landing",
3558            Self::CoolingDown => "quota cooldown",
3559            Self::OrdinaryCapacity => "no free ordinary slot",
3560            Self::UrgentCapacity => "urgent slot busy",
3561            Self::InterruptGate => "withheld by the interrupt sequence",
3562        }
3563    }
3564}
3565
3566/// A reason count from a completed dispatch scan.
3567#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3568pub struct DispatchReasonCount {
3569    /// Stable string key, so readers can preserve future reasons.
3570    pub reason: String,
3571    /// Candidates skipped for this reason.
3572    pub count: usize,
3573}
3574
3575/// Observations from a completed scan, not a fresh queue estimate.
3576#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3577pub struct DispatchWait {
3578    /// Runnable candidates before the interrupt gate.
3579    pub runnable: usize,
3580    /// Counts in descending order, with stable reason order for ties.
3581    pub reasons: Vec<DispatchReasonCount>,
3582}
3583
3584type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3585
3586fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3587    if runnable == 0 {
3588        return None;
3589    }
3590    let mut counts = std::collections::BTreeMap::new();
3591    for (_, reason) in skips {
3592        *counts.entry(*reason).or_insert(0usize) += 1;
3593    }
3594    let mut counts: Vec<_> = counts.into_iter().collect();
3595    counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3596    Some(DispatchWait {
3597        runnable,
3598        reasons: counts
3599            .into_iter()
3600            .map(|(reason, count)| DispatchReasonCount {
3601                reason: reason.key().to_owned(),
3602                count,
3603            })
3604            .collect(),
3605    })
3606}
3607
3608fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3609    before
3610        .iter()
3611        .filter(|id| !after.iter().any(|task| &task.id == *id))
3612        .map(|id| (id.clone(), SkipReason::InterruptGate))
3613        .collect()
3614}
3615
3616fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3617    if *previous == current {
3618        return false;
3619    }
3620    *previous = current;
3621    true
3622}
3623
3624struct DispatchClaim {
3625    task: Task,
3626    claim: crate::queue::Claim,
3627    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3628}
3629
3630/// Claim and re-read before choosing a lane: a queue listing may predate an
3631/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3632fn claim_dispatch(
3633    queue: &Queue,
3634    candidate: &Task,
3635    cooling_down: bool,
3636    ordinary: &Arc<tokio::sync::Semaphore>,
3637    urgent: &Arc<tokio::sync::Semaphore>,
3638) -> std::result::Result<DispatchClaim, SkipReason> {
3639    let claim = queue
3640        .claim(&candidate.id)
3641        .map_err(|_| SkipReason::ClaimUnavailable)?;
3642    let task = match queue.get(&candidate.id) {
3643        Ok(t) if t.status.runnable() => t,
3644        Ok(_) => return Err(SkipReason::NoLongerRunnable),
3645        Err(e) => {
3646            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3647            return Err(SkipReason::RereadFailed);
3648        }
3649    };
3650    let resume = land_resume_state(&task);
3651    if resume == LandResume::StillWaiting {
3652        return Err(SkipReason::WaitingOnLanding);
3653    }
3654    let priority = resume == LandResume::Ready;
3655    if !priority && cooling_down {
3656        return Err(SkipReason::CoolingDown);
3657    }
3658    // Never borrow an ordinary slot when the single urgent slot is busy.
3659    // Keep scanning other candidates when either pool has no free slot.
3660    let permit = match permit_kind(priority, task.urgent) {
3661        PermitKind::None => None,
3662        PermitKind::Urgent => Some(
3663            Arc::clone(urgent)
3664                .try_acquire_owned()
3665                .map_err(|_| SkipReason::UrgentCapacity)?,
3666        ),
3667        PermitKind::Ordinary => Some(
3668            Arc::clone(ordinary)
3669                .try_acquire_owned()
3670                .map_err(|_| SkipReason::OrdinaryCapacity)?,
3671        ),
3672    };
3673    // Persist the dispatch order under the claim, before config discovery or
3674    // coordination waits can reorder concurrent starts.
3675    let stamp = Timestamp::now();
3676    let mut task = task;
3677    task.dispatched_at = Some(stamp);
3678    if let Err(e) = queue.modify(&task.id, |t| {
3679        t.dispatched_at = Some(stamp);
3680        true
3681    }) {
3682        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3683    }
3684    Ok(DispatchClaim {
3685        task,
3686        claim,
3687        permit,
3688    })
3689}
3690
3691/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3692/// teardown and cannot skip the teardown on an early return.
3693///
3694/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3695/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3696/// land approval that has since been answered is dispatched outside that
3697/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3698/// the whole point of parking there is that it must not queue behind
3699/// whatever else the loop happens to be running, even at the default of one.
3700/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3701/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3702/// these exemptions is still subject to the interrupt gate below, urgent
3703/// included: a land-resume or urgent candidate is exactly as much "something
3704/// else running" as an ordinary one from the interrupt sequence's point of
3705/// view, and letting either slip through while a run is being parked, or
3706/// while the interrupt task itself has the floor, is precisely the second
3707/// run 75dd's own "at most one run, ever, at once" guarantee must never
3708/// allow - see [`Interrupt`]'s own doc.
3709#[derive(Serialize, Deserialize)]
3710struct ServiceWorker {
3711    opts: Opts,
3712    queue: PathBuf,
3713    worktrees_root: PathBuf,
3714    operation: String,
3715}
3716
3717fn load_conductor(home: &Path) -> Result<Conductor> {
3718    match std::fs::read(home.join("conductor-state.json")) {
3719        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3720        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3721        Err(error) => Err(error.into()),
3722    }
3723}
3724
3725fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3726    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3727        .into_iter()
3728        .map(|c| c.task)
3729        .collect();
3730    let stalled = stalled_tasks(queue, home, Timestamp::now());
3731    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3732    let finished = finished_tasks(queue)
3733        .into_iter()
3734        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3735        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3736        .collect();
3737    let queued = queued_tasks(queue)
3738        .into_iter()
3739        .filter(|t| !live.contains(&t.id))
3740        .collect();
3741    (queued, stalled, finished)
3742}
3743
3744// Separate latest dispatch and worker receipts expose version handoff and skips
3745// without erasing the last completed scan or treating observations as authority.
3746fn retention_service_receipt(
3747    home: &Path,
3748    operation: &str,
3749    phase: &str,
3750    outcome: &str,
3751    detail: &str,
3752    cfg: Option<&Config>,
3753) {
3754    if !matches!(operation, "housekeeping" | "disk-pressure") {
3755        return;
3756    }
3757    let receipt = serde_json::json!({"checked_at": Timestamp::now(),
3758        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
3759        "operation": operation, "outcome": outcome, "detail": detail,
3760        "auto_fold": cfg.map(|c| c.disk.auto_fold),
3761        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
3762    if let Err(error) = crate::fold_evidence::atomic_write(
3763        &home.join(format!("source-eviction-{operation}-{phase}.json")),
3764        &serde_json::to_vec(&receipt).expect("service receipt"),
3765    ) {
3766        tracing::warn!("retention service receipt failed: {error:#}");
3767    }
3768}
3769
3770async fn start_service(
3771    home: &Path,
3772    opts: &Opts,
3773    queue: &Queue,
3774    worktrees_root: &Path,
3775    operation: &str,
3776    cfg: Option<&Config>,
3777    busy: bool,
3778) -> Result<()> {
3779    // Fetch policy is live configuration, unlike question recovery capacity.
3780    // Reload before both cadence and eligibility, including disabled -> enabled.
3781    let fetch_cfg = if operation == "fetch" {
3782        match prepare(&opts.repo, opts) {
3783            Ok(cfg) => Some(cfg),
3784            Err(error) => {
3785                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3786                return Ok(());
3787            }
3788        }
3789    } else {
3790        None
3791    };
3792    let cfg = fetch_cfg.as_ref().or(cfg);
3793    let ticks = home.join("service-ticks");
3794    std::fs::create_dir_all(&ticks)?;
3795    let receipt = ticks.join(format!("daemon-{operation}"));
3796    let last = std::fs::read(&receipt)
3797        .ok()
3798        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3799    let interval = match operation {
3800        "disk-pressure" => 30,
3801        "chat-goals" => 60,
3802        "cache" => CACHE_CHECK_INTERVAL_SECS,
3803        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3804        _ => opts.poll.as_secs().max(1),
3805    };
3806    let now = Timestamp::now();
3807    if !cache_check_due(last, now, interval) {
3808        retention_service_receipt(
3809            home,
3810            operation,
3811            "dispatch",
3812            "skipped",
3813            "cadence not due",
3814            cfg,
3815        );
3816        return Ok(());
3817    }
3818    let key = format!("service:daemon-{operation}");
3819    if crate::worker::active(home)?
3820        .iter()
3821        .any(|job| job.key == key)
3822    {
3823        retention_service_receipt(
3824            home,
3825            operation,
3826            "dispatch",
3827            "skipped",
3828            "service worker already active",
3829            cfg,
3830        );
3831        return Ok(());
3832    }
3833    let eligible = match operation {
3834        "conductor" => {
3835            let (queued, stalled, finished) = conductor_work(queue, home);
3836            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3837                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3838        }
3839        "maintenance" => {
3840            queue.list().iter().any(|task| {
3841                crate::triage::disk_wait_eligible(task)
3842                    && task
3843                        .disk_checked_at
3844                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
3845            }) || Questions::at(home.join("questions"))
3846                .list_for_effects()
3847                .iter()
3848                .any(|q| {
3849                    q.chosen_action().is_some_and(|action| action.maintenance())
3850                        && !home
3851                            .join("choice-actions")
3852                            .join(format!("{}.json", q.id))
3853                            .exists()
3854                })
3855        }
3856        "housekeeping" => !busy && runnable(queue).is_empty(),
3857        "cache" => {
3858            !busy
3859                && !runnable(queue).is_empty()
3860                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3861        }
3862        "disk-pressure" => busy,
3863        "fetch" => {
3864            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3865        }
3866        "chat-goals" => crate::talk::Talks::at(home.join("talks"))
3867            .list()
3868            .iter()
3869            .any(|talk| {
3870                talk.status.open()
3871                    && talk.pending.is_empty()
3872                    && talk.pending_attachments.is_empty()
3873                    && talk.goals.iter().any(|goal| goal.active())
3874            }),
3875        _ => false,
3876    };
3877    if !eligible {
3878        retention_service_receipt(
3879            home,
3880            operation,
3881            "dispatch",
3882            "skipped",
3883            if operation == "housekeeping" {
3884                "active work or runnable task queue"
3885            } else {
3886                "no active work; idle housekeeping owns scan"
3887            },
3888            cfg,
3889        );
3890        return Ok(());
3891    }
3892    retention_service_receipt(
3893        home,
3894        operation,
3895        "dispatch",
3896        "launching",
3897        "eligible and cadence due",
3898        cfg,
3899    );
3900    let request = ServiceWorker {
3901        opts: opts.absolute()?,
3902        queue: std::path::absolute(queue.root())?,
3903        worktrees_root: std::path::absolute(worktrees_root)?,
3904        operation: operation.to_owned(),
3905    };
3906    if let Err(error) =
3907        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3908    {
3909        retention_service_receipt(
3910            home,
3911            operation,
3912            "dispatch",
3913            "error",
3914            &format!("worker launch: {error:#}"),
3915            cfg,
3916        );
3917        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3918    }
3919    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3920    Ok(())
3921}
3922
3923/// Finite maintenance jobs survive scheduler replacement without duplicating
3924/// agent calls or cancelling an operation between its effect and receipt.
3925pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3926    let request: ServiceWorker = serde_json::from_value(payload)?;
3927    let opts = &request.opts;
3928    let queue = Queue::at(request.queue);
3929    let questions = Questions::at(home.join("questions"));
3930    match request.operation.as_str() {
3931        "chat-goals" => {
3932            let talks = crate::talk::Talks::at(home.join("talks"));
3933            crate::chat_goal_runtime::sweep(&talks, false).await;
3934        }
3935        "maintenance" => {
3936            apply_maintenance_choices(&queue, &questions, home).await;
3937            triage::monitor_disk_waits(
3938                &queue,
3939                &questions,
3940                opts.config.as_deref(),
3941                Timestamp::now(),
3942            );
3943        }
3944        "conductor" => {
3945            let path = home.join("conductor-state.json");
3946            let mut conductor = load_conductor(home)?;
3947            let (queued, stalled, finished) = conductor_work(&queue, home);
3948            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3949                && conductor.worth_a_look(&queue, &stalled, &finished)
3950            {
3951                let cfg = prepare(&opts.repo, opts)?;
3952                conductor
3953                    .maybe_run(
3954                        &cfg,
3955                        &opts.repo,
3956                        &queue,
3957                        &questions,
3958                        home,
3959                        &queued,
3960                        &stalled,
3961                        &finished,
3962                        opts.max_attempts,
3963                    )
3964                    .await;
3965                let temporary = path.with_extension("json.tmp");
3966                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3967                std::fs::rename(temporary, path)?;
3968            }
3969        }
3970        "fetch" => {
3971            let cfg = prepare(&opts.repo, opts)?;
3972            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3973                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3974                tracing::debug!("fetch origins: {outcome:?}");
3975            }
3976        }
3977        "cache" => {
3978            if task_jobs(home)?.is_empty() {
3979                let mut checked = None;
3980                maybe_prune_cache_between_runs(
3981                    &opts.repo,
3982                    opts,
3983                    home,
3984                    &Stop::new(),
3985                    &mut checked,
3986                    Timestamp::now(),
3987                )
3988                .await;
3989            }
3990        }
3991        "disk-pressure" => {
3992            if let Ok(cfg) = prepare(&opts.repo, opts) {
3993                retention_service_receipt(
3994                    home,
3995                    "disk-pressure",
3996                    "worker",
3997                    "running",
3998                    "retention sweep",
3999                    Some(&cfg),
4000                );
4001                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4002                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
4003                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
4004                }
4005                if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
4006                    tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
4007                }
4008                for current in current_work(home, Timestamp::now()) {
4009                    if let Ok(state) = RunState::load_under(&current.run, home)
4010                        && let Some(reason) = disk_gate(&state.repo, &state.config)
4011                    {
4012                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
4013                            job.key.strip_prefix("task:") == Some(current.task.as_str())
4014                        }) {
4015                            request_task_park(
4016                                home,
4017                                &job,
4018                                crate::run::ParkCause::Interrupt {
4019                                    reason: reason.clone(),
4020                                },
4021                            )?;
4022                        }
4023                        notices::raise_in(
4024                            home,
4025                            Notice::warn(
4026                                "disk:pressure",
4027                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
4028                            ),
4029                        );
4030                    }
4031                }
4032            } else {
4033                retention_service_receipt(
4034                    home,
4035                    "disk-pressure",
4036                    "worker",
4037                    "error",
4038                    "configuration could not be loaded",
4039                    None,
4040                );
4041            }
4042        }
4043        "housekeeping" => {
4044            if task_jobs(home)?.is_empty() {
4045                match prepare(&opts.repo, opts) {
4046                    Ok(cfg) => {
4047                        retention_service_receipt(
4048                            home,
4049                            "housekeeping",
4050                            "worker",
4051                            "running",
4052                            "retention sweep",
4053                            Some(&cfg),
4054                        );
4055                        crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4056                    }
4057                    Err(error) => retention_service_receipt(
4058                        home,
4059                        "housekeeping",
4060                        "worker",
4061                        "error",
4062                        &format!("configuration: {error:#}"),
4063                        None,
4064                    ),
4065                }
4066                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
4067                resweep_superseded_attempts(&queue, home);
4068                triage_held(&queue, home, opts).await;
4069            } else {
4070                retention_service_receipt(
4071                    home,
4072                    "housekeeping",
4073                    "worker",
4074                    "skipped",
4075                    "task worker became active",
4076                    None,
4077                );
4078            }
4079        }
4080        operation => bail!("unknown daemon service {operation}"),
4081    }
4082    Ok(())
4083}
4084
4085/// Only a different request under the same key is a dispatch handoff race.
4086/// Our own unacknowledged reservation is a startup failure, not competing work:
4087/// stop dispatch without fencing it, so an already detached child may still run.
4088fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
4089    let key = format!("task:{}", request.task);
4090    let payload = serde_json::to_value(request)?;
4091    if crate::worker::active(home)?
4092        .iter()
4093        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
4094    {
4095        tracing::warn!(
4096            "task {} acquired a competing worker reservation: {error:#}",
4097            crate::run::short_of(&request.task)
4098        );
4099        return Ok(());
4100    }
4101    tracing::error!("task worker startup stopped dispatch: {error:#}");
4102    notices::raise_in(
4103        home,
4104        Notice::error(
4105            "loop:worker-startup",
4106            // Startup diagnostics may contain private child-process details;
4107            // keep them in the local error/log rather than the chat or notifier.
4108            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),
4109        ).link(Link::Task { id: request.task.clone() }),
4110    );
4111    Err(error).with_context(|| {
4112        format!(
4113            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
4114            crate::run::short_of(&request.task)
4115        )
4116    })
4117}
4118
4119async fn poll(
4120    opts: &Opts,
4121    queue: &Queue,
4122    status: &Arc<Mutex<Status>>,
4123    home: &Path,
4124    worktrees_root: &Path,
4125    stop: &Stop,
4126    limits: DispatchLimits,
4127) -> Result<()> {
4128    let mut attempted = Vec::new();
4129    let mut settling_once_services = false;
4130    let interrupt_path = home.join("scheduler-interrupt.json");
4131    let mut interrupt = match std::fs::read(&interrupt_path) {
4132        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
4133        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
4134        Err(error) => return Err(error.into()),
4135    };
4136    let mut previous = std::collections::BTreeSet::<String>::new();
4137    let mut previous_skips = DispatchSkips::new();
4138    while !stop.stopped() {
4139        let jobs: Vec<_> = crate::worker::active(home)?
4140            .into_iter()
4141            .filter(|job| job.kind == "task")
4142            .collect();
4143        let requests: Vec<_> = jobs
4144            .iter()
4145            .map(|job| {
4146                serde_json::from_value::<TaskWorker>(job.payload.clone())
4147                    .with_context(|| format!("read live task worker {}", job.id))
4148            })
4149            .collect::<Result<_>>()?;
4150        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4151        let owned: std::collections::BTreeSet<_> = requests
4152            .iter()
4153            .filter(|r| !r.standalone)
4154            .map(|r| r.task.clone())
4155            .collect();
4156        let current: Vec<_> = requests
4157            .iter()
4158            .zip(&jobs)
4159            .filter(|(request, _)| !request.standalone)
4160            .map(|(request, job)| Current {
4161                worker: Some(job.id.clone()),
4162                task: request.task.clone(),
4163                run: queue
4164                    .get(&request.task)
4165                    .ok()
4166                    .and_then(|task| task.execution_runs().last().cloned())
4167                    .unwrap_or_default(),
4168            })
4169            .collect();
4170        {
4171            let mut snapshot = lock(status);
4172            snapshot.polls += 1;
4173            snapshot.completed += previous.difference(&owned).count();
4174            snapshot.current = current;
4175            snapshot.idle = owned.is_empty();
4176            snapshot.dispatch_wait = None;
4177        }
4178        previous = owned.clone();
4179        stop.busy.store(owned.len(), Ordering::SeqCst);
4180
4181        // Slots are reconstructed from durable reservations and OS-held worker
4182        // leases, not this scheduler's lifetime or mutable task urgency.
4183        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4184        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4185        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4186        let mut permits = Vec::new();
4187        sweep_stale_claims(queue, STALE_CLAIM);
4188        reclaim_orphaned_running(queue, opts.max_attempts, &live);
4189        reclaim_abandoned_runs(home, Timestamp::now());
4190        let questions = Questions::at(home.join("questions"));
4191
4192        // Deterministic: no model, run before the conductor sees anything so
4193        // its input reflects the queue's current, already-resolved state.
4194        crate::task_chat::sweep(
4195            queue,
4196            &crate::talk::Talks::at(home.join("talks")),
4197            &questions,
4198            home,
4199        );
4200        if let Err(error) = crate::task_inquiry::Outbox::at(home)
4201            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4202        {
4203            tracing::warn!("task inquiry delivery remains pending: {error:#}");
4204        }
4205        repair_choice_offers(&questions);
4206        resolve_blockers(queue, &questions);
4207        apply_task_choice_actions(queue, &questions, home);
4208        triage::apply_answers(queue, &questions);
4209        reconcile_task_questions(queue, &questions);
4210        let talks = crate::talk::Talks::at(home.join("talks"));
4211        crate::chat_notify::sweep(queue, &talks, home);
4212        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4213        crate::chat_watch::sweep(home, &talks);
4214        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4215            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4216        }
4217        let mut turns = tokio::task::JoinSet::new();
4218        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4219        // start_turns dispatches detached turns; no paid work lives in this set.
4220        while turns.join_next().await.is_some() {}
4221
4222        crate::consult::start_services(
4223            home,
4224            &opts.repo,
4225            limits.recovery_cfg.as_ref(),
4226            opts.config.as_deref(),
4227        )
4228        .await?;
4229        for operation in [
4230            "conductor",
4231            "maintenance",
4232            "housekeeping",
4233            "disk-pressure",
4234            "cache",
4235            "fetch",
4236            "chat-goals",
4237        ] {
4238            // Once an idle --once drain starts settling services, subsequent
4239            // scans only consume their effects. An expired cadence receipt
4240            // must not start another service and keep the drain alive.
4241            if settling_once_services {
4242                break;
4243            }
4244            if operation == "chat-goals" && stop.parking() {
4245                continue;
4246            }
4247            start_service(
4248                home,
4249                opts,
4250                queue,
4251                worktrees_root,
4252                operation,
4253                limits.recovery_cfg.as_ref(),
4254                !live.is_empty(),
4255            )
4256            .await?;
4257        }
4258        let latest = crate::worker::active(home)?;
4259        if latest.iter().any(|job| job.key == "service:daemon-cache")
4260            || latest
4261                .iter()
4262                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4263        {
4264            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4265            continue;
4266        }
4267        let candidates: Vec<Task> = runnable(queue)
4268            .into_iter()
4269            .filter(|task| !live.contains(&task.id))
4270            .filter(|task| !opts.once || !attempted.contains(&task.id))
4271            .collect();
4272        let in_flight: Vec<_> = owned.iter().cloned().collect();
4273        let prior_interrupt = std::mem::discriminant(&interrupt);
4274        interrupt = advance_interrupt_tick(
4275            limits.pause_for_interrupts,
4276            interrupt,
4277            &in_flight,
4278            &candidates,
4279        );
4280        // Same-variant transitions preserve their identities. Only an actual
4281        // transition needs a durable write, atomically before sending controls.
4282        if prior_interrupt != std::mem::discriminant(&interrupt) {
4283            let temporary = interrupt_path.with_extension("json.tmp");
4284            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4285            std::fs::rename(temporary, &interrupt_path)?;
4286        }
4287        if let Interrupt::Parking {
4288            parked,
4289            interrupt_task,
4290        } = &interrupt
4291        {
4292            for job in jobs.iter().filter(|job| {
4293                parked
4294                    .iter()
4295                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4296            }) {
4297                if crate::worker::control(home, &job.key)?.is_none() {
4298                    request_task_park(
4299                        home,
4300                        job,
4301                        crate::run::ParkCause::Interrupt {
4302                            reason: format!(
4303                                "task {} asked to run first",
4304                                crate::run::short_of(interrupt_task)
4305                            ),
4306                        },
4307                    )?;
4308                }
4309            }
4310        }
4311        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
4312        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4313        let mut skips = interrupt_skips(&candidate_ids, &candidates);
4314        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4315        let mut started = false;
4316        let mut resync = false;
4317        for candidate in candidates {
4318            if stop.stopped() {
4319                break;
4320            }
4321            let DispatchClaim {
4322                task,
4323                claim,
4324                permit,
4325            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
4326                Ok(claim) => claim,
4327                Err(reason) => {
4328                    skips.insert((candidate.id, reason));
4329                    continue;
4330                }
4331            };
4332            if crate::worker::active(home)?
4333                .iter()
4334                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4335            {
4336                drop(claim);
4337                resync = true;
4338                break;
4339            }
4340            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4341            let request = TaskWorker {
4342                opts: opts.absolute()?,
4343                queue: std::path::absolute(queue.root())?,
4344                task: task.id.clone(),
4345                lane,
4346                standalone: false,
4347            };
4348            // Keep the claim until spawn acknowledges the worker's durable
4349            // reservation. The worker then claims and re-reads before attempt.
4350            if let Err(error) = crate::worker::spawn(
4351                home,
4352                "task",
4353                &format!("task:{}", task.id),
4354                serde_json::to_value(&request)?,
4355            )
4356            .await
4357            {
4358                task_worker_spawn_error(home, &request, error)?;
4359                drop(claim);
4360                resync = true;
4361                break;
4362            }
4363            drop(claim);
4364            permits.extend(permit);
4365            attempted.push(task.id);
4366            started = true;
4367        }
4368        if !resync && !stop.stopped() {
4369            if !started {
4370                lock(status).dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
4371            }
4372            if changed_dispatch_skips(&mut previous_skips, skips) {
4373                if previous_skips.is_empty() {
4374                    tracing::info!("dispatch skips cleared");
4375                }
4376                for (task, reason) in &previous_skips {
4377                    tracing::info!(
4378                        task,
4379                        reason = reason.key(),
4380                        "task {} skipped: {}",
4381                        crate::run::short_of(task),
4382                        reason.describe()
4383                    );
4384                }
4385            }
4386        }
4387        if started || resync {
4388            continue;
4389        }
4390        if owned.is_empty() && opts.once {
4391            settling_once_services = true;
4392            // These finite services can own queue claims or publish answers.
4393            // A skipped claim is not an idle queue until they have finished;
4394            // scan again afterwards so their changes are actually scheduled.
4395            if crate::worker::active(home)?.iter().any(|job| {
4396                job.kind == "daemon-service"
4397                    && matches!(
4398                        job.key.as_str(),
4399                        "service:daemon-housekeeping"
4400                            | "service:daemon-conductor"
4401                            | "service:daemon-maintenance"
4402                    )
4403            }) {
4404                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4405                continue;
4406            }
4407            break;
4408        }
4409        stop.idle(if live.is_empty() {
4410            opts.poll
4411        } else {
4412            RECHECK_WHILE_BUSY.min(opts.poll)
4413        })
4414        .await;
4415    }
4416    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4417    // every queue claim and Runner driver lease through outcome settlement.
4418    stop.busy.store(0, Ordering::SeqCst);
4419    lock(status).dispatch_wait = None;
4420    Ok(())
4421}
4422
4423/// A maintenance pass may briefly own the same record while a worker starts.
4424/// Wait without blocking the executor or charging an agent attempt, then read
4425/// ownership again under the acquired lock. Other I/O failures still fail closed.
4426async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4427    let busy = |error: &anyhow::Error| {
4428        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4429            error.kind() == std::io::ErrorKind::WouldBlock
4430                || cfg!(windows) && error.raw_os_error() == Some(33)
4431        })
4432    };
4433    match crate::pr_head::owner_lock(home, id) {
4434        Ok(lock) => return Ok(lock),
4435        Err(error) if busy(&error) => {}
4436        Err(error) => return Err(error),
4437    }
4438    let wait = RunState::load_under(id, home)?
4439        .config
4440        .graph
4441        .timeout_resource_wait;
4442    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4443}
4444
4445/// Historical successors do not revoke a still-resumable public owner. Scan
4446/// under the same lock as publication/driver claims, and fail closed on unknown
4447/// history before spending another attempt.
4448async fn public_resume_owner(
4449    home: &Path,
4450    runs: &[String],
4451    repo: &Path,
4452) -> Result<Option<RunState>> {
4453    let mut owner = None;
4454    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4455        let _lock = resume_owner_lock(home, id).await?;
4456        let state = RunState::load_under(id, home)?;
4457        if state.released()
4458            || state.retired_to.is_some()
4459            || state.pr_taken_over_by.is_some()
4460            || !crate::handover::landing_checkpoint(&state)
4461        {
4462            continue;
4463        }
4464        anyhow::ensure!(
4465            crate::git::toplevel(&state.repo).await?.canonicalize()?
4466                == crate::git::toplevel(repo).await?.canonicalize()?,
4467            "public owner repository differs; inspect run lineage"
4468        );
4469        anyhow::ensure!(
4470            owner.is_none(),
4471            "multiple retained public owners; inspect run lineage"
4472        );
4473        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4474            anyhow::bail!(reason.diagnostic(&state));
4475        }
4476        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4477        anyhow::ensure!(
4478            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4479            "public owner's driver is live or unknown; wait before retrying"
4480        );
4481        owner = Some(state);
4482    }
4483    Ok(owner)
4484}
4485
4486/// Run one claimed task to a terminal status and record the outcome.
4487///
4488/// Every transition is flushed to the queue as it happens, so the state on disk
4489/// is what actually occurred rather than what this process still intends to
4490/// write.
4491async fn attempt(
4492    opts: &Opts,
4493    queue: &Queue,
4494    status: &Arc<Mutex<Status>>,
4495    stop: &Stop,
4496    interrupt_pause: crate::graph::Pause,
4497    task: &mut Task,
4498) -> Vec<QuotaLoss> {
4499    if let Some(request) = task.sync_only.clone() {
4500        Box::pin(attempt_sync_only(
4501            queue,
4502            status,
4503            stop,
4504            interrupt_pause,
4505            task,
4506            request,
4507        ))
4508        .await;
4509        return Vec::new();
4510    }
4511    let repo = repo_for(task, &opts.repo);
4512    tracing::info!(
4513        "task {} — {} (repo {})",
4514        task.short(),
4515        task.title,
4516        repo.display()
4517    );
4518
4519    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4520        Ok(owner) => owner,
4521        Err(e) => {
4522            task.hold_machine(Some(format!(
4523                "Cannot verify existing public owner: {e:#}; no attempt started."
4524            )));
4525            record(queue, task);
4526            return Vec::new();
4527        }
4528    };
4529    let resume_runs = public_owner
4530        .as_ref()
4531        .map(|s| vec![s.id.clone()])
4532        .unwrap_or_else(|| task.execution_runs().to_vec());
4533
4534    // A stop spends no agent resources and uses the saved landing owner.
4535    // Current roster edits, missing attachments or a failed config fetch must
4536    // never turn it into a new implementation, or prevent a PR from closing.
4537    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4538        && previous
4539            .merge_decision
4540            .as_ref()
4541            .is_some_and(|decision| !decision.closed)
4542        && previous.status != RunStatus::Landing
4543        && !crate::merge_decision::resumable_hold(&previous)
4544    {
4545        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)));
4546        record(queue, task);
4547        return Vec::new();
4548    }
4549    let stop_owner = resume_runs
4550        .last()
4551        .and_then(|id| RunState::load(id).ok())
4552        .filter(|state| {
4553            crate::merge_decision::resumable_hold(state)
4554                || state.status == RunStatus::Landing
4555                    && state.land_approval.as_ref().is_some_and(|binding| {
4556                        Questions::open()
4557                            .get_for_effects(&binding.question)
4558                            .is_ok_and(|q| {
4559                                q.run == state.id
4560                                    && q.resolution()
4561                                        .as_deref()
4562                                        .is_some_and(crate::merge_decision::stops)
4563                            })
4564                    })
4565        });
4566    if let Some(owner) = stop_owner {
4567        let mut runner = match Runner::resume(&owner.id) {
4568            Ok(runner) => runner,
4569            Err(e) => {
4570                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4571                record(queue, task);
4572                return Vec::new();
4573            }
4574        };
4575        runner.on_pause(stop.pause());
4576        runner.watch_interrupt(interrupt_pause);
4577        let quota_before = runner.state.quota.clone();
4578        let before_start = task.clone();
4579        task.start(owner.id.clone());
4580        if let Err(error) = queue.put(task) {
4581            *task = before_start;
4582            let error = runner.fail_startup("task-start", error);
4583            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4584                task.record_startup_failure(failure.clone());
4585            }
4586            task.hold_manual(Some(format!(
4587                "Could not persist task start; no agents dispatched: {error:#}"
4588            )));
4589            record(queue, task);
4590            return Vec::new();
4591        }
4592        lock(status).current.push(Current {
4593            worker: None,
4594            task: task.id.clone(),
4595            run: owner.id,
4596        });
4597        runner.state.carry_dispatched_resumes(task);
4598        runner.state.next_pass_task_entry = true;
4599        let result = runner.execute().await;
4600        return finish_attempt(
4601            opts.max_attempts,
4602            queue,
4603            task,
4604            &runner.state,
4605            &quota_before,
4606            result,
4607        );
4608    }
4609
4610    if let Some(owner) = &public_owner
4611        && (task.fresh_start || !may_resume_run(owner, task))
4612    {
4613        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)));
4614        record(queue, task);
4615        return Vec::new();
4616    }
4617
4618    if let Some(state) = task
4619        .execution_runs()
4620        .last()
4621        .and_then(|id| RunState::load(id).ok())
4622        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4623    {
4624        task.hold_machine(Some(reason));
4625        record(queue, task);
4626        return Vec::new();
4627    }
4628
4629    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4630        && !task.fresh_start
4631        && task.pr_recovery.is_none()
4632    {
4633        // Authorization still takes the owner lock and execution lease and
4634        // rechecks liveness, retained HEAD and ownership before saving.
4635        let authorized = if crate::repair_budget::conflict_pending(task, &held) {
4636            true
4637        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4638            let home = queue.root().parent().expect("queue has a home");
4639            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4640                Ok(()) => true,
4641                Err(error) => {
4642                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4643                    false
4644                }
4645            }
4646        } else {
4647            false
4648        };
4649        if !authorized {
4650            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())));
4651            // Retain the existing stop identity when an old release reached the queue.
4652            task.base_sync_notice(&held);
4653            task.resume_override = None;
4654            record(queue, task);
4655            return Vec::new();
4656        }
4657    }
4658    let unfinished = (!task.fresh_start)
4659        .then(|| unfinished_run(&resume_runs, task.short()))
4660        .flatten()
4661        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4662    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4663    if task.repair_grants.last().is_some_and(|receipt| {
4664        task.execution_runs().last() == Some(&receipt.request.run)
4665            && task.operator_decided_at == receipt.decision
4666            && previous
4667                .as_ref()
4668                .is_none_or(|run| run.id != receipt.request.run)
4669    }) {
4670        task.hold_unrequested_retry(Some(
4671            "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(),
4672        ));
4673        record(queue, task);
4674        return Vec::new();
4675    }
4676    if let Some(id) = &task.disk_resume_run
4677        && unfinished.as_ref() != Some(id)
4678    {
4679        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()));
4680        record(queue, task);
4681        return Vec::new();
4682    }
4683
4684    if !task.fresh_start
4685        && task.pr_recovery.is_none()
4686        && task.review_branch.is_none()
4687        && task.resume_override.is_none()
4688        && previous
4689            .as_ref()
4690            .is_some_and(|run| run.retired_to.is_some())
4691        && unfinished.is_none()
4692    {
4693        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()));
4694        record(queue, task);
4695        return Vec::new();
4696    }
4697
4698    let saved_recovery = previous.as_ref().filter(|run| {
4699        task.replacement.is_none()
4700            && task.pr_recovery.as_ref().is_some_and(|selected| {
4701                selected
4702                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4703                    .is_ok()
4704                    && selected_starter(selected, Some(run), unfinished.as_deref())
4705                        == Starter::Resume(run.id.clone())
4706            })
4707    });
4708
4709    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4710    // failure here is the network's or the operator's, not the task's: hold
4711    // without spending an attempt, never fall back to a possibly stale copy.
4712    let explicit = match &task.overrides {
4713        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4714        Some(_) => opts.config.as_deref(),
4715        None => opts.config.as_deref(),
4716    };
4717    let (mut config, layers) = if let Some(run) = saved_recovery {
4718        // A matching resume owns its resolved configuration and evidence;
4719        // current layers and inherited overrides only configure new work.
4720        let mut saved = run.clone();
4721        if let Err(e) = saved.configure_recovery_resume() {
4722            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4723            record(queue, task);
4724            return Vec::new();
4725        }
4726        (saved.config, Vec::new())
4727    } else {
4728        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4729            Ok(loaded) => loaded,
4730            Err(e) => {
4731                let reason = format!("[config] {e:#}");
4732                record_config_failure(task, &e);
4733                task.last_error = Some(reason.clone());
4734                task.hold_machine(Some(reason));
4735                record(queue, task);
4736                return Vec::new();
4737            }
4738        };
4739        if let Err(e) = apply_options(&mut config, opts, task) {
4740            task.hold_manual(Some(format!(
4741                "[config] {e:#}; correct the merge override before releasing the task"
4742            )));
4743            record(queue, task);
4744            return Vec::new();
4745        }
4746        if let Some(selected) = &task.pr_recovery
4747            && let Err(e) = selected.configure(&mut config)
4748        {
4749            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4750            record(queue, task);
4751            return Vec::new();
4752        }
4753        (config, layers)
4754    };
4755    let config_evidence = crate::pr_recovery::ConfigEvidence {
4756        layers,
4757        overrides: task.overrides.clone(),
4758        daemon_merge: task
4759            .overrides
4760            .as_ref()
4761            .is_none_or(|o| o.inherit_daemon_options)
4762            .then(|| opts.merge.clone())
4763            .flatten(),
4764    };
4765    apply_task_implementers(&mut config, task);
4766    if let Some(replacement) = &task.replacement {
4767        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4768            old.liveness(false) == Liveness::Dead
4769                && old.merge_decision.as_ref().is_some_and(|d| {
4770                    d.closed
4771                        && d.question == replacement.question
4772                        && d.replacement_run.as_ref().is_none_or(|run| {
4773                            task.execution_runs().last() == Some(run)
4774                                && RunState::load(run).is_ok_and(|current| {
4775                                    current.replaces.as_ref().is_some_and(|pin| {
4776                                        pin.question == replacement.question
4777                                            && pin.agent == replacement.agent
4778                                    })
4779                                })
4780                        })
4781                })
4782        });
4783        if !safe {
4784            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()));
4785            record(queue, task);
4786            return Vec::new();
4787        }
4788        match config.agent(&replacement.agent) {
4789            Ok(agent) if crate::agent::installed(agent) => {}
4790            _ => {
4791                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)));
4792                record(queue, task);
4793                return Vec::new();
4794            }
4795        }
4796        config.graph.implementers = 1;
4797        config.graph.land_approval = true;
4798        config.merge.mode = MergeMode::Pr;
4799        config.graph.selected_implementer = Some(replacement.agent.clone());
4800    }
4801    let p = phrases(&config.graph.language);
4802    let start_failed = p.could_not_start;
4803    // Resolve once for both admission and settlement. The inputs are the
4804    // task's explicit sources (never prose), plus an explicit review source's
4805    // current head; review-only runs may rebase later, and neither fact can
4806    // refund a failed automatic generation.
4807    if let Ok(base) =
4808        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4809            .await
4810        && let Ok(head) =
4811            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4812    {
4813        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4814        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4815            let source = crate::git::rev_parse(&repo, branch)
4816                .await
4817                .unwrap_or_default();
4818            inputs.push_str(&format!(";review:{branch}:{source}"));
4819        }
4820        if let Some(reason) = task
4821            .recovery_exhausted(
4822                &head,
4823                &inputs,
4824                task.attempt_limit
4825                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4826            )
4827            .filter(|_| {
4828                !task.repair_grants.last().is_some_and(|receipt| {
4829                    RunState::load(&receipt.request.run)
4830                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4831                })
4832            })
4833        {
4834            task.hold_recovery_budget(
4835                reason,
4836                crate::queue::RecoveryAdmission { base: head, inputs },
4837            );
4838            record(queue, task);
4839            return Vec::new();
4840        }
4841        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4842    }
4843
4844    // A resumable run of this task is carried on, never re-competed. The
4845    // candidates are built and paid for, and a fresh competition races a
4846    // second implementation against them.
4847    //
4848    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4849    // started 3cbf on the same task a moment later, duplicating two and a
4850    // half hours of agent work. Then b25f stalled on a judge that timed out
4851    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4852    // was to blame for - and 4043 started **one second** later, buying three
4853    // fresh implementations to reach the same panel. `RunStatus::resumable`
4854    // rather than `!done()` is what catches the second case: a stall is
4855    // terminal, and its cheap recovery re-asks only the absent seats.
4856    //
4857    // A load failure is warned about rather than silently read as "not
4858    // resumable": the alternative is exactly what let a schema mismatch on
4859    // run `eba2` fall through to a full re-competition with nobody told why.
4860    // `crate::conduct` is what actually offers a better answer than
4861    // `Runner::start` here (see `Recovery::Review`), once this task's next
4862    // failure shows it up as `held`/`failed` with the run state unreadable.
4863    // Keep a retained review selection intact until disk admission succeeds.
4864    let consume_review = !previous
4865        .as_ref()
4866        .is_some_and(|state| crate::repair_budget::pending(task, state));
4867    let review_branch = consume_review
4868        .then(|| review_branch_for(task, previous.as_ref()))
4869        .flatten();
4870    let branch_exists = match review_branch {
4871        Some(branch) => crate::git::branch_exists(&repo, branch)
4872            .await
4873            .unwrap_or(false),
4874        None => false,
4875    };
4876    // An explicit `magi review <branch>` is reviewed whatever happens to the
4877    // branch unless an explicit implementer change requires fresh work. An
4878    // unfinished run of the same task still wins, so a retry resumes.
4879    let proposed = review_retry_starter(
4880        task,
4881        previous.as_ref(),
4882        review_branch,
4883        branch_exists,
4884        unfinished.as_deref(),
4885    );
4886    let retry_selected = task.replacement.is_some()
4887        && task.resumption.is_some()
4888        && !task.fresh_start
4889        && previous.as_ref().is_some_and(|run| {
4890            run.replaces.is_some()
4891                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4892                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4893        });
4894    let stop_pin = task
4895        .resume_override
4896        .as_ref()
4897        .filter(|pin| {
4898            Questions::open()
4899                .get_for_effects(&pin.question_id)
4900                .is_ok_and(|q| {
4901                    q.node == land::APPROVAL_NODE
4902                        && q.resolution()
4903                            .as_deref()
4904                            .is_some_and(crate::merge_decision::stops)
4905                })
4906        })
4907        .and_then(|pin| pin.pinned_run.clone());
4908    let granted_run = task.repair_grants.last().and_then(|receipt| {
4909        let state = RunState::load(&receipt.request.run).ok()?;
4910        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
4911    });
4912    let starter = if let Some(run) = granted_run {
4913        Starter::Resume(run)
4914    } else if let Some(owner) = &public_owner {
4915        Starter::Resume(owner.id.clone())
4916    } else if let Some(run) = stop_pin {
4917        // Stop actions resume their exact owner even after seat-count edits;
4918        // they must never fall through to implementation or a takeover.
4919        Starter::Resume(run)
4920    } else if retry_selected {
4921        Starter::Resume(previous.as_ref().unwrap().id.clone())
4922    } else if let Some(selected) = &task.pr_recovery {
4923        if selected
4924            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4925            .is_ok()
4926        {
4927            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4928        } else {
4929            Starter::Review(selected.branch.clone())
4930        }
4931    } else {
4932        starter_with_implementers(task, previous.as_ref(), proposed)
4933    };
4934    // A retained execution still writes to its saved output volume. A newer
4935    // repository policy only selects the volume for a fresh run.
4936    let disk_reason = match &starter {
4937        Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
4938            || {
4939                RunState::load(id)
4940                    .ok()
4941                    .and_then(|run| disk_gate(&run.repo, &run.config))
4942            },
4943            |run| disk_gate(&run.repo, &run.config),
4944        ),
4945        _ => disk_gate(&repo, &config),
4946    };
4947    if let Some(reason) = disk_reason {
4948        task.notice_cause("disk-space", None, None);
4949        task.last_error = Some(reason.clone());
4950        let disk_checked_at = task.disk_checked_at;
4951        task.hold_machine(Some(reason.clone()));
4952        if matches!(starter, Starter::Resume(_)) {
4953            task.mark_disk_capacity();
4954        } else {
4955            task.mark_startup_disk_capacity();
4956        }
4957        task.disk_checked_at = disk_checked_at;
4958        record(queue, task);
4959        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4960        notices::raise(
4961            Notice::warn(
4962                &format!("disk:{}", repo.display()),
4963                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
4964            )
4965            .link(Link::Task {
4966                id: task.id.clone(),
4967            }),
4968        );
4969        return Vec::new();
4970    }
4971    let review_branch = if consume_review {
4972        let valid = review_branch.is_some();
4973        task.review_instruction = None;
4974        task.review_branch.take().filter(|_| valid)
4975    } else {
4976        None
4977    };
4978    // An explicit resume pin must never degrade into a new competition or
4979    // takeover, including when its run stops being eligible after the answer.
4980    if let Some(pin) = &task.resume_override
4981        && let Some(run) = &pin.pinned_run
4982        && starter != Starter::Resume(run.clone())
4983    {
4984        let run = run.clone();
4985        task.notice_cause("resume-owner", Some(&run), None);
4986        task.hold_machine(Some(format!(
4987            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4988            task.id
4989        )));
4990        record(queue, task);
4991        return Vec::new();
4992    }
4993    // Automatic disk recovery resumes its retained run or stops: a changed
4994    // seat count or review branch must not turn it into a new competition.
4995    // No attempt is spent here.
4996    if let Some(run) = &task.disk_resume_run
4997        && starter != Starter::Resume(run.clone())
4998    {
4999        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()));
5000        record(queue, task);
5001        return Vec::new();
5002    }
5003    if task.replacement.is_some()
5004        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
5005        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
5006    {
5007        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()));
5008        record(queue, task);
5009        return Vec::new();
5010    }
5011    if let Some(reason) = retained_attempt_hold(
5012        task,
5013        &starter,
5014        config.disk.retained_attempt_limit,
5015        RunState::load,
5016    ) {
5017        // The review choice was consumed above. Preserve it across this hold
5018        // so a later release cannot silently become a fresh implementation.
5019        if let Starter::Review(branch) = &starter {
5020            task.review_branch = Some(branch.clone());
5021        }
5022        task.hold_unrequested_retry(Some(reason));
5023        record(queue, task);
5024        return Vec::new();
5025    }
5026    // Absolute paths of the files the task was filed with, re-read from the
5027    // task now so a file attached while it was held reaches a resumed run
5028    // too. A stored name whose file has gone is an error before any agent is
5029    // paid for, never a silent omission the implementer cannot notice.
5030    let attachments = match task_attachments(queue, task) {
5031        Ok(a) => a,
5032        Err(e) => {
5033            task.attempts += 1;
5034            task.fail_startup_target(
5035                "startup-attachments",
5036                e.name.clone(),
5037                format!("{start_failed}{e:#}"),
5038                opts.max_attempts,
5039            );
5040            record(queue, task);
5041            return Vec::new();
5042        }
5043    };
5044    let startup_pause = stop.pause();
5045    let startup_interrupt = interrupt_pause.clone();
5046    let wait = crate::repo_lock::WaitPolicy::new(
5047        Duration::from_secs(config.graph.timeout_resource_wait),
5048        move || startup_pause.parked() || startup_interrupt.parked(),
5049    );
5050    // Startup includes review takeover and recovery. Do not embed its large
5051    // future in both the wait scope and the surrounding attempt stack frame.
5052    let started = wait.scope(Box::pin(async { match &starter {
5053        Starter::Review(_) if task.pr_recovery.is_some() => {
5054            let selected = task.pr_recovery.clone().expect("selected recovery");
5055            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
5056                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
5057                    .await
5058                    .map(|mut r| {
5059                        r.state.attachments = attachments.clone();
5060                        r
5061                    }),
5062                Err(e) => Err(e),
5063            }
5064        }
5065        Starter::Review(branch) => {
5066            tracing::info!(
5067                "task {} reopens `{branch}` as a review-only pass",
5068                task.short()
5069            );
5070            // Every earlier attempt is superseded by the one being minted
5071            // now, so a branch one of them still holds may be taken over.
5072            let takeover = crate::handover::Takeover {
5073                earlier: task.earlier_attempts().to_vec(),
5074                home: crate::run::home(),
5075                choice: take_divergence_answer(branch, &config.merge.remote, task),
5076                task_instruction: Some(instruction_for(task)),
5077            };
5078            Runner::review_taking_over(
5079                &repo,
5080                branch,
5081                config,
5082                Some(takeover),
5083                crate::run::Origin::queue(&task.id),
5084            )
5085            .await
5086        }
5087        Starter::Resume(id) => {
5088            tracing::info!("resuming run {id} rather than competing again");
5089            Runner::resume(id).and_then(|mut r| {
5090                if retry_selected {
5091                    // The explicit queue release retries this same pinned
5092                    // implementation, preserving the attempt and worktrees.
5093                    for candidate in &mut r.state.candidates {
5094                        candidate.failed = None;
5095                        candidate.empty = false;
5096                        candidate.commits = 0;
5097                    }
5098                    r.state.status = RunStatus::Implementing;
5099                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
5100                }
5101                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
5102                    r.state.sources = task.sources.clone();
5103                }
5104                if r.state.prep_failure.is_some() {
5105                    let approval = task
5106                        .resumption
5107                        .as_ref()
5108                        .context("preparation retry requires an explicit task release")?;
5109                    r.retry_preparation(approval.at)?;
5110                }
5111                if let Some(instruction) =
5112                    prepare_instruction(&starter, Some(&r.state.instruction), task)
5113                {
5114                    r.state.instruction = instruction;
5115                }
5116                r.state.attachments = attachments.clone();
5117                if task.replacement.is_some() {
5118                    r.state.config.merge.mode = MergeMode::Pr;
5119                    r.state.config.graph.land_approval = true;
5120                }
5121                // Replacements publish a new PR and ask again. Selected PR
5122                // recoveries keep their saved disposition; ordinary runs can
5123                // retain the task's merge override.
5124                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
5125                    .overrides
5126                    .as_ref()
5127                    .and_then(|o| o.merge.as_deref())
5128                    .and_then(|m| merge_mode(m).ok())
5129                {
5130                    r.state.config.merge.mode = mode;
5131                }
5132                Ok(r)
5133            })
5134        }
5135        Starter::Start => {
5136            if let Some(branch) = &review_branch {
5137                tracing::warn!(
5138                    "conductor chose review for task {} but branch `{branch}` no longer \
5139                     exists; requeuing as a fresh competition instead",
5140                    task.short()
5141                );
5142            }
5143            let instruction = prepare_instruction(&starter, None, task)
5144                .unwrap_or_else(|| task.instruction.clone());
5145            Runner::start_naming(
5146                &repo,
5147                instruction,
5148                &task.title,
5149                config,
5150                crate::run::Origin::queue(&task.id),
5151            )
5152            .await
5153            .map(|mut r| {
5154                r.state.attachments = attachments.clone();
5155                r.state.sources = task.sources.clone();
5156                r
5157            })
5158        }
5159    }})).await;
5160    if let Err(error) = &started
5161        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
5162    {
5163        task.record_startup_failure(failure.clone());
5164    }
5165    let mut runner = match started {
5166        Ok(r) => r,
5167        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
5168            let detail = format!("{e:#}");
5169            task.last_error = Some(detail.clone());
5170            if e.is::<crate::build_target::AdmissionDiskWait>()
5171                && let Starter::Review(branch) = &starter
5172                && review_branch.is_some()
5173            {
5174                task.review_branch = Some(branch.clone());
5175                task.review_instruction = Some(task.instruction.clone());
5176            }
5177            if stop.parking() || interrupt_pause.parked() {
5178                let attempts = task.attempts;
5179                task.park(e.to_string());
5180                // Startup has not spent an attempt to refund.
5181                task.attempts = attempts;
5182            } else if e.is::<crate::build_target::AdmissionDiskWait>() {
5183                let disk_checked_at = task.disk_checked_at;
5184                task.hold_machine(Some(detail));
5185                task.mark_startup_disk_capacity();
5186                task.disk_checked_at = disk_checked_at;
5187            } else {
5188                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
5189            }
5190            record(queue, task);
5191            return Vec::new();
5192        }
5193        // A branch an earlier attempt still holds and magi will not release
5194        // by itself is the operator's call, not a failed attempt: hold the
5195        // task with the reason, spend nothing, and say so on the bell.
5196        Err(e) if task.pr_recovery.is_some() => {
5197            task.startup_notice_cause("startup-public-head");
5198            task.attempts += 1;
5199            task.last_error = Some(format!("{start_failed}{e:#}"));
5200            task.hold_unrequested_retry(Some(format!(
5201                "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."
5202            )));
5203            record(queue, task);
5204            return Vec::new();
5205        }
5206        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
5207            let detail = match e.downcast_ref::<crate::handover::Refused>() {
5208                Some(r) => (p.handover_refused)(r),
5209                None => format!("{e:#}"),
5210            };
5211            task.startup_notice_cause("startup-handover");
5212            let reason = format!("{start_failed}{detail}");
5213            task.last_error = Some(reason.clone());
5214            // Consumed above by `take`; keep it so the released task retries
5215            // as a review of this same branch.
5216            let branch = match &starter {
5217                Starter::Review(branch) => Some(branch.clone()),
5218                _ => None,
5219            };
5220            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
5221            // one page; the guidance rides in the reason, fixed per state so a
5222            // re-put never changes the wording and relights it.
5223            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5224            record(queue, task);
5225            tracing::warn!(
5226                "holding {} for a branch it cannot take over: {e:#}",
5227                task.short()
5228            );
5229            return Vec::new();
5230        }
5231        // A branch that differs between here and the remote in ways magi
5232        // cannot prove are the same change is a decision for the owner, not a
5233        // failed attempt: ask with both sides laid out, spend no attempt, and
5234        // let the answer requeue the task.
5235        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5236            let d = e
5237                .downcast_ref::<crate::reconcile::Diverged>()
5238                .expect("checked by the guard");
5239            let mut q = ask::Question::new(
5240                task.id.clone(),
5241                crate::reconcile::NODE.to_owned(),
5242                crate::reconcile::SEAT.to_owned(),
5243                d.summary(),
5244                d.detail(),
5245                d.choices(),
5246            );
5247            match Questions::open().put(&mut q) {
5248                Ok(()) => {
5249                    task.last_error = Some(format!("{e:#}"));
5250                    // Consumed above by `take`; the answer has to reach a review
5251                    // of this same branch, so keep pointing the task at it.
5252                    task.review_branch = Some(d.branch.clone());
5253                    task.review_instruction = Some(task.instruction.clone());
5254                    task.block(vec![q.id.clone()], Some(d.summary()));
5255                }
5256                Err(put) => {
5257                    tracing::warn!("could not file the divergence question: {put:#}");
5258                    task.attempts += 1;
5259                    task.fail_startup(
5260                        "startup-question-store",
5261                        format!("{start_failed}{e:#}"),
5262                        opts.max_attempts,
5263                    );
5264                }
5265            }
5266            record(queue, task);
5267            return Vec::new();
5268        }
5269        Err(e) => {
5270            // The answer was stale and nothing was applied: keep pointing at
5271            // the branch so the next attempt asks again against its new tips.
5272            // Nothing went wrong with the task, so no attempt is spent: a
5273            // budget one short of its limit must not hold it instead of
5274            // letting the question be asked again.
5275            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5276                && let Starter::Review(branch) = &starter
5277            {
5278                task.review_branch = Some(branch.clone());
5279                task.review_instruction = Some(task.instruction.clone());
5280                task.last_error = Some(format!("{start_failed}{e:#}"));
5281                task.status = crate::queue::TaskStatus::Failed;
5282                record(queue, task);
5283                return Vec::new();
5284            }
5285            task.attempts += 1;
5286            task.last_error = Some(format!("{start_failed}{e:#}"));
5287            task.startup_notice_cause("startup-source");
5288            task.hold_unrequested_retry(Some(format!(
5289                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5290            )));
5291            record(queue, task);
5292            return Vec::new();
5293        }
5294    };
5295    if !matches!(starter, Starter::Resume(_))
5296        && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
5297    {
5298        runner
5299            .state
5300            .event("build-cache", format!("{mode} selected by {source}"));
5301    }
5302    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5303        runner.state.recovery_config = Some(config_evidence);
5304    }
5305    if let Some(replacement) = &task.replacement {
5306        if matches!(starter, Starter::Start) {
5307            runner.state.instruction.push_str(&format!(
5308                "\n\n# Replacement review context\n{}",
5309                replacement.context
5310            ));
5311        }
5312        runner.state.replaces = Some(replacement.clone());
5313        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5314        if let Ok(mut old) = RunState::load(&replacement.run)
5315            && let Some(d) = &mut old.merge_decision
5316        {
5317            d.replacement_run = Some(runner.state.id.clone());
5318            old.event(
5319                "replacement",
5320                format!(
5321                    "replacement run {} owns the next attempt; old PR remains closed",
5322                    runner.state.id
5323                ),
5324            );
5325            if let Err(e) = old.save() {
5326                let error = runner.fail_startup("replacement-history", e);
5327                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5328                    task.record_startup_failure(failure.clone());
5329                }
5330                task.hold_manual(Some(format!(
5331                    "Could not link replacement history: {error:#}; no agents dispatched"
5332                )));
5333                record(queue, task);
5334                return Vec::new();
5335            }
5336        }
5337    }
5338    runner.state.task_instruction = Some(task.instruction.clone());
5339    // The follow-up depth is fixed now, while the task certainly exists:
5340    // deleting it later must not reset the cap (`crate::followup`).
5341    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5342    if runner.state.origin_chat.is_none() {
5343        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5344    }
5345    // A stop that means "park" reaches the graph through this handle.
5346    runner.on_pause(stop.pause());
5347    // `poll`'s interrupt scheduler reaches this one run - and no other -
5348    // through this handle. See `Pause`'s own doc for why these are never
5349    // the same one.
5350    runner.watch_interrupt(interrupt_pause);
5351
5352    // `start` has minted the run, so the task can now point at it. Persisting
5353    // `Running` before `execute` is what makes a crash mid-run legible.
5354    let run = runner.state.id.clone();
5355    let before_start = task.clone();
5356    task.start(run.clone());
5357    if let Err(error) = queue.put(task) {
5358        *task = before_start;
5359        let error = runner.fail_startup("task-start", error);
5360        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5361            task.record_startup_failure(failure.clone());
5362        }
5363        task.hold_manual(Some(format!(
5364            "Could not persist task start; no agents dispatched: {error:#}"
5365        )));
5366        record(queue, task);
5367        return Vec::new();
5368    }
5369    if task.status != TaskStatus::Running {
5370        // Queue::put kept a newer hold or continuation instead of this start.
5371        return Vec::new();
5372    }
5373    lock(status).current.push(Current {
5374        worker: None,
5375        task: task.id.clone(),
5376        run,
5377    });
5378
5379    // `RunState::quota` is the run's whole history across every resume, so
5380    // only what this execution added may arm the cooldown or earn a refund.
5381    let quota_before = runner.state.quota.clone();
5382    runner.state.carry_dispatched_resumes(task);
5383    runner.state.next_pass_task_entry = true;
5384    let result = runner.execute().await;
5385    finish_attempt(
5386        opts.max_attempts,
5387        queue,
5388        task,
5389        &runner.state,
5390        &quota_before,
5391        result,
5392    )
5393}
5394
5395async fn attempt_sync_only(
5396    queue: &Queue,
5397    status: &Arc<Mutex<Status>>,
5398    stop: &Stop,
5399    interrupt: crate::graph::Pause,
5400    task: &mut Task,
5401    request: crate::base_sync_only::Request,
5402) {
5403    let result = async {
5404        anyhow::ensure!(
5405            task.status == TaskStatus::Queued
5406                && task.execution_runs().last() == Some(&request.run)
5407                && task.resume_override.as_ref().is_some_and(
5408                    |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
5409                ),
5410            "sync-base-only request no longer owns the exact queued run"
5411        );
5412        let mut runner = Runner::resume(&request.run)?;
5413        anyhow::ensure!(
5414            public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
5415                .await?
5416                .is_none(),
5417            "the task still has a public execution owner"
5418        );
5419        anyhow::ensure!(
5420            !stop.parking() && !interrupt.parked(),
5421            "paused before base synchronization"
5422        );
5423        let original = task.clone();
5424        task.start(request.run.clone());
5425        task.attempts = original.attempts;
5426        if let Err(error) = queue.put(task) {
5427            *task = original;
5428            return Err(error);
5429        }
5430        if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
5431            return Ok(());
5432        }
5433        lock(status).current.push(Current {
5434            worker: None,
5435            task: task.id.clone(),
5436            run: request.run.clone(),
5437        });
5438        runner.on_pause(stop.pause());
5439        runner.watch_interrupt(interrupt);
5440        runner.execute_sync_only(request.clone()).await
5441    }
5442    .await;
5443    if task.sync_only.as_ref() == Some(&request) {
5444        let saved = RunState::load(&request.run).ok();
5445        let detail = result.err().map(|error| {
5446            format!("Base synchronization only: {error:#}; verification was not allowed")
5447        });
5448        crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
5449        record(queue, task);
5450    }
5451}
5452
5453/// Settle `task` after its run executed: the verdict, the diagnosis, the
5454/// supersession of earlier attempts and the save. Shared by the loop and by
5455/// `magi run --resume`, so an attempt is counted one way wherever it ran.
5456/// Returns the quota losses this execution added to the run.
5457pub fn finish_attempt(
5458    max_attempts: usize,
5459    queue: &Queue,
5460    task: &mut Task,
5461    state: &RunState,
5462    quota_before: &[QuotaLoss],
5463    result: Result<()>,
5464) -> Vec<QuotaLoss> {
5465    let detail = match result {
5466        Ok(()) => describe(state),
5467        Err(e) => format!("{e:#}"),
5468    };
5469    let fresh = losses_this_attempt(quota_before, &state.quota);
5470    let verdict = Verdict {
5471        status: state.status,
5472        // A run that opened a pull request handed its work over, whatever the
5473        // gate then decided about merging it.
5474        left_pr: state.pr.is_some(),
5475        // Only a rate limit earns the task its attempt back - and only one
5476        // suffered now: a refund justified by a previous session's loss is
5477        // the same mistake as re-arming the cooldown from it. A stalled run
5478        // resumed without hitting quota again therefore spends its attempt,
5479        // like any other failure of the task's own.
5480        quota_hit: !fresh.is_empty(),
5481        // A run that parked was asked to stop; that is not a failure and must
5482        // not spend an attempt, or replacing the binary a few times would
5483        // exhaust a task's budget without an agent ever misbehaving.
5484        parked: state.parked,
5485        // A quota loss that left nothing viable is the same machine fact as a
5486        // `Stalled` quota loss; see `settle`'s doc table.
5487        no_viable_candidates: state.viable().is_empty(),
5488    };
5489    if let Some(replacement) = &state.replaces
5490        && let Some(pr) = &state.pr
5491        && let Ok(mut old) = RunState::load(&replacement.run)
5492        && let Some(d) = &mut old.merge_decision
5493    {
5494        d.replacement_pr = Some(pr.url.clone());
5495        let _ = old.save();
5496    }
5497    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5498    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5499        task.hold_unrequested_retry(Some(format!(
5500            "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.",
5501            task.short()
5502        )));
5503    }
5504    if task.status == TaskStatus::Done {
5505        supersede_prior_runs(task, &crate::run::home());
5506    }
5507    record(queue, task);
5508    tracing::info!(
5509        "task {} is {} after run {} ({})",
5510        task.short(),
5511        task.status.as_str(),
5512        state.short(),
5513        label(state.status)
5514    );
5515    fresh
5516}
5517
5518/// A task a hand-started run leaves runnable (failed with attempts to spare,
5519/// or requeued) is **held**: nobody asked for a retry, and a loop starting
5520/// later must not spend agent calls on it. `magi task release` retries.
5521pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5522    // Parked work (including legacy Failed records with a parked run) is a
5523    // checkpoint or owner handoff, not an unrequested retry.
5524    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5525        && !awaiting_resume_with(task, RunState::load)
5526        // A run parked on the owner's word about a withheld PR title/body
5527        // resumes via `land_resume_state`, including review-only tasks that
5528        // `awaiting_resume_with` does not consider.
5529        && withheld_text_wait(task).is_none()
5530        && !(task.fresh_start && task.replacement.is_some())
5531    {
5532        let why = task.last_error.clone().map_or_else(
5533            || "the run did not finish".to_owned(),
5534            |e| format!("the run did not finish: {e}"),
5535        );
5536        task.hold_unrequested_retry(Some(format!(
5537            "{why}. It was started by hand, so it is not retried \
5538             automatically; `magi task release` retries it."
5539        )));
5540        record(queue, task);
5541    }
5542}
5543
5544/// Whether an attempt at a task whose newest run is `run` would resume that
5545/// run rather than start a fresh competition. `magi run --resume` hands a run
5546/// to a live loop only when this holds.
5547#[must_use]
5548pub fn loop_would_resume(run: &str) -> bool {
5549    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5550}
5551
5552/// A loop in another process that is alive right now: a fresh heartbeat in
5553/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
5554/// carries the pid it published (`None` inside when it published none - a
5555/// fresh heartbeat is still evidence of a live loop).
5556///
5557/// The one judgement of "is somebody else serving this queue", shared by the
5558/// web UI's refusal to start a second loop and by `magi run` / `magi review`
5559/// deciding whether to hand a task to the loop. A claim file proves nothing
5560/// here: whether a claim succeeds says nothing about whether its owner lives.
5561#[must_use]
5562pub fn foreign_loop(
5563    reading: Option<&Reading>,
5564    now: Timestamp,
5565    own_pid: u32,
5566) -> Option<Option<u32>> {
5567    let reading = reading.filter(|r| r.running(now))?;
5568    match reading.pid {
5569        Some(pid) if pid == own_pid => None,
5570        pid => Some(pid),
5571    }
5572}
5573
5574fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5575    reading.worker_protocol != Some(1)
5576        && (foreign_loop(Some(reading), now, own_pid).is_some()
5577            || reading
5578                .pid
5579                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5580}
5581
5582/// Low-level claimed-task execution shared by the detached standalone worker
5583/// and focused lifecycle fixtures. The caller must retain the queue claim for
5584/// this entire call. CLI callers transfer ownership through
5585/// [`run_detached_claimed`] instead of executing inside their own runtime.
5586///
5587/// The one deliberate difference from the loop: a task the attempt leaves
5588/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5589/// Nobody asked for a retry, and a daemon starting later must not spend agent
5590/// calls re-running a hand-started task behind the operator's back;
5591/// `magi task release` is the explicit retry.
5592pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5593    run_claimed_until(opts, queue, task, &Stop::new()).await;
5594}
5595
5596async fn run_claimed_until(
5597    opts: &Opts,
5598    queue: &Queue,
5599    task: &mut Task,
5600    stop: &Stop,
5601) -> Vec<QuotaLoss> {
5602    let status = Arc::new(Mutex::new(Status::new()));
5603    // An attempt embeds startup and graph futures. Keep it off the standalone
5604    // caller's stack, on both the initial execution and withheld-text resume.
5605    let mut quota = Box::pin(attempt(
5606        opts,
5607        queue,
5608        &status,
5609        stop,
5610        crate::graph::Pause::new(),
5611        task,
5612    ))
5613    .await;
5614    // A run parked on the owner's word about a withheld PR title/body has no
5615    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5616    // here with the claim still held, and resume once the question is settled
5617    // (answered, or abandoned at its deadline -> the neutral text).
5618    // A rejected reply files one more question (the gate asks at most twice),
5619    // so after a resume the run may be waiting again: keep going, with a fresh
5620    // limit for the new question. `resumes` bounds it even if a resume parks
5621    // without asking anything new.
5622    let mut resumes = 0;
5623    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5624        let Some(timeout) = withheld_text_wait(task) else {
5625            break;
5626        };
5627        eprintln!(
5628            "waiting for the owner's answer on a withheld pull request text \
5629             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5630        );
5631        // The deadline abandons the question itself; the extra margin only
5632        // covers an abandon that could not be saved.
5633        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5634        let ready = loop {
5635            match land_resume_state(task) {
5636                LandResume::StillWaiting
5637                    if !stop.parking() && std::time::Instant::now() < limit =>
5638                {
5639                    tokio::time::sleep(WITHHELD_POLL).await;
5640                }
5641                LandResume::Ready => break true,
5642                _ => break false,
5643            }
5644        };
5645        if !ready || stop.parking() {
5646            break;
5647        }
5648        resumes += 1;
5649        quota.extend(
5650            Box::pin(attempt(
5651                opts,
5652                queue,
5653                &status,
5654                stop,
5655                crate::graph::Pause::new(),
5656                task,
5657            ))
5658            .await,
5659        );
5660    }
5661    hold_if_runnable(queue, task);
5662    quota
5663}
5664
5665/// Resumes an in-process run makes for withheld-text questions: the gate asks
5666/// at most twice, plus one for a resume that asks nothing new.
5667const MAX_WITHHELD_RESUMES: u32 = 3;
5668
5669/// How often an in-process run rechecks its withheld-text question.
5670const WITHHELD_POLL: Duration = Duration::from_secs(15);
5671
5672/// The `answer_timeout` (seconds) of the task's last run when that run is
5673/// parked on an unresolved withheld-text question; `None` otherwise.
5674fn withheld_text_wait(task: &Task) -> Option<u64> {
5675    let id = task.execution_runs().last()?;
5676    let s = RunState::load(id).ok()?;
5677    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5678        .then_some(s.config.graph.answer_timeout)
5679}
5680
5681/// The quota losses `after` holds that `before` did not: what one execution
5682/// suffered, as opposed to the run's history.
5683///
5684/// Compared by value rather than by length or position because
5685/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5686/// the vector can shrink and shift under a resume. A retried seat that hits
5687/// quota again is a `push` with a new `at`, so it shows up as new here.
5688/// Crash recovery uses the recorded pass start as its boundary when available;
5689/// legacy records without passes retain their original history-based policy.
5690fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5691    after
5692        .iter()
5693        .filter(|q| !before.contains(q))
5694        .cloned()
5695        .collect()
5696}
5697
5698/// When the loop-wide quota cooldown should end, given this attempt's losses;
5699/// `None` when there were none. Reset-hint parsing and the cap live here.
5700fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5701    let quota: Vec<_> = quota
5702        .iter()
5703        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5704        .collect();
5705    if quota.is_empty() {
5706        return None;
5707    }
5708    let with_hint = quota.iter().find(|q| q.reset.is_some());
5709    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5710    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5711    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5712    Some(
5713        now.checked_add(jiff::SignedDuration::from_secs(secs))
5714            .unwrap_or(Timestamp::MAX),
5715    )
5716}
5717
5718/// An explicit task count must agree with a run before any resume.
5719fn implementers_match(task: &Task, state: &RunState) -> bool {
5720    task.replacement.as_ref().map_or_else(
5721        || {
5722            task.implementers()
5723                .is_none_or(|n| n == state.config.graph.implementers)
5724        },
5725        |replacement| {
5726            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5727                && state.config.graph.implementers == 1
5728        },
5729    )
5730}
5731
5732/// Never resume or take over candidate work built for a different seat count.
5733fn starter_with_implementers(
5734    task: &Task,
5735    previous: Option<&RunState>,
5736    proposed: Starter,
5737) -> Starter {
5738    if previous.is_some_and(|s| !implementers_match(task, s)) {
5739        task.review_of
5740            .as_ref()
5741            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5742    } else {
5743        proposed
5744    }
5745}
5746
5747/// Apply this task's explicit count to the new attempt, without changing defaults.
5748fn apply_task_implementers(config: &mut Config, task: &Task) {
5749    if let Some(n) = task.implementers() {
5750        config.graph.implementers = n;
5751    }
5752}
5753
5754/// [`prepare`] for one task: its own `--config` and command-line overrides
5755/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5756/// over the loop's, so handing a hand-started task to a daemon changes nothing
5757/// about what it does.
5758#[cfg(test)]
5759fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5760    let explicit = match &task.overrides {
5761        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5762        _ => opts.config.as_deref(),
5763    };
5764    let (mut config, _) = Config::discover(repo, explicit)?;
5765    apply_options(&mut config, opts, task)?;
5766    Ok(config)
5767}
5768
5769fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5770    if task
5771        .overrides
5772        .as_ref()
5773        .is_none_or(|o| o.inherit_daemon_options)
5774        && let Some(mode) = opts.merge.as_deref()
5775    {
5776        config.merge.mode = merge_mode(mode)?;
5777    }
5778    if let Some(o) = &task.overrides {
5779        o.apply(config);
5780    }
5781    if let Some((mode, _)) = task.build_cache_override(config) {
5782        config.verify.build_cache = mode;
5783    }
5784    Ok(())
5785}
5786
5787/// Load the config for a task's repository, with the merge override applied.
5788fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5789    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5790    if let Some(mode) = &opts.merge {
5791        config.merge.mode = merge_mode(mode)?;
5792    }
5793    Ok(config)
5794}
5795
5796/// Prune the shared build cache at a between-runs boundary. The detached cache
5797/// service checks authoritative task jobs first; dispatch waits for that finite
5798/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5799/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5800async fn maybe_prune_cache_between_runs(
5801    repo: &Path,
5802    opts: &Opts,
5803    home: &Path,
5804    stop: &Stop,
5805    last_checked: &mut Option<Timestamp>,
5806    now: Timestamp,
5807) {
5808    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5809        return;
5810    }
5811    *last_checked = Some(now);
5812    let cfg = match prepare(repo, opts) {
5813        Ok(cfg) => cfg,
5814        Err(e) => {
5815            tracing::warn!("cache check: no config: {e:#}");
5816            return;
5817        }
5818    };
5819    match clean::prune_cache_if_over_limit(&cfg, home) {
5820        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5821            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5822            pruned.files,
5823            pruned.freed
5824        ),
5825        Ok(_) => {}
5826        Err(e) => {
5827            tracing::warn!("housekeep: prune cache: {e:#}");
5828            notices::raise_in(
5829                home,
5830                Notice::warn(
5831                    "housekeep:cache",
5832                    format!(
5833                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5834                        e.to_string()
5835                            .lines()
5836                            .next()
5837                            .unwrap_or("unknown cleanup error")
5838                    ),
5839                ),
5840            );
5841        }
5842    }
5843}
5844
5845/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5846/// now, given when it last did (if ever). Pure, so the cadence is asserted
5847/// directly rather than by waiting out real minutes in a test.
5848fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5849    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5850}
5851
5852/// The disk janitor, with its housekeeping logged rather than fatal.
5853///
5854/// Called only at the loop's idle points, for the reason the caller documents:
5855/// a prune racing a live compile would delete files mid-build. The config is
5856/// re-read on every call because the repository that just ran may not be the
5857/// daemon's own default, and the cache directory is a repository fact.
5858///
5859/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5860/// and [`crate::run::default_worktree_root`] read here, for the same reason
5861/// [`drive`] takes its queue and status file rather than resolving them: a
5862/// test driving the loop must not reach through to the operator's real home
5863/// or worktree bay just because the janitor runs on every idle tick.
5864/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5865/// to get wrong silently - a test's `home` was already isolated, but nothing
5866/// exercised the parameter next to it, so a real worktree bay stayed wired in
5867/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5868/// it for real, every test in this file that drives the loop at all started
5869/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5870async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5871    let cfg = match prepare(repo, opts) {
5872        Ok(cfg) => cfg,
5873        Err(e) => {
5874            tracing::warn!("housekeep: no config: {e:#}");
5875            return;
5876        }
5877    };
5878    // A run's own worktree lives under `config.graph.worktree_root` when the
5879    // repository sets one - the same precedence `RunState::worktree_root`
5880    // uses - and `worktrees_root` only stands in for the *default* an
5881    // unconfigured repository resolves to (see this function's own
5882    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5883    // that always swept the default regardless of this override would never
5884    // see, and so never reclaim, a single worktree for a repository that
5885    // relocated them elsewhere.
5886    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5887    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5888    // Reported whenever there is anything to say, not only when `folded > 0`:
5889    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5890    // folded, on every single pass, for months - a report gated on `folded`
5891    // would have stayed silent through every one of them.
5892    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5893        let mut extra = Vec::new();
5894        if out.unreadable > 0 {
5895            extra.push(format!("{} unreadable", out.unreadable));
5896        }
5897        if out.orphaned_worktrees > 0 {
5898            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5899        }
5900        let detail = if extra.is_empty() {
5901            String::new()
5902        } else {
5903            format!(" ({})", extra.join(", "))
5904        };
5905        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5906    }
5907    if out.external_merges_recorded > 0 {
5908        tracing::info!(
5909            "housekeep: recorded {} run(s) as merged externally",
5910            out.external_merges_recorded
5911        );
5912    }
5913    if out.stale_pr_states_repaired > 0 {
5914        tracing::info!(
5915            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5916            out.stale_pr_states_repaired
5917        );
5918    }
5919    if out.cache_files > 0 {
5920        tracing::info!(
5921            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5922            out.cache_files,
5923            out.cache_freed
5924        );
5925    }
5926    if out.questions_abandoned > 0 {
5927        tracing::info!(
5928            "housekeep: abandoned {} question(s) left open by a finished run",
5929            out.questions_abandoned
5930        );
5931    }
5932}
5933
5934/// Run [`triage::run_once`] and log whatever it did, the same "only when
5935/// there is something to say" rule [`janitor`] follows for its own report.
5936///
5937/// Called at the same idle points as [`janitor`] - once per full poll
5938/// interval, never mid-attempt - for the same reason: it is not liveness
5939/// critical, and a task's own `hold_reason` string is the one thing this
5940/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5941/// tick for no benefit.
5942async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5943    let questions = Questions::at(home.join("questions"));
5944    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5945    if report.is_empty() {
5946        return;
5947    }
5948    if !report.quarantined.is_empty() {
5949        tracing::info!(
5950            "triage: held {} blocked task(s) whose blocked-on task or \
5951             question no longer exists: {}",
5952            report.quarantined.len(),
5953            report.quarantined.join(", ")
5954        );
5955    }
5956    if !report.resumed.is_empty() {
5957        tracing::info!(
5958            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5959            report.resumed.len(),
5960            report.resumed.join(", ")
5961        );
5962    }
5963    if !report.asked.is_empty() {
5964        tracing::info!(
5965            "triage: asked about {} held task(s): {}",
5966            report.asked.len(),
5967            report.asked.join(", ")
5968        );
5969    }
5970    if !report.answered.is_empty() {
5971        tracing::info!(
5972            "triage: applied {} operator answer(s): {}",
5973            report.answered.len(),
5974            report.answered.join(", ")
5975        );
5976    }
5977}
5978
5979/// The free-space gate: what stands between this task and a new run, if
5980/// anything. `Some(reason)` holds the task; `None` lets it start.
5981///
5982/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5983/// the operator opted out. A measurement failure is a gate, not a pass: both
5984/// sides of "cannot tell" are served by not starting.
5985pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5986    disk_gate_at(repo, config, crate::run::home)
5987}
5988
5989pub(crate) fn disk_gate_at(
5990    repo: &Path,
5991    config: &Config,
5992    home: impl FnOnce() -> PathBuf,
5993) -> Option<String> {
5994    let measure = if crate::build_target::isolated(config) {
5995        crate::disk::managed_free_bytes
5996    } else {
5997        crate::disk::free_bytes
5998    };
5999    disk_gate_with(repo, config, home, measure)
6000}
6001
6002/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
6003/// test can assert the exact wiring `attempt` runs - config's threshold in,
6004/// task-holding reason out - without asking the real machine's disk anything.
6005fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
6006    repo: &Path,
6007    config: &Config,
6008    home: impl FnOnce() -> PathBuf,
6009    free_bytes: F,
6010) -> Option<String> {
6011    let min = config.disk.min_free_bytes;
6012    if min == 0 {
6013        return None;
6014    }
6015    let output = match config.verify.build_cache {
6016        BuildCache::Shared => config.cache_dir(),
6017        BuildCache::Isolated => Some(home()),
6018    };
6019    let default_worktree_root;
6020    let worktree_root = match config.graph.worktree_root.as_deref() {
6021        Some(root) => root,
6022        None => {
6023            default_worktree_root = crate::run::default_worktree_root();
6024            &default_worktree_root
6025        }
6026    };
6027    for path in [Some(repo), output.as_deref(), Some(worktree_root)]
6028        .into_iter()
6029        .flatten()
6030    {
6031        let probe = if path == repo {
6032            path
6033        } else {
6034            path.ancestors().find(|p| p.exists()).unwrap_or(path)
6035        };
6036        let reason = match free_bytes(probe) {
6037            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
6038            Err(e) => Some(crate::disk::unmeasured_in(
6039                probe,
6040                &e,
6041                &config.graph.language,
6042            )),
6043        };
6044        if reason.is_some() {
6045            return reason;
6046        }
6047    }
6048    None
6049}
6050
6051/// How long to wait before offering another task when a run lost a seat to a
6052/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
6053/// could read, or carried nothing at all. Long enough that a quota outage
6054/// cannot burn through a whole backlog in the few seconds each doomed attempt
6055/// takes to fail; short enough that a quota which clears early is not left
6056/// idle for the fallback's sake.
6057const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
6058
6059/// Longest a parsed reset hint may push the wait out to. The hint comes from
6060/// the CLI's own words, not a contract, so a parsing slip that lands a day
6061/// away must not leave the loop asleep for a day.
6062const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
6063
6064/// How long [`poll`] should wait before offering the next task, after a run
6065/// lost at least one seat to a rate limit.
6066///
6067/// Pure and separate from the loop so the policy can be exercised without a
6068/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
6069/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
6070/// nothing to parse, or the parsed time has already passed; `cap` bounds how
6071/// far a parsed hint is trusted to push the wait out.
6072fn quota_wait(
6073    reset_at: Option<Timestamp>,
6074    now: Timestamp,
6075    fallback: Duration,
6076    cap: Duration,
6077) -> Duration {
6078    match reset_at {
6079        Some(at) if at > now => {
6080            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
6081            Duration::from_secs(secs).min(cap)
6082        }
6083        _ => fallback,
6084    }
6085}
6086
6087/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
6088///
6089/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
6090/// explains why parsing it exactly "would be a bug factory" — so this only
6091/// recognises the shapes actually observed in the wild, and returns `None`
6092/// for anything else rather than guess at a format nobody has seen.
6093///
6094/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
6095/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
6096/// said it, not from whenever this loop happens to read it: anchoring on `now`
6097/// would push the reset later on every read and would read an already-elapsed
6098/// reset as still in the future. (A long hint is still clamped by
6099/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
6100fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
6101    parse_reset_hint_zoned(text, now)
6102        .or_else(|| parse_reset_hint_dated(text))
6103        .or_else(|| parse_reset_hint_relative(text, recorded))
6104}
6105
6106/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
6107/// optional but at least one required, in that order. A bare number or any
6108/// unknown unit is refused.
6109fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
6110    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
6111    let mut rest = rest.trim();
6112    if rest.is_empty() {
6113        return None;
6114    }
6115    let mut total: i64 = 0;
6116    let mut matched = false;
6117    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
6118        if let Some((digits, tail)) = rest.split_once(unit)
6119            && !digits.is_empty()
6120            && digits.bytes().all(|b| b.is_ascii_digit())
6121        {
6122            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
6123            rest = tail;
6124            matched = true;
6125        }
6126    }
6127    if !rest.is_empty() || !matched {
6128        return None;
6129    }
6130    recorded
6131        .checked_add(jiff::SignedDuration::from_secs(total))
6132        .ok()
6133}
6134
6135/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
6136/// case-insensitive) into a 24-hour hour and minute. Shared by every
6137/// reset-hint shape below.
6138fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
6139    let clock = clock.trim().to_lowercase();
6140    let (digits, pm) = clock
6141        .strip_suffix("am")
6142        .map(|d| (d, false))
6143        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
6144    let (h, m) = digits.trim().split_once(':')?;
6145    let mut hour: i8 = h.trim().parse().ok()?;
6146    let minute: i8 = m.trim().parse().ok()?;
6147    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
6148        return None;
6149    }
6150    if pm && hour != 12 {
6151        hour += 12;
6152    } else if !pm && hour == 12 {
6153        hour = 0;
6154    }
6155    Some((hour, minute))
6156}
6157
6158/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
6159/// and a zone, never a date. A clock reading already past today is read as
6160/// tomorrow's: a CLI naming a same-day reset that has already gone by means
6161/// the window rolled over while nothing was watching.
6162fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
6163    let open = text.find('(')?;
6164    let close = text.rfind(')')?;
6165    if close <= open {
6166        return None;
6167    }
6168    let zone = text[open + 1..close].trim();
6169    let (hour, minute) = parse_12h_clock(&text[..open])?;
6170    let tz = jiff::tz::TimeZone::get(zone).ok()?;
6171    let candidate = now
6172        .to_zoned(tz)
6173        .with()
6174        .hour(hour)
6175        .minute(minute)
6176        .second(0)
6177        .millisecond(0)
6178        .microsecond(0)
6179        .nanosecond(0)
6180        .build()
6181        .ok()?;
6182    let mut at = candidate.timestamp();
6183    if at <= now {
6184        at += jiff::SignedDuration::from_hours(24);
6185    }
6186    Some(at)
6187}
6188
6189/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
6190/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
6191/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
6192/// "already past today" correction to make: the year already disambiguates
6193/// it. Scanned as a five-word window so it can be pulled out of the middle
6194/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
6195/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
6196/// any other timestamp with no zone attached.
6197fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
6198    let words: Vec<&str> = text.split_whitespace().collect();
6199    if words.len() < 5 {
6200        return None;
6201    }
6202    (0..=words.len() - 5)
6203        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
6204}
6205
6206/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
6207/// parenthesis right after the window is refused rather than ignored — it
6208/// reads as an explicit zone annotation on a shape that otherwise carries
6209/// none, and guessing UTC anyway would be exactly the silent misread this
6210/// module's parsing otherwise avoids.
6211fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
6212    if trailing.is_some_and(|next| next.starts_with('(')) {
6213        return None;
6214    }
6215    let month = month_number(window[0])?;
6216    let day_token = window[1].strip_suffix(',')?.to_lowercase();
6217    let day_digits = ["st", "nd", "rd", "th"]
6218        .iter()
6219        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
6220    let day: i8 = day_digits.parse().ok()?;
6221    let year_token = window[2];
6222    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
6223        return None;
6224    }
6225    let year: i16 = year_token.parse().ok()?;
6226    // The am/pm word carries the sentence's own trailing punctuation, e.g.
6227    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
6228    // reusing the same 12-hour clock reader the bracketed shape uses.
6229    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
6230    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
6231    let date = jiff::civil::Date::new(year, month, day).ok()?;
6232    let candidate = date
6233        .at(hour, minute, 0, 0)
6234        .to_zoned(jiff::tz::TimeZone::UTC)
6235        .ok()?;
6236    Some(candidate.timestamp())
6237}
6238
6239/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
6240/// case-insensitively, into a 1-based month number.
6241fn month_number(name: &str) -> Option<i8> {
6242    const NAMES: [&str; 12] = [
6243        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
6244    ];
6245    let lower = name.to_lowercase();
6246    NAMES
6247        .iter()
6248        .position(|n| *n == lower.as_str())
6249        .map(|i| i as i8 + 1)
6250}
6251
6252/// Test probe for the shared resume policy's review-budget exclusion.
6253#[cfg(test)]
6254fn exhausted_review_budget(state: &RunState) -> bool {
6255    // A run whose task-head publication failed has nothing left to review:
6256    // resuming it only retries the publication, so it is never "exhausted".
6257    !crate::handover::can_resume(state)
6258        && state.status == RunStatus::Blocked
6259        && !state.released()
6260        && state.retired_to.is_none()
6261}
6262
6263/// This task's *most recent* run, if resuming it would actually make
6264/// progress. `short` is only for the warning's own message.
6265///
6266/// Only ever `runs.last()` — never a search back through older history.
6267/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
6268/// mint, oldest first, and every entry before the last one was already
6269/// superseded at the moment it was minted: the daemon only ever starts a new
6270/// run when the previous one was not worth resuming (unresumable, exhausted,
6271/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
6272/// opens a fresh review-only run alongside an older, already-failed
6273/// competition. Searching further back would let an old run that merely
6274/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
6275/// behind, say — get resumed instead of the fresh competition
6276/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
6277/// nothing asked to revisit.
6278///
6279/// Two runs paid for the "prefer resuming over restarting" half of this
6280/// lesson, which is why this still checks `runs.last()` rather than always
6281/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
6282/// task a moment later, duplicating two and a half hours of agent work. Then
6283/// b25f stalled on a judge that timed out and one that answered with no JSON
6284/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
6285/// **one second** later, buying three fresh implementations to reach the
6286/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
6287/// the second case: a stall is terminal, and its cheap recovery re-asks only
6288/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
6289/// that is technically `resumable()` but provably cannot progress must not
6290/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
6291/// no-op instead of the fresh competition it promises.
6292///
6293/// A load failure is warned about rather than silently read as "not
6294/// resumable": the alternative is exactly what let a schema mismatch on run
6295/// `eba2` fall through to a full re-competition with nobody told why.
6296/// `crate::conduct` is what actually offers a better answer than
6297/// `Runner::start` here (see `Recovery::Review`), once this task's next
6298/// failure shows it up as `held`/`failed` with the run state unreadable.
6299fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
6300    unfinished_run_with(runs, short, RunState::load)
6301}
6302
6303/// [`unfinished_run`] with an injected state reader. Tests provide their
6304/// fixtures directly rather than touching the process-global run home.
6305pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6306where
6307    F: FnMut(&str) -> Result<RunState>,
6308{
6309    let mut id = runs.last()?.clone();
6310    let mut visited = std::collections::BTreeSet::new();
6311    let mut repo = None;
6312    loop {
6313        if !runs.contains(&id) || !visited.insert(id.clone()) {
6314            tracing::warn!("invalid or cyclic recovery authority for task {short}");
6315            return None;
6316        }
6317        let state = match load(&id) {
6318            Ok(state) if state.id == id => state,
6319            Ok(_) => return None,
6320            Err(e) => {
6321                tracing::warn!("could not read run {id} for task {short}: {e:#}");
6322                return None;
6323            }
6324        };
6325        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6326            return None;
6327        }
6328        repo = Some(state.repo.clone());
6329        if let Some(authority) = state.retired_to {
6330            id = authority;
6331            continue;
6332        }
6333        return (crate::handover::can_resume(&state)
6334            && state.liveness(false) != crate::run::Liveness::Live)
6335            .then_some(id);
6336    }
6337}
6338
6339/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
6340/// that [`attempt`] will resume it on its own?
6341///
6342/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
6343/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
6344/// injected reader like its sibling. An unreadable run is not awaiting
6345/// anything: it keeps going to the conductor as before.
6346fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6347where
6348    F: FnOnce(&str) -> Result<RunState>,
6349{
6350    // `Failed` stays: a record an older build wrote for a parked run.
6351    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6352        || task.fresh_start
6353        || task.review_branch.is_some()
6354    {
6355        return false;
6356    }
6357    let Some(id) = task.execution_runs().last() else {
6358        return false;
6359    };
6360    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6361}
6362
6363/// Which of the three ways [`attempt`] can mint or continue a run this task
6364/// should use.
6365#[derive(Debug, Clone, PartialEq, Eq)]
6366enum Starter {
6367    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
6368    /// and that still exists.
6369    Review(String),
6370    /// `crate::graph::Runner::resume` on an unfinished run of this task.
6371    Resume(String),
6372    /// `crate::graph::Runner::start`: a fresh competition.
6373    Start,
6374}
6375
6376/// A second bound independent of inputs and the resettable failure counter.
6377/// Count execution and failed-startup recovery records once per run. Startup
6378/// failures can retain unrecorded preparation assets without an execution pass.
6379/// Unknown history is not evidence that a new set of worktrees is affordable.
6380fn retained_attempt_hold(
6381    task: &Task,
6382    starter: &Starter,
6383    limit: usize,
6384    mut load: impl FnMut(&str) -> Result<RunState>,
6385) -> Option<String> {
6386    if limit == 0 || matches!(starter, Starter::Resume(_)) {
6387        return None;
6388    }
6389    let mut retained = 0;
6390    for id in task
6391        .runs
6392        .iter()
6393        .chain(task.startup_failures.iter().map(|failure| &failure.run))
6394        .collect::<std::collections::BTreeSet<_>>()
6395    {
6396        let state = match load(id) {
6397            Ok(state) if state.id == *id => state,
6398            _ => {
6399                return Some(format!(
6400                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6401                ));
6402            }
6403        };
6404        if state.retired_to.is_some() || state.released() {
6405            continue;
6406        }
6407        // Neither a completed status nor an empty candidate array proves that
6408        // all recovery sources (including unrecorded preparation) were retired.
6409        retained += 1;
6410    }
6411    (retained >= limit).then(|| format!(
6412        "[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."
6413    ))
6414}
6415
6416/// A selected public implementation overrides every historical candidate and pin.
6417fn selected_starter(
6418    selected: &crate::pr_recovery::Selection,
6419    previous: Option<&RunState>,
6420    unfinished: Option<&str>,
6421) -> Starter {
6422    if let Some(id) = unfinished
6423        && previous.is_some_and(|r| {
6424            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6425        })
6426    {
6427        Starter::Resume(id.to_owned())
6428    } else {
6429        Starter::Review(selected.branch.clone())
6430    }
6431}
6432
6433/// The owner's answer to this branch's divergence question, consumed from the
6434/// task so a later, different divergence asks again. The runner applies it
6435/// (see `Runner::review_taking_over`), after the earlier worktree is released.
6436fn take_divergence_answer(
6437    branch: &str,
6438    remote: &str,
6439    task: &mut Task,
6440) -> Option<crate::reconcile::Choice> {
6441    let summary = crate::reconcile::summary_for(branch, remote);
6442    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6443        (a.question == summary)
6444            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6445            .flatten()
6446            .map(|c| (i, c))
6447    })?;
6448    task.answers.remove(idx);
6449    Some(choice)
6450}
6451
6452/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
6453/// this attempt should use. Pure, and separate from [`attempt`], so the
6454/// routing itself is assertable without spawning a real graph or a git
6455/// process: `attempt`'s own `crate::git::branch_exists` call has already
6456/// happened by the time this is called.
6457///
6458/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
6459/// whose branch is gone falls all the way through to [`Starter::Start`], not
6460/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
6461/// old (likely `Blocked`) run in the first place, and a branch that vanished
6462/// out from under that choice is not evidence resuming it would fare better.
6463fn choose_starter(
6464    review_branch: Option<&str>,
6465    branch_exists: bool,
6466    unfinished: Option<&str>,
6467) -> Starter {
6468    match review_branch {
6469        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6470        Some(_) => Starter::Start,
6471        None => match unfinished {
6472            Some(id) => Starter::Resume(id.to_owned()),
6473            None => Starter::Start,
6474        },
6475    }
6476}
6477
6478/// Reuse a compatible latest review owner instead of taking its checked-out
6479/// branch into a new run. Different branches and changed criteria still use
6480/// the ordinary review/takeover policy.
6481fn review_retry_starter(
6482    task: &Task,
6483    previous: Option<&RunState>,
6484    branch: Option<&str>,
6485    exists: bool,
6486    unfinished: Option<&str>,
6487) -> Starter {
6488    if let Some(run) = previous
6489        && unfinished == Some(run.id.as_str())
6490        && run.reviewed_commits.is_some()
6491        && branch.is_some_and(|branch| {
6492            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6493        })
6494        && may_resume_run(run, task)
6495    {
6496        return Starter::Resume(run.id.clone());
6497    }
6498    match (branch, unfinished, &task.review_of) {
6499        (None, None, Some(branch)) => Starter::Review(branch.clone()),
6500        _ => choose_starter(branch, exists, unfinished),
6501    }
6502}
6503
6504/// A retained review is valid only while its authored criteria still match.
6505fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
6506    task.review_branch
6507        .as_deref()
6508        .filter(|&branch| match &task.review_instruction {
6509            Some(authored) => *authored == task.instruction,
6510            // Legacy retained branches must agree with their prior run; only an
6511            // explicitly pinned review can proceed without recoverable provenance.
6512            None => previous.map_or_else(
6513                || task.review_of.as_deref() == Some(branch),
6514                |run| compatible_run_instruction(run, task),
6515            ),
6516        })
6517}
6518
6519/// A current explicit pin can select an otherwise incompatible run. Edits
6520/// and subsequent approvals invalidate pins selected for earlier criteria.
6521fn may_resume_run(run: &RunState, task: &Task) -> bool {
6522    if !task.assignment_accepts(run) {
6523        return false;
6524    }
6525    task.resume_override
6526        .as_ref()
6527        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6528        || compatible_run_instruction(run, task)
6529}
6530
6531/// Review scaffolding is execution context, not evidence of an operator edit.
6532pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6533    if let Some(authored) = &run.task_instruction {
6534        return compatible_instruction(authored, task);
6535    }
6536    if compatible_instruction(&run.instruction, task) {
6537        return true;
6538    }
6539    // Recognize only the existing generated review shapes on legacy runs.
6540    // Ordinary authored text with a similar heading is left intact.
6541    if run.reviewed_commits.is_some() {
6542        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6543            return strip_answers_block(authored, task).trim() == task.instruction.trim();
6544        }
6545        if let Some(branch) = &task.review_of {
6546            let canonical = format!(
6547                "Review the branch `{branch}` (review-only: no implementation, no judging)."
6548            );
6549            let generated = format!(
6550                "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"
6551            );
6552            return task.instruction == canonical && run.instruction.starts_with(&generated);
6553        }
6554    }
6555    false
6556}
6557
6558/// Compare authored instructions, excluding answer blocks appended by the daemon.
6559pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6560    strip_answers_block(old, task) == task.instruction
6561}
6562
6563/// Which repository a task runs in. A task that names none — the normal case
6564/// for one filed from a phone — runs in the daemon's own default.
6565fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6566    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6567        return fallback.to_path_buf();
6568    }
6569    task.repo.clone()
6570}
6571
6572/// The header [`append_answers`] appends operator answers under. Shared with
6573/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
6574/// rather than grown a new block on every resume.
6575const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6576
6577/// Render the first `count` answers in the block appended to an instruction.
6578fn answers_block(task: &Task, count: usize) -> String {
6579    let mut s = ANSWERS_HEADER.to_owned();
6580    for a in &task.answers[..count] {
6581        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6582    }
6583    s
6584}
6585
6586/// Render the approval independently of transient task state, so historical
6587/// suffixes remain recognizable after another explicit release.
6588fn resumption_block(r: &crate::queue::Resumption) -> String {
6589    format!(
6590        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6591         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6592        r.generation, r.at, r.instruction, r.answers_through,
6593    )
6594}
6595
6596/// Append audit answers and the latest explicit approval to the instruction.
6597fn append_answers(base: &str, task: &Task) -> String {
6598    let mut s = base.to_owned();
6599    if !task.answers.is_empty() {
6600        s.push_str(&answers_block(task, task.answers.len()));
6601    }
6602    if let Some(r) = &task.resumption {
6603        s.push_str(&resumption_block(r));
6604    }
6605    s
6606}
6607
6608/// Drop the prior answer block only when it is exactly the suffix this task
6609/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6610/// the task author is ordinary instruction text, not a block to remove.
6611fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6612    let mut instruction = instruction;
6613    for approval in task
6614        .resumption
6615        .iter()
6616        .chain(task.resumption_history.iter().rev())
6617    {
6618        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6619            instruction = base;
6620            break;
6621        }
6622    }
6623    for count in (1..=task.answers.len()).rev() {
6624        let block = answers_block(task, count);
6625        if let Some(base) = instruction.strip_suffix(&block) {
6626            return base;
6627        }
6628    }
6629    instruction
6630}
6631
6632/// The instruction handed to `Runner::start`: the task's own text, plus any
6633/// operator answers `crate::conduct` collected for it (see
6634/// [`Task::answers`]), so a decision the operator actually made reaches the
6635/// implementers rather than only clearing the block that was waiting on it.
6636///
6637/// Appended rather than merged into [`Task::instruction`] itself, so the
6638/// task's own record stays exactly what its author wrote.
6639fn instruction_for(task: &Task) -> String {
6640    append_answers(&task.instruction, task)
6641}
6642
6643/// The instruction a resumed run should carry on with: whatever it already
6644/// had, refreshed with the task's *current* operator answers.
6645///
6646/// A resumable run's own `RunState::instruction` predates any answer
6647/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6648/// the behaviour before this function existed — silently drops the very
6649/// decision the operator made to unblock it. Re-stripping any block this
6650/// function appended on an earlier resume before re-appending the current
6651/// list (rather than blindly appending again) is what keeps a task resumed
6652/// three times over three answered questions from carrying the same answer
6653/// three times.
6654fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6655    append_answers(strip_answers_block(old_instruction, task), task)
6656}
6657
6658/// Preserve the producer's verified boundary and target, independent of prose.
6659fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6660    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6661    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6662    if let Some(cause) = task.hold_notice_cause.as_mut() {
6663        cause.target = failure.map(|f| f.target.clone());
6664    }
6665}
6666
6667#[derive(Debug, thiserror::Error)]
6668#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6669struct MissingAttachment {
6670    name: String,
6671    path: PathBuf,
6672}
6673
6674/// The task's attachments as absolute paths, each checked to still exist.
6675fn task_attachments(
6676    queue: &Queue,
6677    task: &Task,
6678) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6679    let paths = queue.attachment_paths(task);
6680    for (name, path) in task.attachments.iter().zip(&paths) {
6681        if !path.is_file() {
6682            return Err(MissingAttachment {
6683                name: name.clone(),
6684                path: path.clone(),
6685            });
6686        }
6687    }
6688    Ok(paths)
6689}
6690
6691/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6692/// answers before handing it to `Runner` — the actual boundary between
6693/// [`choose_starter`]'s routing and the graph, factored out so it is
6694/// assertable without a real repository, git branch, or agent CLI.
6695///
6696/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6697/// instruction from the reviewed branch's own commit log because there is no
6698/// task statement to speak of for hand-written work, and splicing operator
6699/// answers into that text would contradict the very message it sends
6700/// reviewers ("there is no task statement").
6701fn prepare_instruction(
6702    starter: &Starter,
6703    old_instruction: Option<&str>,
6704    task: &Task,
6705) -> Option<String> {
6706    match starter {
6707        Starter::Start => Some(instruction_for(task)),
6708        Starter::Resume(_) => Some(resumed_instruction(
6709            old_instruction.expect("a resumed run always has a prior instruction"),
6710            task,
6711        )),
6712        Starter::Review(_) => None,
6713    }
6714}
6715
6716/// Persist a transition. A queue write failure is logged rather than fatal: the
6717/// run already happened, and taking the daemon down would only add a lost
6718/// backlog to a full disk.
6719fn record(queue: &Queue, task: &mut Task) {
6720    if let Err(e) = queue.put(task) {
6721        tracing::error!("could not record task {}: {e:#}", task.short());
6722        let notice = Notice::error(
6723            "loop:record",
6724            format!(
6725                "Task {} state could not be saved: {}. Check the disk.",
6726                task.id,
6727                e.to_string().lines().next().unwrap_or("unknown save error")
6728            ),
6729        )
6730        .link(Link::Task {
6731            id: task.id.clone(),
6732        });
6733        // The queue lives at `<home>/queue`, so its parent is the home.
6734        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6735            Some(home) => notices::raise_in(home, notice),
6736            None => notices::raise(notice),
6737        }
6738    }
6739}
6740
6741/// Every runnable task, in the order the loop should try them.
6742///
6743/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6744/// tail exists so that a claim somebody else holds costs the loop the next
6745/// candidate rather than a whole poll interval of idleness.
6746fn runnable(queue: &Queue) -> Vec<Task> {
6747    let mut tasks: Vec<Task> = queue
6748        .list()
6749        .into_iter()
6750        .filter(|t| t.status.runnable())
6751        .collect();
6752    tasks.sort_unstable_by(crate::queue::dispatch_order);
6753    tasks
6754}
6755
6756/// Why a run ended where it did, in one line, for [`Task::last_error`].
6757///
6758/// A stalled run names the seats the quota took out: "out of quota" is not
6759/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6760/// agent to replace or which plan to top up.
6761///
6762/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6763/// purpose: unlike `label`'s other callers (an internal log line, an
6764/// already-a-bug fallback message), this string becomes `Task::last_error`
6765/// verbatim, which the phone renders in the same alarm-styled box an
6766/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6767/// `.err` styling. A bare `verified_noop` there would read exactly like the
6768/// failure this whole feature exists to tell apart from one.
6769fn describe(state: &RunState) -> String {
6770    let p = phrases(&state.config.graph.language);
6771    let mut detail = if state.status == RunStatus::Stalled {
6772        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6773        seats.sort_unstable();
6774        seats.dedup();
6775        if seats.is_empty() {
6776            p.quorum_lost.to_owned()
6777        } else {
6778            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6779        }
6780    } else {
6781        format!("{}{}", p.run_ended, state.status.display_label())
6782    };
6783    if let Some(cause) = state.verification_blocking_cause() {
6784        detail.push_str(&format!(" ({cause})"));
6785    } else if let Some(last) = state.events.last() {
6786        // The review loop's "never answered" stop is the one event worth
6787        // translating; it is recognised from structured state, not by
6788        // matching the English event text (which stays as recorded).
6789        let unanswered = state
6790            .reviews
6791            .last()
6792            .filter(|r| {
6793                state.status == RunStatus::Blocked
6794                    && last.node == "review"
6795                    && r.incomplete()
6796                    && r.blocking == 0
6797                    && r.round == state.config.graph.review_rounds
6798                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6799            })
6800            .map(|r| (r.expected - r.answered, r.round));
6801        match unanswered {
6802            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6803                detail.push_str(&format!(
6804                    " ({}: {})",
6805                    last.node,
6806                    (p.reviewers_never_answered)(missing, rounds)
6807                ));
6808            }
6809            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6810        }
6811    }
6812    detail.push_str(&format!(" [run {}]", state.id));
6813    detail
6814}
6815
6816/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6817///
6818/// The task file lives in the backlog indefinitely; a diagnostic is an
6819/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6820/// stay small regardless of how much a gate command or a candidate printed.
6821const DIAGNOSTIC_MAX: usize = 4_000;
6822
6823/// Tail kept from a single failing command's output inside a diagnostic.
6824/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6825/// pointer for a human deciding whether to go read the full artifact by hand,
6826/// not a replacement for reading it.
6827const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6828
6829/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6830/// `magi task show` says more than the one-line reason in [`describe`].
6831///
6832/// The one-liner answers "where did the run stop"; this answers "what would a
6833/// human have found opening `artifacts/` by hand" — the point of the whole
6834/// feature is the case that one-liner actively misleads on: a run held as "no
6835/// candidate produced a change" can mean the implementer actually finished
6836/// the task (opened a PR, merged it, tagged a release) and only left a clean
6837/// local worktree behind, which reads as "nothing happened" unless someone
6838/// goes and reads what the agent actually said. `None` when the run carries
6839/// none of the three shapes this recognises — an ordinary run held for
6840/// something not diagnosable from `RunState` alone still explains itself
6841/// through `Task::last_error`.
6842fn diagnostic(state: &RunState) -> Option<String> {
6843    let mut parts: Vec<String> = Vec::new();
6844
6845    // Gate failure: which check(s), and the tail of what each printed.
6846    for o in state.gate.iter().filter(|o| !o.ok()) {
6847        parts.push(format!(
6848            "gate `{}` failed ({}):\n{}",
6849            o.command,
6850            notices::exit_status(o.code),
6851            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6852        ));
6853    }
6854
6855    // The land loop gave up because the fixer declined while checks were
6856    // still red: the message already names them (see `land::run`).
6857    if let Some(last) = state
6858        .events
6859        .iter()
6860        .rev()
6861        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6862    {
6863        parts.push(last.message.clone());
6864    }
6865
6866    // No viable candidate: every implementer's own final word, sanitized the
6867    // same way a judge would have read it, so a run that actually finished
6868    // the job does not read as an unexplained failure. A verified no-op is
6869    // called out ahead of its own summary and apart from an ordinary
6870    // failure's `why` — this is the one candidate shape whose diagnostic a
6871    // human is expected to actually judge, not just skim.
6872    if state.viable().is_empty() {
6873        for c in &state.candidates {
6874            if let Some(evidence) = &c.verified_noop {
6875                parts.push(format!(
6876                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6877                    c.label
6878                ));
6879            } else if !c.summary.trim().is_empty() {
6880                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6881            } else if let Some(why) = &c.failed {
6882                parts.push(format!("candidate {}: {why}", c.label));
6883            }
6884        }
6885    }
6886
6887    if parts.is_empty() {
6888        return None;
6889    }
6890    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6891    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6892    // back slightly over. Leave it enough room to always land under the
6893    // limit.
6894    Some(crate::run::tail(
6895        &parts.join("\n\n"),
6896        DIAGNOSTIC_MAX.saturating_sub(100),
6897    ))
6898}
6899
6900/// Stable lower-case name for a run status, for an internal log line and the
6901/// "graph stopped without reaching a terminal status" bug message in
6902/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6903/// doc for why that one reads [`RunStatus::display_label`] instead. One
6904/// definition of a status's name, on the type that owns it: this table used
6905/// to live here as a second copy, and a status renamed in one place would
6906/// have gone on reading correctly in the other.
6907fn label(status: RunStatus) -> &'static str {
6908    status.as_str()
6909}
6910
6911/// Parse a merge mode override.
6912pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6913    match mode {
6914        "none" => Ok(MergeMode::None),
6915        "local" => Ok(MergeMode::Local),
6916        "pr" => Ok(MergeMode::Pr),
6917        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6918    }
6919}
6920
6921/// Take the status lock, recovering from a poisoned one.
6922///
6923/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6924/// data, and the worst a poisoned lock can hold is a stale timestamp.
6925fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6926    mutex
6927        .lock()
6928        .unwrap_or_else(std::sync::PoisonError::into_inner)
6929}
6930
6931#[cfg(test)]
6932mod tests {
6933    use super::*;
6934    use crate::queue::{Source, TaskStatus};
6935    use crate::run::{Candidate, CommandOutcome};
6936    use pretty_assertions::assert_eq;
6937
6938    fn task() -> Task {
6939        Task::new(
6940            "add retries".to_owned(),
6941            "add retries".to_owned(),
6942            PathBuf::from("/repo"),
6943            Source::Human,
6944        )
6945    }
6946
6947    #[test]
6948    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
6949        let skips = DispatchSkips::from([
6950            ("a".into(), SkipReason::CoolingDown),
6951            ("b".into(), SkipReason::WaitingOnLanding),
6952            ("c".into(), SkipReason::WaitingOnLanding),
6953            ("d".into(), SkipReason::OrdinaryCapacity),
6954        ]);
6955        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
6956        assert_eq!(wait.runnable, 4);
6957        assert_eq!(
6958            wait.reasons
6959                .iter()
6960                .map(|r| (r.reason.as_str(), r.count))
6961                .collect::<Vec<_>>(),
6962            [
6963                ("waiting_on_landing", 2),
6964                ("cooling_down", 1),
6965                ("ordinary_capacity", 1)
6966            ]
6967        );
6968        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
6969        assert!(
6970            aggregate_dispatch_wait(2, &DispatchSkips::new())
6971                .unwrap()
6972                .reasons
6973                .is_empty()
6974        );
6975    }
6976
6977    #[test]
6978    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
6979        let before = vec!["a".into(), "b".into(), "c".into()];
6980        let allowed = vec![task_with_id("b")];
6981        let skips = interrupt_skips(&before, &allowed);
6982        assert_eq!(
6983            skips,
6984            DispatchSkips::from([
6985                ("a".into(), SkipReason::InterruptGate),
6986                ("c".into(), SkipReason::InterruptGate),
6987            ])
6988        );
6989        let mut previous = DispatchSkips::new();
6990        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
6991        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
6992        assert!(!changed_dispatch_skips(&mut previous, skips));
6993        assert!(changed_dispatch_skips(
6994            &mut previous,
6995            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
6996        ));
6997        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
6998    }
6999
7000    #[test]
7001    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
7002        let mut value = serde_json::to_value(Status::new()).unwrap();
7003        value.as_object_mut().unwrap().remove("dispatch_wait");
7004        assert!(
7005            serde_json::from_value::<Status>(value.clone())
7006                .unwrap()
7007                .dispatch_wait
7008                .is_none()
7009        );
7010        assert!(
7011            serde_json::from_value::<Reading>(value.clone())
7012                .unwrap()
7013                .dispatch_wait
7014                .is_none()
7015        );
7016        value["dispatch_wait"] = serde_json::json!({
7017            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
7018        });
7019        let reading = serde_json::from_value::<Reading>(value).unwrap();
7020        assert_eq!(
7021            reading.dispatch_wait.unwrap().reasons[0].reason,
7022            "future_reason"
7023        );
7024    }
7025
7026    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
7027        let job = crate::worker::Job {
7028            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
7029            sequence: 1,
7030            kind: "task".into(),
7031            key: format!("task:{}", request.task),
7032            payload: serde_json::to_value(request).unwrap(),
7033            generation: "a".repeat(64),
7034            version: None,
7035            status: crate::worker::Status::Starting,
7036            result: None,
7037            pid: None,
7038            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
7039            finished_at: None,
7040        };
7041        let dir = home.join("workers/jobs").join(&job.id);
7042        std::fs::create_dir_all(&dir).unwrap();
7043        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
7044        job
7045    }
7046
7047    #[test]
7048    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
7049        let home = tempfile::tempdir().unwrap();
7050        let request = TaskWorker {
7051            opts: Opts::default(),
7052            queue: home.path().join("queue"),
7053            task: "startup".into(),
7054            lane: PermitKind::Ordinary,
7055            standalone: false,
7056        };
7057        let job = starting_task_reservation(home.path(), &request);
7058        let error = task_worker_spawn_error(
7059            home.path(),
7060            &request,
7061            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
7062        )
7063        .expect_err("our own reservation must not turn a failed spawn into a resync");
7064        let active = crate::worker::active(home.path()).unwrap();
7065        assert_eq!(active.len(), 1);
7066        assert_eq!(active[0].id, job.id);
7067        assert_eq!(active[0].status, crate::worker::Status::Starting);
7068        assert!(
7069            crate::worker::control(home.path(), &job.key)
7070                .unwrap()
7071                .is_none()
7072        );
7073        let notices = notices::Notices::at(home.path().join("notifications")).list();
7074        assert_eq!(notices.len(), 1);
7075        assert_eq!(notices[0].key, "loop:worker-startup");
7076        assert!(!notices[0].message.contains("private-error-detail"));
7077        assert!(notices[0].message.contains(&request.task));
7078        assert!(
7079            notices[0]
7080                .message
7081                .contains("could not be started or acknowledged")
7082        );
7083        assert!(notices[0].message.contains("worker.log"));
7084        assert_eq!(
7085            notices[0].link,
7086            Some(Link::Task {
7087                id: request.task.clone()
7088            })
7089        );
7090        assert!(format!("{error:#}").contains("private-error-detail"));
7091    }
7092
7093    #[test]
7094    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
7095        let home = tempfile::tempdir().unwrap();
7096        let mut request = TaskWorker {
7097            opts: Opts::default(),
7098            queue: home.path().join("queue"),
7099            task: "handoff".into(),
7100            lane: PermitKind::Ordinary,
7101            standalone: true,
7102        };
7103        let job = starting_task_reservation(home.path(), &request);
7104        request.standalone = false;
7105        task_worker_spawn_error(
7106            home.path(),
7107            &request,
7108            anyhow::anyhow!("operation key is already reserved for a different request"),
7109        )
7110        .expect("a different standalone request is the handoff race, not our startup failure");
7111        let active = crate::worker::active(home.path()).unwrap();
7112        assert_eq!(active.len(), 1);
7113        assert_eq!(active[0].id, job.id);
7114        assert_eq!(active[0].payload, job.payload);
7115        assert!(
7116            notices::Notices::at(home.path().join("notifications"))
7117                .list()
7118                .is_empty()
7119        );
7120    }
7121
7122    #[test]
7123    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
7124        let home = tempfile::tempdir().unwrap();
7125        let queue = Queue::at(home.path().join("queue"));
7126        let mut task = task();
7127        task.runs = vec!["previous".into()];
7128        queue.put(&mut task).unwrap();
7129        let request = TaskWorker {
7130            opts: Opts::default(),
7131            queue: home.path().join("queue"),
7132            task: task.id.clone(),
7133            lane: PermitKind::Ordinary,
7134            standalone: false,
7135        };
7136        let job = starting_task_reservation(home.path(), &request);
7137        let claims = current_work(home.path(), Timestamp::now());
7138        assert_eq!(claims.len(), 1);
7139        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
7140        assert_eq!(claims[0].run, "previous");
7141        assert!(other_claims_run(&claims, "previous", None));
7142        // Only after confirming the executing caller may admission ignore
7143        // this exact projection. Cleanup continues to observe it as live.
7144        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
7145        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
7146    }
7147
7148    #[test]
7149    fn admission_excludes_only_the_callers_exact_reservation() {
7150        let own = Current {
7151            worker: Some("own".into()),
7152            task: "same-task".into(),
7153            run: "previous".into(),
7154        };
7155        assert!(!other_claims_run(
7156            std::slice::from_ref(&own),
7157            "previous",
7158            Some("own")
7159        ));
7160        assert!(other_claims_run(
7161            std::slice::from_ref(&own),
7162            "previous",
7163            None
7164        ));
7165        for worker in [None, Some("other".into())] {
7166            let other = Current {
7167                worker,
7168                ..own.clone()
7169            };
7170            assert!(other_claims_run(
7171                &[own.clone(), other],
7172                "previous",
7173                Some("own")
7174            ));
7175        }
7176        let legacy: Current =
7177            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
7178        assert!(other_claims_run(&[legacy], "previous", Some("own")));
7179    }
7180
7181    #[test]
7182    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
7183        let mut task = task();
7184        let mut run = run_state(RunStatus::Reviewing);
7185        run.task_instruction = Some(task.instruction.clone());
7186        run.reviewed_commits = Some(vec!["committed-fix".into()]);
7187        let branch = "magi/test/B";
7188        run.candidates.push(crate::run::Candidate {
7189            branch: branch.into(),
7190            ..candidate('B', "preserved work", false, None)
7191        });
7192        task.runs = vec![run.id.clone()];
7193        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
7194        assert_eq!(
7195            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7196            Starter::Resume(run.id.clone())
7197        );
7198        assert!(matches!(
7199            review_retry_starter(
7200                &task,
7201                Some(&run),
7202                Some("different"),
7203                true,
7204                unfinished.as_deref()
7205            ),
7206            Starter::Review(_)
7207        ));
7208        assert_eq!(
7209            review_retry_starter(
7210                &task,
7211                Some(&run),
7212                Some(branch),
7213                false,
7214                unfinished.as_deref()
7215            ),
7216            Starter::Start
7217        );
7218        task.instruction.push_str(" changed criteria");
7219        assert!(matches!(
7220            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7221            Starter::Review(_)
7222        ));
7223        assert!(matches!(
7224            review_retry_starter(&task, Some(&run), Some(branch), true, None),
7225            Starter::Review(_)
7226        ));
7227    }
7228
7229    #[test]
7230    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
7231        let dir = tempfile::tempdir().unwrap();
7232        let queue = Queue::at(dir.path().join("queue"));
7233        let mut task = task();
7234        task.status = TaskStatus::Running;
7235        task.attempts = 1;
7236        queue.put(&mut task).unwrap();
7237        let live = std::collections::BTreeSet::from([task.id.clone()]);
7238        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
7239        drop(queue.claim(&task.id).unwrap());
7240        let saved = queue.get(&task.id).unwrap();
7241        assert_eq!(saved.status, TaskStatus::Running);
7242        assert_eq!(saved.attempts, 1);
7243        assert!(saved.last_error.is_none());
7244    }
7245
7246    #[test]
7247    fn standalone_workers_do_not_consume_scheduler_lanes() {
7248        let request = |task: &str, lane, standalone| TaskWorker {
7249            opts: Opts::default(),
7250            queue: PathBuf::from("/queue"),
7251            task: task.to_owned(),
7252            lane,
7253            standalone,
7254        };
7255        let mut jobs = vec![
7256            request("ordinary", PermitKind::Ordinary, false),
7257            request("standalone-urgent", PermitKind::Urgent, true),
7258            request("standalone-ordinary", PermitKind::Ordinary, true),
7259            request("decision", PermitKind::None, false),
7260        ];
7261        assert_eq!(available_slots(&jobs, 2), (1, 1));
7262        jobs.push(request("urgent", PermitKind::Urgent, false));
7263        assert_eq!(available_slots(&jobs, 2), (1, 0));
7264        assert_eq!(available_slots(&jobs, 0), (0, 0));
7265    }
7266
7267    #[test]
7268    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
7269        let now = Timestamp::now();
7270        let mut reading = Reading {
7271            pid: Some(std::process::id()),
7272            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
7273            ..Reading::default()
7274        };
7275        assert!(!reading.running(now));
7276        assert!(legacy_scheduler_running(&reading, now, 0));
7277        reading.worker_protocol = Some(1);
7278        assert!(!legacy_scheduler_running(&reading, now, 0));
7279    }
7280
7281    #[test]
7282    fn selected_public_head_overrides_historical_resume_and_pin() {
7283        let mut t = task();
7284        let mut old = run_state(RunStatus::Blocked);
7285        let selection = crate::pr_recovery::Selection {
7286            url: "url".into(),
7287            branch: format!("magi/task-{}", t.id),
7288            head: "a".repeat(40),
7289            source_head: None,
7290            source_run: None,
7291            source_proof: None,
7292            disposition: Some(crate::pr_recovery::Disposition::Review),
7293            instruction: t.instruction.clone(),
7294            approved_at: Timestamp::now(),
7295        };
7296        t.resume_override = Some(crate::queue::OperatorResume {
7297            pinned_run: Some(old.id.clone()),
7298            question_id: "choice".into(),
7299            at: Timestamp::now(),
7300            conductor_rehold: None,
7301            forced: false,
7302        });
7303        assert_eq!(
7304            selected_starter(&selection, Some(&old), Some(&old.id)),
7305            Starter::Review(selection.branch.clone())
7306        );
7307        old.pr_recovery = Some(selection.clone());
7308        assert_eq!(
7309            selected_starter(&selection, Some(&old), Some(&old.id)),
7310            Starter::Review(selection.branch.clone())
7311        );
7312        old.reviewed_commits = Some(vec!["implementation".into()]);
7313        assert_eq!(
7314            selected_starter(&selection, Some(&old), Some(&old.id)),
7315            Starter::Resume(old.id.clone())
7316        );
7317        let mut changed = selection.clone();
7318        changed.head = "b".repeat(40);
7319        assert_eq!(
7320            selected_starter(&changed, Some(&old), Some(&old.id)),
7321            Starter::Review(changed.branch)
7322        );
7323    }
7324
7325    #[test]
7326    fn candidate_transplant_failure_is_one_actionable_hold() {
7327        let dir = tempfile::tempdir().unwrap();
7328        let q = Queue::at(dir.path().join("queue"));
7329        let mut t = task();
7330        let mut state = run_state(RunStatus::Blocked);
7331        state.event("prep", "cannot apply referenced commit: conflict");
7332        state.prep_failure = Some("conflict".into());
7333        t.start(state.id.clone());
7334        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
7335        assert_eq!(t.attempts, 1);
7336        assert_eq!(t.status, TaskStatus::Held);
7337        assert!(t.operator_held());
7338        assert!(!t.status.runnable());
7339        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
7340        let first = t.chat_notice_key().unwrap();
7341        t.chat_notices.push(first.clone());
7342        t.release_operator("test", None);
7343        state.id = "another-unprepared-run".into();
7344        t.start(state.id.clone());
7345        finish_attempt(
7346            3,
7347            &q,
7348            &mut t,
7349            &state,
7350            &[],
7351            Err(anyhow::anyhow!("still conflicts")),
7352        );
7353        assert_eq!(
7354            t.chat_notice_key().as_ref(),
7355            Some(&first),
7356            "no work happened"
7357        );
7358        t.release_operator("test", None);
7359        state.prep_failure = None;
7360        state.status = RunStatus::Failed;
7361        state.begin_pass();
7362        t.start(state.id.clone());
7363        finish_attempt(
7364            1,
7365            &q,
7366            &mut t,
7367            &state,
7368            &[],
7369            Err(anyhow::anyhow!("new gate failure")),
7370        );
7371        let failure = t.chat_notice_key().unwrap();
7372        assert_ne!(failure, first, "approved recovery reached a real failure");
7373        t.release_operator("test", None);
7374        state.begin_pass();
7375        t.start(state.id.clone());
7376        finish_attempt(
7377            1,
7378            &q,
7379            &mut t,
7380            &state,
7381            &[],
7382            Err(anyhow::anyhow!("new failure on resume")),
7383        );
7384        assert_ne!(
7385            t.chat_notice_key().as_ref(),
7386            Some(&failure),
7387            "a new settled pass"
7388        );
7389    }
7390
7391    #[test]
7392    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7393        for source in ["cli", "web"] {
7394            let mut t = task();
7395            let mut run = run_state(RunStatus::Blocked);
7396            run.instruction = "Run A original criteria".into();
7397            run.task_instruction = Some(run.instruction.clone());
7398            t.start(run.id.clone());
7399            t.release_operator("choice", Some("resume-question"));
7400            t.resume_override = Some(crate::queue::OperatorResume {
7401                question_id: "resume-question".into(),
7402                at: Timestamp::now(),
7403                conductor_rehold: None,
7404                forced: true,
7405                pinned_run: Some(run.id.clone()),
7406            });
7407            t.hold_machine(Some("not enough free space to start a run".into()));
7408            let mut unchanged = t.clone();
7409            unchanged
7410                .edit("title changed".into(), unchanged.instruction.clone())
7411                .unwrap();
7412            unchanged.release_operator(source, None);
7413            assert_eq!(
7414                unchanged
7415                    .resume_override
7416                    .as_ref()
7417                    .unwrap()
7418                    .pinned_run
7419                    .as_deref(),
7420                Some(run.id.as_str())
7421            );
7422            assert!(!compatible_run_instruction(&run, &unchanged));
7423            assert!(may_resume_run(&run, &unchanged));
7424
7425            t.edit(
7426                "approved recovery".into(),
7427                "Reuse measured PR head B; fix Clippy; review".into(),
7428            )
7429            .unwrap();
7430            assert!(t.resume_override.is_none());
7431            t.release_operator(source, None);
7432            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7433            assert!(reloaded.resume_override.is_none());
7434            assert!(!may_resume_run(&run, &reloaded));
7435            let unfinished =
7436                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7437                    .filter(|_| may_resume_run(&run, &reloaded));
7438            assert_eq!(
7439                choose_starter(None, false, unfinished.as_deref()),
7440                Starter::Start
7441            );
7442            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7443            assert_eq!(
7444                reloaded.resumption_history[0].question_id.as_deref(),
7445                Some("resume-question")
7446            );
7447
7448            // A revision already persisted with the old approval/pin is also
7449            // invalidated when the new operator release is recorded.
7450            unchanged.instruction = "Reuse measured PR head B".into();
7451            unchanged.hold_machine(Some("disk hold".into()));
7452            unchanged.release_operator(source, None);
7453            assert!(unchanged.resume_override.is_none());
7454            assert!(!may_resume_run(&run, &unchanged));
7455        }
7456    }
7457
7458    #[test]
7459    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7460        let mut t = task();
7461        let mut run = run_state(RunStatus::Blocked);
7462        t.review_of = Some("approved-head".into());
7463        t.instruction =
7464            "Review the branch `approved-head` (review-only: no implementation, no judging)."
7465                .into();
7466        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();
7467        run.reviewed_commits = Some(vec!["Commit log".into()]);
7468        t.start(run.id.clone());
7469        t.hold_machine(Some("interrupted review".into()));
7470        t.release_operator("cli", None);
7471        assert!(
7472            compatible_run_instruction(&run, &t),
7473            "legacy explicit review remains resumable"
7474        );
7475        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7476            .filter(|_| compatible_run_instruction(&run, &t));
7477        assert_eq!(
7478            choose_starter(None, false, unfinished.as_deref()),
7479            Starter::Resume(run.id.clone())
7480        );
7481        run.task_instruction = Some(t.instruction.clone());
7482        assert!(compatible_run_instruction(&run, &t));
7483        let reloaded: RunState =
7484            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7485        assert!(compatible_run_instruction(&reloaded, &t));
7486        t.edit(
7487            "new approved head".into(),
7488            "Reuse measured PR head B".into(),
7489        )
7490        .unwrap();
7491        assert!(!compatible_run_instruction(&run, &t));
7492
7493        // Legacy recovery reviews retain the task criteria ahead of the log.
7494        t.review_of = None;
7495        t.instruction = "Fix Clippy on approved head".into();
7496        run.task_instruction = None;
7497        run.instruction = format!(
7498            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7499            t.instruction
7500        );
7501        assert!(compatible_run_instruction(&run, &t));
7502        t.instruction.push('\n');
7503        assert!(
7504            compatible_run_instruction(&run, &t),
7505            "legacy generated review trimmed the original criteria"
7506        );
7507        t.hold_for_handover(Some("approved-head".into()), "refused".into());
7508        assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
7509        t.edit("new plan".into(), "Reuse measured PR head B".into())
7510            .unwrap();
7511        assert!(review_branch_for(&t, Some(&run)).is_none());
7512        assert!(!compatible_run_instruction(&run, &t));
7513        t.review_branch = Some("approved-head".into());
7514        t.review_instruction = None;
7515        assert!(
7516            review_branch_for(&t, Some(&run)).is_none(),
7517            "legacy retained candidate cannot replace a revised approved head"
7518        );
7519    }
7520
7521    #[test]
7522    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7523        let home = crate::run::test_home();
7524        crate::run::pin_test_home();
7525        let dir = tempfile::tempdir().unwrap();
7526        let queue = Queue::at(dir.path().join("queue"));
7527        for resume in [true, false] {
7528            let state = run_state(RunStatus::Blocked);
7529            let mut t = task();
7530            t.start(state.id.clone());
7531            let action = if resume {
7532                ask::ChoiceAction::Resume {
7533                    run: state.id.clone(),
7534                }
7535            } else {
7536                ask::ChoiceAction::Requeue
7537            };
7538            let mut q = action_question(&state.id, action);
7539            q.status = ask::QuestionStatus::Open;
7540            q.answer = None;
7541            q.answered_at = None;
7542            t.fail("run stopped with a question", 3);
7543            hold_if_runnable(&queue, &mut t);
7544            assert!(t.operator_decided_at.is_none());
7545            assert!(t.operator_held());
7546            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7547            let expected = if resume {
7548                ActionDecision::Resume(state.id.clone())
7549            } else {
7550                ActionDecision::Requeue
7551            };
7552            assert_eq!(
7553                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7554                expected
7555            );
7556            t.hold_manual(Some("later explicit hold".into()));
7557            assert_eq!(
7558                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7559                ActionDecision::Stale
7560            );
7561        }
7562    }
7563
7564    #[test]
7565    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7566        let mut t = task();
7567        t.answers.push(crate::queue::AnsweredQuestion {
7568            question: "Inspect the remote?".into(),
7569            answer: "Inspect then wait".into(),
7570        });
7571        let old = instruction_for(&t);
7572        assert!(compatible_instruction(&old, &t));
7573        t.instruction = "Reuse approved PR head and review".into();
7574        t.release_operator("cli", None);
7575        assert!(!compatible_instruction(&old, &t));
7576        let approved = instruction_for(&t);
7577        assert!(approved.contains("waiting premises are superseded"));
7578        assert!(compatible_instruction(&approved, &t));
7579        assert_eq!(resumed_instruction(&approved, &t), approved);
7580        t.release_operator("web", None);
7581        assert!(compatible_instruction(&approved, &t));
7582        assert_eq!(t.resumption_history.len(), 1);
7583        t.start("run".into());
7584        assert!(instruction_for(&t).contains("Explicit operator resumption"));
7585    }
7586
7587    /// A run that stopped on an infrastructure wait asked no agent anything:
7588    /// the task is held by the machine under a `[resource]` reason (resumable,
7589    /// re-checked by triage), and the attempt it started is given back.
7590    #[test]
7591    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7592        let mut state = RunState::new(
7593            PathBuf::from("/repo"),
7594            "main".into(),
7595            "base".into(),
7596            "task".into(),
7597            Config::default(),
7598        );
7599        state.status = RunStatus::Landing;
7600        state.parked = true;
7601        state.pr_pushed_head = Some("head".into());
7602        state.land_unrelated = Some(
7603            serde_json::from_value(serde_json::json!({
7604                "head": "head", "question": "ci-question",
7605                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7606            }))
7607            .unwrap(),
7608        );
7609        let mut t = task();
7610        t.start(state.id.clone());
7611        let verdict = Verdict {
7612            status: RunStatus::Landing,
7613            left_pr: true,
7614            quota_hit: false,
7615            parked: true,
7616            no_viable_candidates: false,
7617        };
7618        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7619        assert_eq!(t.attempts, 0);
7620        assert_eq!(t.status, TaskStatus::Held);
7621        assert!(!t.operator_held());
7622        assert!(
7623            t.hold_reason
7624                .as_deref()
7625                .unwrap()
7626                .starts_with("[ci-unrelated]")
7627        );
7628        // A second settlement must not refund an earlier task attempt.
7629        t.attempts = 1;
7630        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7631        assert_eq!(t.attempts, 1);
7632        assert_eq!(t.passes.len(), 1);
7633        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7634        state.pr_pushed_head = Some("new-head".into());
7635        state.parked = false;
7636        state.status = RunStatus::Blocked;
7637        let stale = Verdict {
7638            status: RunStatus::Blocked,
7639            parked: false,
7640            ..verdict
7641        };
7642        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7643        assert_eq!(t.attempts, 1);
7644        // A new execution pass can refund its own newly charged attempt.
7645        state.begin_pass();
7646        state.begin_pass();
7647        state.status = RunStatus::Landing;
7648        state.parked = true;
7649        state.pr_pushed_head = Some("head".into());
7650        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7651        assert_eq!(t.attempts, 0);
7652        assert_eq!(t.passes.len(), 2);
7653    }
7654
7655    #[test]
7656    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7657        let mut state = run_state(RunStatus::Failed);
7658        state
7659            .quota
7660            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7661        state.begin_pass();
7662        let mut t = task();
7663        t.start(state.id.clone());
7664        reclaim(&mut t, Some(state), 2, "en");
7665        assert_eq!(t.attempts, 1);
7666    }
7667
7668    #[test]
7669    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7670        let mut state = run_state(RunStatus::Blocked);
7671        let losses: Vec<_> = ["alpha", "beta"]
7672            .into_iter()
7673            .enumerate()
7674            .map(|(i, agent)| {
7675                QuotaLoss::from_report(
7676                    format!("advisor-{i}"),
7677                    "advise",
7678                    Some(&crate::agent::Quota {
7679                        cause: crate::agent::QuotaCause::Authentication,
7680                        agent: agent.to_owned(),
7681                        reset: None,
7682                    }),
7683                )
7684            })
7685            .collect();
7686        crate::graph::block_machine_outage(&mut state, "advise", &losses);
7687        state.quota = losses;
7688        let mut t = task();
7689        t.start(state.id.clone());
7690        let verdict = Verdict {
7691            status: state.status,
7692            left_pr: false,
7693            quota_hit: true,
7694            parked: false,
7695            no_viable_candidates: true,
7696        };
7697        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7698        assert_eq!(t.attempts, 0);
7699        assert_eq!(t.status, TaskStatus::Held);
7700        assert!(!t.operator_held());
7701        let reason = t.hold_reason.as_deref().unwrap();
7702        assert!(reason.starts_with("[authentication]"));
7703        assert!(
7704            reason.contains("alpha")
7705                && reason.contains("beta")
7706                && reason.contains("re-authenticate")
7707        );
7708        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7709        // Orphan recovery uses the same settlement and cannot spend an attempt.
7710        let mut orphan = task();
7711        orphan.start(state.id.clone());
7712        reclaim(&mut orphan, Some(state), 2, "en");
7713        assert_eq!(orphan.attempts, 0);
7714        assert_eq!(orphan.status, TaskStatus::Held);
7715    }
7716
7717    #[test]
7718    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7719        let mut state = RunState::new(
7720            PathBuf::from("/repo"),
7721            "main".to_owned(),
7722            "abc1234".to_owned(),
7723            "task".to_owned(),
7724            Config::default(),
7725        );
7726        state.status = RunStatus::Blocked;
7727        state.resource_block = Some(crate::run::ResourceBlock {
7728            cause: crate::run::ResourceBlockCause::Other,
7729            node: "graft".to_owned(),
7730            kind: "shared build cache".to_owned(),
7731            detail: "timed out".to_owned(),
7732            at: jiff::Timestamp::now(),
7733        });
7734        let mut t = task();
7735        t.start("20260902-000000-aaaa".to_owned());
7736        assert_eq!(t.attempts, 1);
7737        let verdict = Verdict {
7738            status: RunStatus::Blocked,
7739            left_pr: false,
7740            quota_hit: false,
7741            parked: false,
7742            no_viable_candidates: false,
7743        };
7744        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7745        assert_eq!(t.status, TaskStatus::Held);
7746        assert_eq!(t.attempts, 0, "the attempt is refunded");
7747        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7748        assert!(
7749            !t.operator_held(),
7750            "a machine hold, released without a human"
7751        );
7752
7753        let mut selected = task();
7754        selected.start("20260902-000000-cccc".into());
7755        selected.replacement = Some(crate::merge_decision::Replacement {
7756            question: "fixture".into(),
7757            run: "earlier".into(),
7758            pr: "https://example.invalid/pr/1".into(),
7759            agent: "selected".into(),
7760            context: "fixture".into(),
7761        });
7762        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7763        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7764        assert_eq!(selected.attempts, 0);
7765        assert!(
7766            !selected.operator_held(),
7767            "a selected agent also retains a machine resource hold"
7768        );
7769        assert!(
7770            selected
7771                .hold_reason
7772                .as_deref()
7773                .unwrap()
7774                .starts_with("[resource] ")
7775        );
7776
7777        // A park request outranks it: still the operator's doing.
7778        let mut p = task();
7779        p.start("20260902-000000-bbbb".to_owned());
7780        settle_and_diagnose(
7781            &mut p,
7782            Verdict {
7783                parked: true,
7784                ..verdict
7785            },
7786            "parked",
7787            2,
7788            &state,
7789        );
7790        assert_eq!(p.status, TaskStatus::Parked);
7791        assert_eq!(
7792            p.attempts, 0,
7793            "parking refunds once rather than also settling the resource hold"
7794        );
7795    }
7796
7797    #[test]
7798    fn record_failure_notice_links_the_task() {
7799        let dir = tempfile::tempdir().unwrap();
7800        // A regular file where the queue directory should be makes every
7801        // `put` fail, on every platform and whoever runs the test.
7802        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7803        let queue = Queue::at(dir.path().join("queue"));
7804        let mut t = interrupt_task("rec-fail-1");
7805        record(&queue, &mut t);
7806
7807        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7808        assert_eq!(found.len(), 1);
7809        assert_eq!(found[0].key, "loop:record");
7810        assert_eq!(
7811            found[0].link,
7812            Some(Link::Task {
7813                id: "rec-fail-1".to_owned()
7814            })
7815        );
7816    }
7817
7818    /// A runnable task marked to interrupt, with an id fixed for assertions
7819    /// rather than the random one [`Task::new`] mints.
7820    fn interrupt_task(id: &str) -> Task {
7821        let mut t = task();
7822        t.id = id.to_owned();
7823        t.interrupt = true;
7824        t
7825    }
7826
7827    /// An ordinary runnable task with an id fixed for assertions.
7828    fn task_with_id(id: &str) -> Task {
7829        let mut t = task();
7830        t.id = id.to_owned();
7831        t
7832    }
7833
7834    /// A runnable task marked `--urgent`, with an id fixed for assertions.
7835    fn urgent_task(id: &str) -> Task {
7836        let mut t = task();
7837        t.id = id.to_owned();
7838        t.urgent = true;
7839        t
7840    }
7841
7842    #[test]
7843    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7844        let dir = tempfile::tempdir().unwrap();
7845        let queue = Queue::at(dir.path().join("queue"));
7846        let mut parked = task_with_id("parked");
7847        parked.start("run".into());
7848        parked.park("upgrade");
7849        parked.record_pass_at(
7850            "run",
7851            0,
7852            Some(Timestamp::now()),
7853            1,
7854            Some(crate::run::ParkCause::Upgrade {
7855                from: "old".into(),
7856                to: None,
7857            }),
7858        );
7859        let mut fresh = task_with_id("fresh");
7860        fresh.priority = 100;
7861        let mut urgent_task = urgent_task("urgent");
7862        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7863            queue.put(t).unwrap();
7864        }
7865        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7866        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7867        let candidates = runnable(&queue);
7868        assert_eq!(candidates[0].id, parked.id);
7869        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7870        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
7871        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
7872        drop(first);
7873        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7874        let next = runnable(&queue)
7875            .into_iter()
7876            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
7877            .unwrap();
7878        assert_eq!(next.task.id, fresh.id);
7879        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7880        drop(claimed_elsewhere);
7881        drop(next);
7882        assert!(matches!(
7883            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
7884            Err(SkipReason::CoolingDown)
7885        ));
7886    }
7887
7888    #[test]
7889    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7890        let dir = tempfile::tempdir().unwrap();
7891        let queue = Queue::at(dir.path().join("queue"));
7892        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7893        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7894        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7895        let mut first = task();
7896        queue.put(&mut first).unwrap();
7897        let stale_plain = queue.get(&first.id).unwrap();
7898        first.set_urgent(true).unwrap();
7899        queue.put(&mut first).unwrap();
7900        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7901        let mut second = urgent_task("second");
7902        queue.put(&mut second).unwrap();
7903        assert!(matches!(
7904            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
7905            Err(SkipReason::UrgentCapacity)
7906        ));
7907        drop(queue.claim(&second.id).unwrap());
7908        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7909        drop(dispatched);
7910        let stale_urgent = queue.get(&first.id).unwrap();
7911        first.set_urgent(false).unwrap();
7912        queue.put(&mut first).unwrap();
7913        assert!(matches!(
7914            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
7915            Err(SkipReason::OrdinaryCapacity)
7916        ));
7917        assert_eq!(urgent.available_permits(), 1);
7918        drop(queue.claim(&first.id).unwrap());
7919        drop(occupied);
7920    }
7921
7922    #[test]
7923    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7924        let dir = tempfile::tempdir().unwrap();
7925        let queue = Queue::at(dir.path().join("queue"));
7926        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7927        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7928        let mut t = task();
7929        queue.put(&mut t).unwrap();
7930        for enabled in [true, false] {
7931            let stale = queue.get(&t.id).unwrap();
7932            t.set_urgent(enabled).unwrap();
7933            queue.put(&mut t).unwrap();
7934            assert_ne!(stale.urgent, enabled);
7935            let DispatchClaim {
7936                task: fresh,
7937                claim,
7938                permit,
7939            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7940            assert_eq!(fresh.urgent, enabled);
7941            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7942            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7943            assert!(queue.claim(&t.id).is_err());
7944            assert_eq!(fresh.attempts, stale.attempts);
7945            drop((claim, permit));
7946            assert_eq!(ordinary.available_permits(), 1);
7947            assert_eq!(urgent.available_permits(), 1);
7948        }
7949        t.set_urgent(true).unwrap();
7950        queue.put(&mut t).unwrap();
7951        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7952        assert!(matches!(
7953            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7954            Err(SkipReason::UrgentCapacity)
7955        ));
7956        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7957        drop(queue.claim(&t.id).unwrap());
7958        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7959        drop(occupied);
7960        assert!(matches!(
7961            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
7962            Err(SkipReason::CoolingDown)
7963        ));
7964        drop(queue.claim(&t.id).unwrap());
7965        let held = queue.claim(&t.id).unwrap();
7966        assert!(matches!(
7967            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7968            Err(SkipReason::ClaimUnavailable)
7969        ));
7970        drop(held);
7971        t.status = TaskStatus::Held;
7972        queue.put(&mut t).unwrap();
7973        assert!(matches!(
7974            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7975            Err(SkipReason::NoLongerRunnable)
7976        ));
7977        drop(queue.claim(&t.id).unwrap());
7978        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7979        assert!(matches!(
7980            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7981            Err(SkipReason::RereadFailed)
7982        ));
7983        drop(queue.claim(&t.id).unwrap());
7984        assert_eq!(urgent.available_permits(), 1);
7985    }
7986
7987    /// The land-resume exemption wins outright, whether or not the candidate
7988    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7989    /// queue behind anything" guarantee cannot be weaker just because the
7990    /// same task was also filed with `--urgent`.
7991    #[test]
7992    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7993        assert_eq!(permit_kind(true, false), PermitKind::None);
7994        assert_eq!(permit_kind(true, true), PermitKind::None);
7995    }
7996
7997    /// The one property this whole feature exists for: `--urgent` draws from
7998    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7999    /// ordinary candidate draws from the ordinary pool exactly as before,
8000    /// untouched by the urgent slot's existence.
8001    #[test]
8002    fn permit_kind_separates_urgent_from_ordinary() {
8003        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
8004        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
8005    }
8006
8007    /// The exact wiring `attempt` runs before minting anything: a config's
8008    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
8009    /// Free space is injected rather than asked of the real disk - the point
8010    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
8011    /// is deterministic on every machine this test runs on, never dependent
8012    /// on how full the CI runner's own disk happens to be.
8013    #[test]
8014    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
8015        let cfg = Config::default();
8016        let repo = Path::new("/any/repo/path");
8017
8018        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
8019            .expect("must hold below the threshold");
8020        assert!(reason.contains("1024"), "{reason}");
8021        assert!(
8022            reason.contains(&cfg.disk.min_free_bytes.to_string()),
8023            "{reason}"
8024        );
8025
8026        assert_eq!(
8027            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
8028            None,
8029            "exactly at the floor is open"
8030        );
8031        assert_eq!(
8032            disk_gate_with(
8033                repo,
8034                &cfg,
8035                PathBuf::new,
8036                |_| Ok(cfg.disk.min_free_bytes + 1)
8037            ),
8038            None,
8039            "comfortably above the floor is open"
8040        );
8041    }
8042
8043    #[test]
8044    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
8045        let dir = tempfile::tempdir().unwrap();
8046        let repo = dir.path().join("repo");
8047        let cache = dir.path().join("cache");
8048        let worktrees = dir.path().join("worktrees");
8049        for path in [&repo, &cache, &worktrees] {
8050            std::fs::create_dir(path).unwrap();
8051        }
8052        let mut cfg = Config::default();
8053        cfg.graph.worktree_root = Some(worktrees.clone());
8054        cfg.verify.gate = vec![format!(
8055            "CARGO_TARGET_DIR='{}' cargo build",
8056            cache.display()
8057        )];
8058        for blocked in [&cache, &worktrees] {
8059            for unmeasured in [false, true] {
8060                assert!(
8061                    disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
8062                        if path == blocked {
8063                            if unmeasured {
8064                                Err(anyhow::anyhow!("measurement failed"))
8065                            } else {
8066                                Ok(0)
8067                            }
8068                        } else {
8069                            Ok(u64::MAX)
8070                        }
8071                    })
8072                    .is_some(),
8073                    "a blocked secondary output volume must close admission"
8074                );
8075            }
8076        }
8077        assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
8078    }
8079
8080    #[test]
8081    fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
8082        let dir = tempfile::tempdir().unwrap();
8083        let repo = dir.path().join("repo");
8084        let cache = dir.path().join("cache");
8085        let home_parent = dir.path().join("run-volume");
8086        let home = home_parent.join("new-home");
8087        for path in [&repo, &cache, &home_parent] {
8088            std::fs::create_dir(path).unwrap();
8089        }
8090        let mut cfg = Config::default();
8091        cfg.graph.worktree_root = Some(repo.clone());
8092        cfg.verify.gate = vec![format!(
8093            "CARGO_TARGET_DIR='{}' cargo build",
8094            cache.display()
8095        )];
8096        cfg.verify.build_cache = BuildCache::Isolated;
8097        let denied = |blocked: &Path| {
8098            disk_gate_with(
8099                &repo,
8100                &cfg,
8101                || home.clone(),
8102                |path| Ok(if path == blocked { 0 } else { u64::MAX }),
8103            )
8104            .is_some()
8105        };
8106        assert!(!denied(&cache));
8107        assert!(denied(&home_parent));
8108    }
8109
8110    #[test]
8111    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
8112        let mut cfg = Config::default();
8113        cfg.disk.min_free_bytes = 0;
8114        let repo = Path::new("/any/repo/path");
8115        assert_eq!(
8116            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
8117            None,
8118            "a zero floor never measures at all"
8119        );
8120    }
8121
8122    #[test]
8123    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
8124        let cfg = Config::default();
8125        let repo = Path::new("/any/repo/path");
8126        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
8127            Err(anyhow::anyhow!("no df on this box"))
8128        })
8129        .expect("a measurement failure must close the gate, not open it");
8130        assert!(reason.contains("could not measure"), "{reason}");
8131    }
8132
8133    #[test]
8134    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
8135        let ordinary = task();
8136        let next = advance_interrupt(
8137            Interrupt::Idle,
8138            std::slice::from_ref(&ordinary.id),
8139            std::slice::from_ref(&ordinary),
8140        );
8141        assert_eq!(next, Interrupt::Idle);
8142    }
8143
8144    #[test]
8145    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
8146        // Nothing to interrupt - this is just an ordinary candidate, and the
8147        // loop's normal dispatch will pick it up like any other.
8148        let marked = interrupt_task("marked");
8149        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8150        assert_eq!(next, Interrupt::Idle);
8151    }
8152
8153    #[test]
8154    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
8155        let marked = interrupt_task("marked");
8156        let next = advance_interrupt(
8157            Interrupt::Idle,
8158            &["running".to_owned()],
8159            std::slice::from_ref(&marked),
8160        );
8161        assert_eq!(
8162            next,
8163            Interrupt::Parking {
8164                parked: vec!["running".to_owned()],
8165                interrupt_task: "marked".to_owned(),
8166            }
8167        );
8168    }
8169
8170    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
8171    /// one run can be in flight when a task becomes runnable and marked.
8172    /// Parking all of them would mean `Resuming` later has more than one id
8173    /// to release back to ordinary dispatch, which cannot be made safe
8174    /// against that same setting's own extra concurrency slots letting two
8175    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
8176    /// The simplification the task's own constraints ask for: do not begin
8177    /// a sequence at all until the herd settles back to exactly one.
8178    #[test]
8179    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
8180        let marked = interrupt_task("marked");
8181
8182        let two = advance_interrupt(
8183            Interrupt::Idle,
8184            &["a".to_owned(), "b".to_owned()],
8185            std::slice::from_ref(&marked),
8186        );
8187        assert_eq!(two, Interrupt::Idle);
8188
8189        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8190        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
8191    }
8192
8193    #[test]
8194    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
8195        let state = Interrupt::Parking {
8196            parked: vec!["running".to_owned()],
8197            interrupt_task: "marked".to_owned(),
8198        };
8199        // Still in flight: no change.
8200        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
8201        assert_eq!(still_going, state);
8202
8203        // Left flight, but the interrupt task has not been dispatched yet on
8204        // this tick - stays `Parking` so `interrupt_gate` can let it through,
8205        // as long as it is still runnable.
8206        let stopped_but_not_yet_dispatched =
8207            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
8208        assert_eq!(stopped_but_not_yet_dispatched, state);
8209
8210        // Left flight, and the interrupt task is now in flight itself.
8211        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
8212        assert_eq!(
8213            dispatched,
8214            Interrupt::Running {
8215                parked: vec!["running".to_owned()],
8216                interrupt_task: "marked".to_owned(),
8217            }
8218        );
8219    }
8220
8221    #[test]
8222    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
8223        let state = Interrupt::Running {
8224            parked: vec!["running".to_owned()],
8225            interrupt_task: "marked".to_owned(),
8226        };
8227        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
8228        assert_eq!(still_running, state);
8229
8230        // Whatever it ended as - merged, failed, held - is not this
8231        // function's concern: leaving flight is the only trigger, driven
8232        // straight off the same in-flight list `poll` already reaps. It does
8233        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
8234        // why that would let an unrelated task start ahead of, or alongside,
8235        // the guaranteed resume.
8236        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
8237        assert_eq!(
8238            ended,
8239            Interrupt::Resuming {
8240                parked: vec!["running".to_owned()]
8241            }
8242        );
8243    }
8244
8245    #[test]
8246    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
8247        let state = Interrupt::Resuming {
8248            parked: vec!["running".to_owned()],
8249        };
8250        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
8251        assert_eq!(still_waiting, state);
8252
8253        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
8254        assert_eq!(dispatched, Interrupt::Idle);
8255    }
8256
8257    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
8258    /// or otherwise moved on by an operator with no claim standing in the
8259    /// way - must not wedge the sequence (and so the whole loop's dispatch,
8260    /// via `interrupt_gate`) waiting forever for a dispatch that can never
8261    /// come. The parked run still gets its resume.
8262    #[test]
8263    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
8264    {
8265        let state = Interrupt::Parking {
8266            parked: vec!["running".to_owned()],
8267            interrupt_task: "marked".to_owned(),
8268        };
8269        // `marked` has been held/blocked/deleted since the sequence began:
8270        // it no longer appears in `runnable` at all.
8271        let next = advance_interrupt(state, &[], &[]);
8272        assert_eq!(
8273            next,
8274            Interrupt::Resuming {
8275                parked: vec!["running".to_owned()]
8276            },
8277            "abandoning the interrupt must not abandon the resume it owes"
8278        );
8279    }
8280
8281    /// The same abandonment, one step later: `Resuming` itself must not wait
8282    /// forever for a parked task that has since become unrunnable.
8283    #[test]
8284    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
8285        let state = Interrupt::Resuming {
8286            parked: vec!["running".to_owned()],
8287        };
8288        let next = advance_interrupt(state, &[], &[]);
8289        assert_eq!(
8290            next,
8291            Interrupt::Idle,
8292            "nothing is left to wait for; the loop must not stay wedged"
8293        );
8294    }
8295
8296    #[test]
8297    fn disabled_by_config_the_sequence_can_never_leave_idle() {
8298        let marked = interrupt_task("marked");
8299        let next = advance_interrupt_tick(
8300            false,
8301            Interrupt::Idle,
8302            &["running".to_owned()],
8303            std::slice::from_ref(&marked),
8304        );
8305        assert_eq!(
8306            next,
8307            Interrupt::Idle,
8308            "an unmarked, unconfigured daemon must behave exactly as before"
8309        );
8310    }
8311
8312    #[test]
8313    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
8314        let state = Interrupt::Parking {
8315            parked: vec!["running".to_owned()],
8316            interrupt_task: "marked".to_owned(),
8317        };
8318        let candidates = vec![interrupt_task("marked"), task()];
8319        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8320        assert!(
8321            allowed.is_empty(),
8322            "nothing may dispatch - not even the interrupt task itself - \
8323             until the parked run has actually stopped"
8324        );
8325    }
8326
8327    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
8328    /// grow a special case for it: an urgent candidate that is not the
8329    /// interrupt task withholds exactly like an ordinary one for as long as
8330    /// the parked run it is racing has not actually left flight. A version
8331    /// of this feature once bypassed the gate for urgent candidates, on the
8332    /// theory that a genuinely separate concurrency lane could not collide
8333    /// with 75dd's own; it could, and did - the bypassed task dispatched
8334    /// alongside a run 75dd's own state machine had only *asked* to park,
8335    /// not yet confirmed gone, which is exactly the second run
8336    /// `Interrupt::Parking`'s own doc says must never happen. There is no
8337    /// tick during Parking/Running/Resuming where letting an extra
8338    /// candidate through is safe, urgent or not - the parked run may still
8339    /// be genuinely mid-call.
8340    #[test]
8341    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
8342        for state in [
8343            Interrupt::Parking {
8344                parked: vec!["running".to_owned()],
8345                interrupt_task: "marked".to_owned(),
8346            },
8347            Interrupt::Running {
8348                parked: vec!["running".to_owned()],
8349                interrupt_task: "marked".to_owned(),
8350            },
8351            Interrupt::Resuming {
8352                parked: vec!["running".to_owned()],
8353            },
8354        ] {
8355            let candidates = vec![
8356                interrupt_task("marked"),
8357                urgent_task("hot"),
8358                task_with_id("ordinary"),
8359            ];
8360            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8361            assert!(
8362                !allowed.iter().any(|t| t.id == "hot"),
8363                "an urgent candidate must wait out the same gate as anything \
8364                 else while the run it would run alongside has not actually \
8365                 left flight, for state {state:?}: {allowed:?}"
8366            );
8367        }
8368    }
8369
8370    /// The one case where marking a task `--urgent` and `interrupt` at once
8371    /// is not redundant: once the interrupt sequence's own guaranteed
8372    /// resume/dispatch actually admits the task, it is unaffected by also
8373    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
8374    /// never on the urgent flag.
8375    #[test]
8376    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
8377        let state = Interrupt::Resuming {
8378            parked: vec!["hot".to_owned()],
8379        };
8380        let candidates = vec![urgent_task("hot"), task()];
8381        let allowed = interrupt_gate(&state, &[], candidates);
8382        assert_eq!(
8383            allowed.iter().filter(|t| t.id == "hot").count(),
8384            1,
8385            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
8386        );
8387    }
8388
8389    #[test]
8390    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
8391        let state = Interrupt::Parking {
8392            parked: vec!["running".to_owned()],
8393            interrupt_task: "marked".to_owned(),
8394        };
8395        let other = task();
8396        let candidates = vec![interrupt_task("marked"), other.clone()];
8397        let allowed = interrupt_gate(&state, &[], candidates);
8398        assert_eq!(allowed.len(), 1);
8399        assert_eq!(allowed[0].id, "marked");
8400    }
8401
8402    #[test]
8403    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
8404        let state = Interrupt::Running {
8405            parked: vec!["running".to_owned()],
8406            interrupt_task: "marked".to_owned(),
8407        };
8408        let candidates = vec![task(), task()];
8409        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
8410        assert!(allowed.is_empty());
8411    }
8412
8413    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
8414    /// sequence began (only reachable above the default
8415    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
8416    /// never both in the same tick, which is what "exactly one resume, no
8417    /// simultaneous run" actually requires structurally rather than by
8418    /// coincidence of how many ordinary slots happen to be free.
8419    #[test]
8420    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
8421        let state = Interrupt::Resuming {
8422            parked: vec!["a".to_owned(), "c".to_owned()],
8423        };
8424        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
8425        let allowed = interrupt_gate(&state, &[], candidates);
8426        assert_eq!(
8427            allowed.len(),
8428            1,
8429            "at most one candidate may be offered while resuming: {allowed:?}"
8430        );
8431        assert_eq!(allowed[0].id, "a");
8432    }
8433
8434    #[test]
8435    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
8436        let state = Interrupt::Resuming {
8437            parked: vec!["a".to_owned()],
8438        };
8439        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
8440        assert!(allowed.is_empty());
8441    }
8442
8443    /// The invariant the completion criteria ask for by name: across a whole
8444    /// simulated sequence, there is never a tick where the gate would let
8445    /// through both the parked run's resume and the interrupt task, and
8446    /// exactly one candidate resumes the instant the interrupt task's run
8447    /// ends - never zero, never more than one.
8448    #[test]
8449    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8450        let running = task(); // id: whatever `Task::new` minted
8451        let marked = interrupt_task("marked");
8452
8453        let mut state = Interrupt::Idle;
8454        // Tick 1: `running` is in flight, `marked` becomes runnable.
8455        let in_flight = vec![running.id.clone()];
8456        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8457        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8458        assert!(gated.is_empty(), "still waiting on `running` to park");
8459
8460        // Tick 2: `running` parked and left flight; nothing dispatched yet.
8461        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8462        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8463        assert_eq!(
8464            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8465            vec!["marked"],
8466            "only the interrupt task may be offered to the dispatcher now"
8467        );
8468
8469        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
8470        state = advance_interrupt_tick(
8471            true,
8472            state,
8473            &["marked".to_owned()],
8474            std::slice::from_ref(&running),
8475        );
8476        let gated = interrupt_gate(
8477            &state,
8478            &["marked".to_owned()],
8479            vec![marked.clone(), running.clone()],
8480        );
8481        assert!(
8482            gated.is_empty(),
8483            "the parked run must not be offered back while the interrupt \
8484             task is still running"
8485        );
8486
8487        // Tick 4: `marked`'s run reached a terminal status and left flight.
8488        // A higher-priority ordinary task `other` is also runnable now - it
8489        // must not be let through instead of, or alongside, `running`.
8490        let other = task_with_id("other");
8491        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8492        assert_eq!(
8493            state,
8494            Interrupt::Resuming {
8495                parked: vec![running.id.clone()]
8496            }
8497        );
8498        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8499        assert_eq!(
8500            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8501            vec![running.id.as_str()],
8502            "exactly the parked run resumes - not the unrelated task, even \
8503             though it was offered first"
8504        );
8505
8506        // Tick 5: `running` is now in flight (dispatched from tick 4's
8507        // gate). Only now does the sequence end and ordinary dispatch fully
8508        // resume.
8509        state = advance_interrupt_tick(
8510            true,
8511            state,
8512            std::slice::from_ref(&running.id),
8513            std::slice::from_ref(&other),
8514        );
8515        assert_eq!(state, Interrupt::Idle);
8516        let gated = interrupt_gate(
8517            &state,
8518            std::slice::from_ref(&running.id),
8519            vec![other.clone()],
8520        );
8521        assert_eq!(
8522            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8523            vec![other.id.as_str()],
8524            "ordinary dispatch is unrestricted again"
8525        );
8526    }
8527
8528    #[test]
8529    fn every_run_status_settles_the_task_it_came_from() {
8530        // run status, resulting task status, attempts still standing after one
8531        let table = [
8532            (RunStatus::Merged, TaskStatus::Done, 1),
8533            (RunStatus::Ready, TaskStatus::Done, 1),
8534            (RunStatus::Stalled, TaskStatus::Failed, 0),
8535            (RunStatus::Blocked, TaskStatus::Failed, 1),
8536            (RunStatus::Failed, TaskStatus::Failed, 1),
8537            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8538            (RunStatus::Prep, TaskStatus::Failed, 1),
8539            (RunStatus::Implementing, TaskStatus::Failed, 1),
8540            (RunStatus::Judging, TaskStatus::Failed, 1),
8541            (RunStatus::Deliberating, TaskStatus::Failed, 1),
8542            (RunStatus::Voting, TaskStatus::Failed, 1),
8543            (RunStatus::Reviewing, TaskStatus::Failed, 1),
8544            (RunStatus::Gating, TaskStatus::Failed, 1),
8545        ];
8546        for (run, want, attempts) in table {
8547            let mut t = task();
8548            t.start("20260902-000000-aaaa".to_owned());
8549            settle(
8550                &mut t,
8551                Verdict {
8552                    status: run,
8553                    left_pr: false,
8554                    parked: false,
8555                    quota_hit: matches!(run, RunStatus::Stalled),
8556                    no_viable_candidates: false,
8557                },
8558                "why",
8559                2,
8560            );
8561            assert_eq!(t.status, want, "task status after {}", label(run));
8562            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8563        }
8564    }
8565
8566    #[test]
8567    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8568        let mut stalled = task();
8569        stalled.start("20260902-000000-aaaa".to_owned());
8570        settle(
8571            &mut stalled,
8572            Verdict {
8573                status: RunStatus::Stalled,
8574                left_pr: false,
8575                parked: false,
8576                quota_hit: true,
8577                no_viable_candidates: false,
8578            },
8579            "quota",
8580            1,
8581        );
8582        assert_eq!(stalled.attempts, 0);
8583        assert!(
8584            stalled.status.runnable(),
8585            "a machine problem must leave the task in line"
8586        );
8587
8588        let mut blocked = task();
8589        blocked.start("20260902-000000-aaaa".to_owned());
8590        settle(
8591            &mut blocked,
8592            Verdict {
8593                status: RunStatus::Blocked,
8594                left_pr: false,
8595                parked: false,
8596                quota_hit: false,
8597                no_viable_candidates: false,
8598            },
8599            "findings open",
8600            1,
8601        );
8602        assert_eq!(blocked.attempts, 1);
8603        assert_eq!(
8604            blocked.status,
8605            TaskStatus::Held,
8606            "the last attempt hands the task to a human"
8607        );
8608    }
8609
8610    #[test]
8611    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8612        // Attempts to spare: without the pull request this task would go
8613        // straight back in line and run the whole competition again.
8614        let mut delivered = task();
8615        delivered.start("20260903-080619-01c2".to_owned());
8616        settle(
8617            &mut delivered,
8618            Verdict {
8619                status: RunStatus::Blocked,
8620                left_pr: true,
8621                parked: false,
8622                quota_hit: false,
8623                no_viable_candidates: false,
8624            },
8625            "no check status",
8626            4,
8627        );
8628        assert_eq!(
8629            delivered.status,
8630            TaskStatus::Held,
8631            "a pull request waiting on CI or a person is not a retryable failure"
8632        );
8633        assert!(
8634            !delivered.status.runnable(),
8635            "the loop must not pick this task up again"
8636        );
8637        assert_eq!(
8638            delivered.last_error.as_deref(),
8639            Some("no check status"),
8640            "the operator needs to be told what the gate was waiting for"
8641        );
8642
8643        // The same status without a pull request is a plain failure, and with
8644        // attempts left it is retried.
8645        let mut empty_handed = task();
8646        empty_handed.start("20260903-080619-01c2".to_owned());
8647        settle(
8648            &mut empty_handed,
8649            Verdict {
8650                status: RunStatus::Blocked,
8651                left_pr: false,
8652                parked: false,
8653                quota_hit: false,
8654                no_viable_candidates: false,
8655            },
8656            "findings open",
8657            4,
8658        );
8659        assert_eq!(empty_handed.status, TaskStatus::Failed);
8660        assert!(empty_handed.status.runnable());
8661    }
8662
8663    #[test]
8664    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8665        // Every candidate agreed, with evidence, that nothing belonged in the
8666        // worktree. That is not a confirmed success to close automatically -
8667        // a human still has to check the claim - and it is not an ordinary
8668        // failure either, so this settles exactly like a pull request nobody
8669        // merged yet: `Held`, same as `Blocked` with a PR.
8670        let mut noop = task();
8671        noop.start("20260912-131304-391f".to_owned());
8672        settle(
8673            &mut noop,
8674            Verdict {
8675                status: RunStatus::VerifiedNoop,
8676                left_pr: false,
8677                parked: false,
8678                quota_hit: false,
8679                no_viable_candidates: true,
8680            },
8681            "candidate A: already fixed by b32cfc4, on main",
8682            4,
8683        );
8684        assert_eq!(
8685            noop.status,
8686            TaskStatus::Held,
8687            "an unverified claim is a request for a human, not a failure"
8688        );
8689        assert!(
8690            !noop.status.runnable(),
8691            "the loop must not requeue this on the same unverified claim"
8692        );
8693        // `Task::release` resets attempts to zero the moment a human looks at
8694        // the evidence and lets it run again, so it does not matter here
8695        // whether the one attempt already spent stays spent - what matters is
8696        // that nothing retries this task unattended in the meantime.
8697        assert_eq!(noop.attempts, 1);
8698    }
8699
8700    #[test]
8701    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8702        // Parking is the operator asking for the process back - to replace the
8703        // binary, most of all. The run's work is intact on disk, so this is
8704        // not a failed attempt, and charging for it would mean a few upgrades
8705        // could exhaust a budget meant for agents that misbehaved.
8706        let mut parked = task();
8707        parked.start("20260903-183634-2d98".to_owned());
8708        settle(
8709            &mut parked,
8710            Verdict {
8711                status: RunStatus::Implementing,
8712                left_pr: false,
8713                quota_hit: false,
8714                parked: true,
8715                no_viable_candidates: false,
8716            },
8717            "parked after `implementing`",
8718            2,
8719        );
8720        assert_eq!(parked.attempts, 0, "a park is refunded");
8721        assert!(
8722            parked.status.runnable(),
8723            "and the task stays in line so the next loop resumes its run"
8724        );
8725        assert_eq!(parked.status, TaskStatus::Parked);
8726        assert_eq!(
8727            parked.park_reason.as_deref(),
8728            Some("parked after `implementing`"),
8729            "the card says where it stopped"
8730        );
8731        assert_eq!(parked.last_error, None, "nothing failed");
8732
8733        // Without the park flag the same non-terminal status is what it always
8734        // was: `execute` returning mid-flight, which is a bug and spends an
8735        // attempt so a task cannot loop on it forever.
8736        let mut broken = task();
8737        broken.start("20260903-183634-2d98".to_owned());
8738        settle(
8739            &mut broken,
8740            Verdict {
8741                status: RunStatus::Implementing,
8742                left_pr: false,
8743                quota_hit: false,
8744                parked: false,
8745                no_viable_candidates: false,
8746            },
8747            "returned mid-flight",
8748            2,
8749        );
8750        assert_eq!(broken.attempts, 1);
8751    }
8752
8753    #[test]
8754    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
8755        // Run e633: quorum lost because two judges answered with the wrong
8756        // JSON shape, `quota: []`. Refunding that takes the bound off the
8757        // retry loop, and each retry pays for a fresh hour-long implement
8758        // wave before it can fail the same way.
8759        let mut flaky = task();
8760        flaky.start("20260903-123023-e633".to_owned());
8761        settle(
8762            &mut flaky,
8763            Verdict {
8764                status: RunStatus::Stalled,
8765                left_pr: false,
8766                parked: false,
8767                quota_hit: false,
8768                no_viable_candidates: false,
8769            },
8770            "verdict rests on 1 of 3 judges",
8771            2,
8772        );
8773        assert_eq!(
8774            flaky.attempts, 1,
8775            "flakiness spends an attempt, so `max_attempts` still bounds it"
8776        );
8777        assert!(flaky.status.runnable(), "and it is still worth retrying");
8778
8779        // The same status, lost to a rate limit, is the machine's fault.
8780        let mut limited = task();
8781        limited.start("20260903-123023-e633".to_owned());
8782        settle(
8783            &mut limited,
8784            Verdict {
8785                status: RunStatus::Stalled,
8786                left_pr: false,
8787                parked: false,
8788                quota_hit: true,
8789                no_viable_candidates: false,
8790            },
8791            "judge-2, judge-3 out of quota",
8792            2,
8793        );
8794        assert_eq!(limited.attempts, 0, "a quota window is refunded");
8795        assert!(limited.status.runnable());
8796
8797        // And the bound really binds: a task that keeps stalling on flakiness
8798        // reaches a human instead of running the roster forever.
8799        let mut worn = task();
8800        for _ in 0..2 {
8801            worn.release();
8802        }
8803        worn.start("20260903-123023-e633".to_owned());
8804        worn.attempts = 2;
8805        settle(
8806            &mut worn,
8807            Verdict {
8808                status: RunStatus::Stalled,
8809                left_pr: false,
8810                parked: false,
8811                quota_hit: false,
8812                no_viable_candidates: false,
8813            },
8814            "no quorum again",
8815            2,
8816        );
8817        assert_eq!(worn.status, TaskStatus::Held);
8818        assert!(!worn.status.runnable());
8819    }
8820
8821    #[test]
8822    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8823        // The implement wave loses every seat to the same rate limit and
8824        // `after_implement` bails with nothing viable, which surfaces as
8825        // `Failed` rather than `Stalled`. That is the same machine fact the
8826        // `Stalled`-quota row already refunds, and must be refunded the same
8827        // way, or a quota outage quietly holds every task it touches instead
8828        // of leaving them in line for the reset.
8829        let mut wiped_out = task();
8830        wiped_out.start("20260907-025000-a1b2".to_owned());
8831        settle(
8832            &mut wiped_out,
8833            Verdict {
8834                status: RunStatus::Failed,
8835                left_pr: false,
8836                parked: false,
8837                quota_hit: true,
8838                no_viable_candidates: true,
8839            },
8840            "no candidate produced a change; nothing to judge",
8841            2,
8842        );
8843        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8844        assert!(
8845            wiped_out.status.runnable(),
8846            "a machine problem must leave the task in line"
8847        );
8848
8849        // This is the exemption that must stay narrow: a candidate that did
8850        // produce a change, and then failed for some other reason, still
8851        // spends the attempt even though a seat elsewhere hit its quota.
8852        // Otherwise every ordinary failure that happens to share a run with
8853        // an unrelated rate limit would be refunded for free.
8854        let mut partial_progress = task();
8855        partial_progress.start("20260907-025500-c3d4".to_owned());
8856        settle(
8857            &mut partial_progress,
8858            Verdict {
8859                status: RunStatus::Failed,
8860                left_pr: false,
8861                parked: false,
8862                quota_hit: true,
8863                no_viable_candidates: false,
8864            },
8865            "gate failed on the winning candidate",
8866            2,
8867        );
8868        assert_eq!(
8869            partial_progress.attempts, 1,
8870            "a candidate that actually produced a change spends the attempt \
8871             even though some other seat hit its quota"
8872        );
8873        assert!(partial_progress.status.runnable());
8874    }
8875
8876    #[test]
8877    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8878        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
8879        // disk, and that construction must reach the same conclusion as the
8880        // one `attempt` builds from a live run, or a crash at exactly the
8881        // wrong moment gives a recovered task a different policy than one a
8882        // daemon finished settling itself.
8883        let mut t = task();
8884        t.start("20260907-025000-a1b2".to_owned());
8885        let mut state = run_state(RunStatus::Failed);
8886        state.quota.push(QuotaLoss {
8887            cause: crate::agent::QuotaCause::UsageLimit,
8888            agent: String::new(),
8889            seat: "cand-a".to_owned(),
8890            node: "implement".to_owned(),
8891            at: Timestamp::now(),
8892            reset: None,
8893        });
8894        assert!(
8895            state.viable().is_empty(),
8896            "no candidate was added, so nothing is viable"
8897        );
8898        reclaim(&mut t, Some(state), 2, "en");
8899        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8900        assert!(t.status.runnable());
8901    }
8902
8903    #[test]
8904    fn a_held_task_is_never_offered_to_the_loop() {
8905        let dir = tempfile::tempdir().unwrap();
8906        let queue = Queue::at(dir.path().to_path_buf());
8907        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8908            let mut t = task();
8909            t.id = format!("2026090{n}-000000-000{n}");
8910            t.priority = priority;
8911            queue.put(&mut t).unwrap();
8912        }
8913        let mut held = task();
8914        held.id = "20260909-000000-9999".to_owned();
8915        held.priority = 99;
8916        held.hold_machine(None);
8917        queue.put(&mut held).unwrap();
8918
8919        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8920        assert_eq!(order.len(), 3);
8921        assert!(!order.contains(&held.id));
8922        assert_eq!(
8923            order.first().cloned(),
8924            queue.next_runnable().map(|t| t.id),
8925            "the loop's first candidate is exactly what the queue offers"
8926        );
8927        assert_eq!(
8928            order,
8929            vec![
8930                "20260902-000000-0002".to_owned(),
8931                "20260903-000000-0003".to_owned(),
8932                "20260901-000000-0001".to_owned(),
8933            ],
8934            "priority first, then oldest, so nothing starves"
8935        );
8936    }
8937
8938    #[test]
8939    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8940        let dir = tempfile::tempdir().unwrap();
8941        let queue = Queue::at(dir.path().to_path_buf());
8942        let mut old = task();
8943        old.id = "20260101-000000-old0".to_owned();
8944        queue.put(&mut old).unwrap();
8945        let mut fresh = task();
8946        fresh.id = "20260101-000000-new0".to_owned();
8947        queue.put(&mut fresh).unwrap();
8948
8949        // No parseable pid at all, so age is the only signal there is to
8950        // check - unlike a real `Queue::claim`, which always names a real,
8951        // and therefore alive, pid this test cannot fake as dead.
8952        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8953        std::thread::sleep(Duration::from_millis(60));
8954        let live = queue.claim(&fresh.id).unwrap();
8955
8956        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8957        assert_eq!(swept, vec![old.id.clone()]);
8958        assert!(
8959            queue.claim(&old.id).is_ok(),
8960            "an unparseable lock older than the threshold is swept"
8961        );
8962        assert!(
8963            queue.claim(&fresh.id).is_err(),
8964            "a live pid protects its lock regardless of age"
8965        );
8966        drop(live);
8967    }
8968
8969    #[test]
8970    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8971        // A live worker's claim remains authoritative even beyond the sweep's
8972        // age limit. Sweeping it would permit a second competing attempt.
8973        let dir = tempfile::tempdir().unwrap();
8974        let queue = Queue::at(dir.path().to_path_buf());
8975        let mut t = task();
8976        t.id = "20260101-000000-live".to_owned();
8977        queue.put(&mut t).unwrap();
8978
8979        let claim = queue.claim(&t.id).unwrap();
8980        std::thread::sleep(Duration::from_millis(60));
8981
8982        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8983        assert!(
8984            swept.is_empty(),
8985            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8986        );
8987        assert!(
8988            queue.claim(&t.id).is_err(),
8989            "the lock still protects its task"
8990        );
8991        drop(claim);
8992    }
8993
8994    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8995    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8996    fn injected_dead_pid() -> u32 {
8997        std::process::id().checked_add(1).unwrap_or(1)
8998    }
8999
9000    #[test]
9001    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
9002        let dir = tempfile::tempdir().unwrap();
9003        let queue = Queue::at(dir.path().to_path_buf());
9004        let mut t = task();
9005        t.id = "20260101-000000-dead".to_owned();
9006        queue.put(&mut t).unwrap();
9007        let dead_pid = injected_dead_pid();
9008
9009        // Written directly rather than through `Queue::claim`, which would
9010        // stamp this test process's own very much alive pid and defeat the
9011        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
9012        // like moments after it died, not six hours later.
9013        std::fs::write(
9014            dir.path().join(format!("{}.lock", t.id)),
9015            dead_pid.to_string(),
9016        )
9017        .unwrap();
9018
9019        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9020            pid != dead_pid
9021        });
9022        assert_eq!(
9023            swept,
9024            vec![t.id.clone()],
9025            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
9026        );
9027        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
9028    }
9029
9030    #[test]
9031    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
9032        let dir = tempfile::tempdir().unwrap();
9033        let queue = Queue::at(dir.path().to_path_buf());
9034        let mut t = task();
9035        t.id = "20260101-000000-late".to_owned();
9036        queue.put(&mut t).unwrap();
9037        let dead_pid = injected_dead_pid();
9038
9039        // Tick one, standing in for the sweep `poll` already runs at
9040        // startup: nothing to find yet.
9041        assert!(
9042            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
9043            "nothing has claimed the task yet"
9044        );
9045
9046        // A second daemon claims the task and dies before it ever writes
9047        // `running`, well after this loop's own startup sweep already ran.
9048        std::fs::write(
9049            dir.path().join(format!("{}.lock", t.id)),
9050            dead_pid.to_string(),
9051        )
9052        .unwrap();
9053
9054        // Tick two, standing in for a poll long into this daemon's uptime:
9055        // the same function, called again, notices what only just appeared -
9056        // proving the sweep is not a one-shot startup check.
9057        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9058            pid != dead_pid
9059        });
9060        assert_eq!(swept, vec![t.id.clone()]);
9061    }
9062
9063    #[test]
9064    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
9065        // `reclaim_orphaned_running` looks up the task's last run, which
9066        // touches `run::home()`; the first call anywhere in this binary wins,
9067        // so this is a no-op if another test already pinned one, and either
9068        // way the run id below is never written under it.
9069        crate::run::pin_test_home();
9070        let dir = tempfile::tempdir().unwrap();
9071        let queue = Queue::at(dir.path().to_path_buf());
9072        let mut t = task();
9073        t.id = "20260101-000000-crsh".to_owned();
9074        t.status = TaskStatus::Running;
9075        t.attempts = 1;
9076        // No `run.json` behind this id: standing in for a run this test does
9077        // not need to make readable, since the point is the lock, not the
9078        // recovery table `reclaim` already has its own tests for.
9079        t.runs.push("20260904-000000-4043".to_owned());
9080        queue.put(&mut t).unwrap();
9081        let dead_pid = injected_dead_pid();
9082
9083        // The crashed daemon's own claim, naming a pid nothing on the
9084        // machine holds anymore.
9085        std::fs::write(
9086            dir.path().join(format!("{}.lock", t.id)),
9087            dead_pid.to_string(),
9088        )
9089        .unwrap();
9090
9091        // Before the lock is swept the task looks claimed, and
9092        // `reclaim_orphaned_running` must leave it alone - this is exactly
9093        // the bug: a `running` task stranded behind a dead daemon's lock,
9094        // invisible to the claim-as-proof check because the lock outlived
9095        // the process that wrote it.
9096        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
9097        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9098
9099        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9100            pid != dead_pid
9101        });
9102        assert_eq!(swept, vec![t.id.clone()]);
9103
9104        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9105        assert_eq!(reclaimed, vec![t.id.clone()]);
9106        let after = queue.get(&t.id).unwrap();
9107        assert_eq!(
9108            after.status,
9109            TaskStatus::Held,
9110            "no run.json to recover from, so a human is asked"
9111        );
9112        assert_eq!(
9113            after.runs,
9114            vec!["20260904-000000-4043".to_owned()],
9115            "the crashed run's id is kept as evidence, not discarded"
9116        );
9117    }
9118
9119    #[test]
9120    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
9121        let dir = tempfile::tempdir().unwrap();
9122        let queue = Queue::at(dir.path().to_path_buf());
9123        let mut t = task();
9124        t.id = "20260101-000000-unknown".to_owned();
9125        queue.put(&mut t).unwrap();
9126        let dead_pid = injected_dead_pid();
9127        std::fs::write(
9128            dir.path().join(format!("{}.lock", t.id)),
9129            dead_pid.to_string(),
9130        )
9131        .unwrap();
9132
9133        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
9134        assert!(swept.is_empty(), "an unknown pid must keep its lock");
9135        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
9136    }
9137
9138    fn run_state_in(status: RunStatus, language: &str) -> RunState {
9139        let mut s = run_state(status);
9140        s.config.graph.language = language.to_owned();
9141        s
9142    }
9143
9144    fn unstarted_verdict(status: RunStatus) -> Verdict {
9145        Verdict {
9146            status,
9147            left_pr: false,
9148            quota_hit: false,
9149            parked: false,
9150            no_viable_candidates: false,
9151        }
9152    }
9153
9154    #[test]
9155    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
9156        let mut t = task();
9157        t.attempts = 1;
9158        settle_in(
9159            &mut t,
9160            unstarted_verdict(RunStatus::AlreadyInBase),
9161            "already in main",
9162            1,
9163            phrases("en"),
9164        );
9165        assert_eq!(t.status, TaskStatus::Done);
9166        assert_eq!(t.attempts, 0);
9167    }
9168
9169    #[test]
9170    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
9171        let reason = |language: &str| {
9172            let mut t = task();
9173            settle_in(
9174                &mut t,
9175                unstarted_verdict(RunStatus::Judging),
9176                "boom",
9177                1,
9178                phrases(language),
9179            );
9180            t.last_error.or(t.hold_reason).unwrap_or_default()
9181        };
9182        assert!(
9183            reason("en").starts_with("the graph stopped at `"),
9184            "{}",
9185            reason("en")
9186        );
9187        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
9188        assert!(reason("日本語").contains("boom"));
9189        assert_eq!(reason("fr"), reason("en"));
9190    }
9191
9192    #[test]
9193    fn describe_follows_the_run_language_and_keeps_the_run_id() {
9194        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
9195        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
9196        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
9197        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
9198        assert!(ja.contains("[run "), "{ja}");
9199        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
9200        assert!(ended.starts_with("run 終了: "), "{ended}");
9201        let mut de = run_state_in(RunStatus::Failed, "de");
9202        let mut en = run_state_in(RunStatus::Failed, "en");
9203        de.id = "same".to_owned();
9204        en.id = "same".to_owned();
9205        assert_eq!(describe(&de), describe(&en));
9206    }
9207
9208    #[test]
9209    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
9210        use crate::handover::Refused;
9211        let cases = [
9212            Refused::Foreign {
9213                branch: "b".into(),
9214                path: "/w/x".into(),
9215                why: "made by hand".into(),
9216            },
9217            Refused::Unsafe {
9218                branch: "b".into(),
9219                path: "/w/x".into(),
9220                why: "its worktree has uncommitted changes (a.rs)".into(),
9221            },
9222            Refused::ReleaseFailed {
9223                branch: "b".into(),
9224                path: "/w/x".into(),
9225                run: "ab12".into(),
9226            },
9227        ];
9228        for r in &cases {
9229            let en = (phrases("en").handover_refused)(r);
9230            assert_eq!(en, r.to_string());
9231            let ja = (phrases("ja").handover_refused)(r);
9232            assert!(
9233                !ja.contains("is checked out") && !ja.contains("try again"),
9234                "{ja}"
9235            );
9236            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
9237            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
9238                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
9239            }
9240        }
9241        assert!(phrases("en").handover_hint.contains("release the task"));
9242        assert!(phrases("ja").handover_hint.contains("解放"));
9243    }
9244
9245    #[test]
9246    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
9247        let build = |lang: &str| {
9248            let mut s = run_state_in(RunStatus::Blocked, lang);
9249            s.id = "same".to_owned();
9250            s.config.graph.review_rounds = 3;
9251            let mut r = review_round(3);
9252            r.expected = 3;
9253            r.answered = 1;
9254            s.reviews.push(r);
9255            s.event(
9256                "review",
9257                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
9258            );
9259            s
9260        };
9261        let en = describe(&build("en"));
9262        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
9263        let ja = describe(&build("ja"));
9264        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
9265        assert!(!ja.contains("never answered"), "{ja}");
9266        assert!(ja.contains("[run "), "{ja}");
9267
9268        // An incomplete panel whose verification failed is a different stop:
9269        // the real event must survive in ja too.
9270        let mut failed = build("ja");
9271        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
9272            command: "cargo test".to_owned(),
9273            code: Some(1),
9274            output_tail: String::new(),
9275            duration_ms: 0,
9276            resource_blocked: false,
9277        });
9278        failed.event("review", "stopped; e2e failed: cargo test");
9279        let ja = describe(&failed);
9280        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
9281        assert!(!ja.contains("席のレビュアー"), "{ja}");
9282    }
9283
9284    #[test]
9285    fn refusals_and_recovery_prose_follow_the_language() {
9286        let home = crate::run::test_home();
9287        let t = held_task_with("r1");
9288        let q = action_question(
9289            "r1",
9290            ask::ChoiceAction::Resume {
9291                run: "r1".to_owned(),
9292            },
9293        );
9294        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
9295            ActionDecision::Refuse(s) => s,
9296            other => panic!("{other:?}"),
9297        };
9298        assert!(refuse(phrases("en")).contains("could not be read: gone"));
9299        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
9300        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
9301
9302        let mut held = task();
9303        reclaim(&mut held, None, 2, "ja");
9304        assert!(held.hold_reason.unwrap().contains("保留にしました"));
9305        let mut held = task();
9306        reclaim(&mut held, None, 2, "xx");
9307        assert!(held.hold_reason.unwrap().contains("held for a human"));
9308    }
9309
9310    fn run_state(status: RunStatus) -> RunState {
9311        let mut state = RunState::new(
9312            PathBuf::from("/repo"),
9313            "main".to_owned(),
9314            "abc1234def".to_owned(),
9315            "add retries".to_owned(),
9316            Config::default(),
9317        );
9318        state.status = status;
9319        state
9320    }
9321
9322    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
9323        Candidate {
9324            index: 0,
9325            label,
9326            agent: "claude".to_owned(),
9327            branch: format!("magi/x/{label}"),
9328            worktree: PathBuf::from("/repo"),
9329            summary: summary.to_owned(),
9330            stat: String::new(),
9331            files: 0,
9332            commits: usize::from(!empty),
9333            empty,
9334            failed: failed.map(str::to_owned),
9335            verified_noop: None,
9336            duration_ms: 0,
9337            folded: false,
9338        }
9339    }
9340
9341    #[test]
9342    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
9343        let mut state = run_state(RunStatus::Blocked);
9344        state.gate = vec![
9345            CommandOutcome {
9346                command: "cargo make check".to_owned(),
9347                code: Some(0),
9348                output_tail: "ok".to_owned(),
9349                duration_ms: 0,
9350                resource_blocked: false,
9351            },
9352            CommandOutcome {
9353                command: "cargo test".to_owned(),
9354                code: Some(101),
9355                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
9356                duration_ms: 0,
9357                resource_blocked: false,
9358            },
9359        ];
9360        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
9361        assert!(d.contains("cargo test"), "{d}");
9362        assert!(
9363            !d.contains("cargo make check"),
9364            "a passing check is not a diagnostic: {d}"
9365        );
9366        assert!(d.contains("assertion failed"), "{d}");
9367    }
9368
9369    #[test]
9370    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
9371        let mut state = run_state(RunStatus::Blocked);
9372        state.event(
9373            "land",
9374            "stopped: the fixer produced no commit while 2 check(s) were failing \
9375             (build, lint); stopping instead of looping on an unchanged tree",
9376        );
9377        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
9378        assert!(d.contains("build"), "{d}");
9379        assert!(d.contains("lint"), "{d}");
9380        assert!(d.contains("fixer produced no commit"), "{d}");
9381    }
9382
9383    #[test]
9384    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
9385        // `describe`'s output becomes `Task::last_error` verbatim, and the
9386        // phone renders that in the same alarm-styled box an ordinary
9387        // failure gets. A bare `verified_noop` there would read exactly like
9388        // the failure this status exists to be told apart from.
9389        let state = run_state(RunStatus::VerifiedNoop);
9390        let d = describe(&state);
9391        assert!(
9392            d.contains("agent-verified no-op"),
9393            "expected the display label, not the wire spelling: {d}"
9394        );
9395        assert!(!d.contains("verified_noop"), "{d}");
9396    }
9397
9398    #[test]
9399    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
9400        let mut state = run_state(RunStatus::Failed);
9401        state.gate.push(crate::run::CommandOutcome {
9402            command: "cargo test".into(),
9403            code: Some(101),
9404            output_tail: format!(
9405                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
9406                "  41: 0x1234 - backtrace frame\n".repeat(10000)
9407            ),
9408            duration_ms: 1,
9409            resource_blocked: false,
9410        });
9411        let d = diagnostic(&state).unwrap();
9412        assert!(d.contains("panicked at widget.rs:12"), "{d}");
9413        assert!(d.contains("assertion failed: widget missing"));
9414        assert!(d.contains("widget log"));
9415    }
9416
9417    #[test]
9418    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
9419        // The whole point of the feature: a run held as "no candidate produced
9420        // a change" can mean the implementer actually finished the task and
9421        // only left a clean local tree behind - see AGENTS.md on this exact
9422        // failure mode. The diagnostic has to carry what the agent actually
9423        // said, not just the fact that nothing was there to judge.
9424        let mut state = run_state(RunStatus::Failed);
9425        state.candidates = vec![candidate(
9426            'A',
9427            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
9428            true,
9429            None,
9430        )];
9431        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
9432        assert!(d.contains("candidate A"), "{d}");
9433        assert!(d.contains("tagged v1.2.3"), "{d}");
9434    }
9435
9436    #[test]
9437    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
9438        let mut state = run_state(RunStatus::Failed);
9439        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
9440        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
9441        assert!(d.contains("candidate A"), "{d}");
9442        assert!(d.contains("agent timed out"), "{d}");
9443    }
9444
9445    #[test]
9446    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9447        // A viable candidate existed, the gate never ran, and nothing land
9448        // said matches - `Task::last_error` is left to explain this one alone.
9449        let mut state = run_state(RunStatus::Failed);
9450        state.candidates = vec![candidate('A', "did the work", false, None)];
9451        assert!(diagnostic(&state).is_none());
9452    }
9453
9454    #[test]
9455    fn diagnostic_is_bounded_however_much_a_run_printed() {
9456        let mut state = run_state(RunStatus::Blocked);
9457        state.gate = vec![
9458            CommandOutcome {
9459                command: "cargo test".to_owned(),
9460                code: Some(101),
9461                output_tail: "x".repeat(50_000),
9462                duration_ms: 0,
9463                resource_blocked: false,
9464            },
9465            CommandOutcome {
9466                command: "cargo clippy".to_owned(),
9467                code: Some(1),
9468                output_tail: "y".repeat(50_000),
9469                duration_ms: 0,
9470                resource_blocked: false,
9471            },
9472        ];
9473        state.candidates = vec![
9474            candidate('A', &"z".repeat(50_000), true, None),
9475            candidate('B', &"w".repeat(50_000), true, None),
9476        ];
9477        let d = diagnostic(&state).expect("plenty here to diagnose");
9478        assert!(
9479            d.len() <= DIAGNOSTIC_MAX,
9480            "diagnostic grew to {} bytes, unbounded",
9481            d.len()
9482        );
9483    }
9484
9485    #[test]
9486    fn selected_delivery_guards_survive_recovery_failure_accounting() {
9487        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9488            let mut t = task();
9489            let mut state = run_state(status);
9490            t.pr_recovery = Some(crate::pr_recovery::Selection {
9491                url: "url".into(),
9492                branch: format!("magi/task-{}", t.id),
9493                head: "a".repeat(40),
9494                source_head: None,
9495                source_run: None,
9496                source_proof: None,
9497                disposition: Some(crate::pr_recovery::Disposition::Land),
9498                instruction: t.instruction.clone(),
9499                approved_at: Timestamp::now(),
9500            });
9501            state.pr_recovery = t.pr_recovery.clone();
9502            t.start(state.id.clone());
9503            settle_and_diagnose(
9504                &mut t,
9505                Verdict {
9506                    status,
9507                    left_pr: false,
9508                    quota_hit: false,
9509                    parked: false,
9510                    no_viable_candidates: false,
9511                },
9512                "delivery stopped",
9513                5,
9514                &state,
9515            );
9516            assert_eq!(t.status, TaskStatus::Held);
9517            let reason = t.hold_reason.as_deref().unwrap();
9518            if status == RunStatus::Ready {
9519                assert!(reason.contains("Selected PR delivery is incomplete"));
9520                assert!(t.recovery_budget.is_none());
9521            } else {
9522                assert!(reason.contains("Selected recovery stopped"));
9523                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9524            }
9525            assert!(t.pr_recovery.is_some());
9526        }
9527    }
9528
9529    #[test]
9530    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9531        let mut state = run_state(RunStatus::Voting);
9532        state.base_sync = Some(crate::run::BaseSync {
9533            tip: "base-tip".into(),
9534            behind: 3,
9535            attempts: 4,
9536            conflict: Some("base stopped".into()),
9537            already_in: None,
9538        });
9539        state.record_base_sync_stop("candidate-head");
9540        let mut t = task();
9541        t.start(state.id.clone());
9542        let verdict = Verdict {
9543            status: RunStatus::Blocked,
9544            left_pr: false,
9545            quota_hit: false,
9546            parked: false,
9547            no_viable_candidates: false,
9548        };
9549        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9550        assert_eq!(
9551            t.status,
9552            TaskStatus::Held,
9553            "unspent task attempts cannot start another competition"
9554        );
9555        let at = t.held_at;
9556        let cause = t.hold_notice_cause.clone();
9557        state.begin_pass();
9558        t.release_operator("test-resume", None);
9559        t.start(state.id.clone());
9560        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9561        assert_eq!(t.status, TaskStatus::Held);
9562        assert_eq!(t.held_at, at);
9563        assert_eq!(t.hold_notice_cause, cause);
9564    }
9565
9566    #[test]
9567    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9568        let mut state = run_state(RunStatus::Blocked);
9569        state.gate = vec![CommandOutcome {
9570            command: "cargo test".to_owned(),
9571            code: Some(101),
9572            output_tail: "assertion failed".to_owned(),
9573            duration_ms: 0,
9574            resource_blocked: false,
9575        }];
9576        let verdict = Verdict {
9577            status: RunStatus::Blocked,
9578            left_pr: false,
9579            quota_hit: false,
9580            parked: false,
9581            no_viable_candidates: false,
9582        };
9583
9584        // Attempt one of two still has a retry coming: no diagnostic yet, the
9585        // task is going to run again and this run's evidence would go stale.
9586        let mut t = task();
9587        t.start("run-1".to_owned());
9588        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9589        assert_eq!(t.status, TaskStatus::Failed);
9590        assert!(t.diagnostic.is_none());
9591
9592        // Attempt two exhausts the budget: now it is held, and the
9593        // diagnostic is what `magi task show` has to say more than one line.
9594        t.start("run-2".to_owned());
9595        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9596        assert_eq!(t.status, TaskStatus::Held);
9597        let d = t.diagnostic.expect("a held task must carry its diagnostic");
9598        assert!(d.contains("cargo test"), "{d}");
9599    }
9600
9601    #[test]
9602    fn a_held_task_names_the_open_question_it_is_waiting_on() {
9603        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
9604        // `magi ask` question settled Held with `hold_reason: null`, so the
9605        // notification said nothing actionable. `note_open_question` should
9606        // append the question id to whatever `handed_off` already wrote.
9607        crate::run::pin_test_home();
9608        let home = crate::run::home();
9609        let state = run_state(RunStatus::VerifiedNoop);
9610        let mut q = ask::Question::new(
9611            state.id.clone(),
9612            "implement".to_owned(),
9613            "impl-A".to_owned(),
9614            "is this really a no-op?".to_owned(),
9615            String::new(),
9616            Vec::new(),
9617        );
9618        Questions::at(home.join("questions")).put(&mut q).unwrap();
9619
9620        let verdict = Verdict {
9621            status: RunStatus::VerifiedNoop,
9622            left_pr: false,
9623            quota_hit: false,
9624            parked: false,
9625            no_viable_candidates: false,
9626        };
9627        let mut t = task();
9628        t.start(state.id.clone());
9629        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9630
9631        assert_eq!(t.status, TaskStatus::Held);
9632        let reason = t.hold_reason.expect("a held task must record why");
9633        assert!(
9634            reason.starts_with("run ended agent-verified no-op"),
9635            "the original settle reason must survive unchanged: {reason}"
9636        );
9637        assert!(
9638            reason.contains(q.short()),
9639            "the open question's id must be named so the notice is actionable: {reason}"
9640        );
9641    }
9642
9643    #[test]
9644    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9645        crate::run::pin_test_home();
9646        let state = run_state(RunStatus::VerifiedNoop);
9647
9648        let verdict = Verdict {
9649            status: RunStatus::VerifiedNoop,
9650            left_pr: false,
9651            quota_hit: false,
9652            parked: false,
9653            no_viable_candidates: false,
9654        };
9655        let mut t = task();
9656        t.start(state.id.clone());
9657        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9658
9659        assert_eq!(t.status, TaskStatus::Held);
9660        assert_eq!(
9661            t.hold_reason.as_deref(),
9662            Some("run ended agent-verified no-op"),
9663            "nothing to append when the question was already answered or never asked"
9664        );
9665    }
9666
9667    #[test]
9668    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
9669        crate::run::pin_test_home();
9670        let mut first = run_state(RunStatus::Blocked);
9671        first.id = "20260101-000000-sup1".to_owned();
9672        first.save().unwrap();
9673        let mut second = run_state(RunStatus::Merged);
9674        second.id = "20260101-000000-sup2".to_owned();
9675        second.save().unwrap();
9676
9677        let mut t = task();
9678        t.runs = vec![first.id.clone(), second.id.clone()];
9679        t.status = TaskStatus::Done;
9680
9681        supersede_prior_runs(&t, &crate::run::home());
9682
9683        assert_eq!(
9684            RunState::load(&first.id).unwrap().status,
9685            RunStatus::Superseded,
9686            "the first attempt's Blocked no longer needs anyone's attention"
9687        );
9688        assert_eq!(
9689            RunState::load(&second.id).unwrap().status,
9690            RunStatus::Merged,
9691            "the run that actually succeeded is left exactly as it was"
9692        );
9693    }
9694
9695    #[test]
9696    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
9697        // `is_working_on` alone only proves a *daemon* claim; a `magi run
9698        // --resume` invoked by hand outside the daemon never touches
9699        // `daemon.json` at all, so it would look identical to a genuinely
9700        // idle run without also consulting `RunState::liveness`, which reads
9701        // this run's own recorded `driver_pid` instead.
9702        crate::run::pin_test_home();
9703        let mut first = run_state(RunStatus::Blocked);
9704        first.id = "20260101-000000-sup9".to_owned();
9705        // This test process's own pid: guaranteed alive without needing a
9706        // real second process or daemon.
9707        first.driver_pid = Some(std::process::id());
9708        first.driver_started_at = Some(
9709            crate::proc::process_started_at(std::process::id())
9710                .expect("this test process's own start time must be queryable"),
9711        );
9712        first.save().unwrap();
9713        let mut second = run_state(RunStatus::Merged);
9714        second.id = "20260101-000000-supa".to_owned();
9715        second.save().unwrap();
9716
9717        let mut t = task();
9718        t.runs = vec![first.id.clone(), second.id.clone()];
9719        t.status = TaskStatus::Done;
9720
9721        supersede_prior_runs(&t, &crate::run::home());
9722
9723        assert_eq!(
9724            RunState::load(&first.id).unwrap().status,
9725            RunStatus::Blocked,
9726            "a live driver_pid means something is still actually working this run, \
9727             even though no daemon claims it - rewriting under it would just be \
9728             undone the next time that process saves"
9729        );
9730    }
9731
9732    #[test]
9733    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
9734        // The first resweep must skip a still-live attempt exactly like
9735        // `supersede_prior_runs` itself does; a later resweep, once that
9736        // process is no longer actually driving it, is what closes the gap
9737        // `supersede_prior_runs` alone leaves - a task only ever reaches
9738        // `Done` once, so nothing else would ever look at this run again.
9739        let dir = tempfile::tempdir().unwrap();
9740        let home = dir.path().to_path_buf();
9741        let queue = Queue::at(dir.path().join("queue"));
9742
9743        let mut first = run_state(RunStatus::Blocked);
9744        first.id = "20260101-000000-supd".to_owned();
9745        first.driver_pid = Some(std::process::id());
9746        first.driver_started_at = Some(
9747            crate::proc::process_started_at(std::process::id())
9748                .expect("this test process's own start time must be queryable"),
9749        );
9750        first.save_under(&home).unwrap();
9751        let mut second = run_state(RunStatus::Merged);
9752        second.id = "20260101-000000-supe".to_owned();
9753        second.save_under(&home).unwrap();
9754
9755        let mut t = task();
9756        t.runs = vec![first.id.clone(), second.id.clone()];
9757        t.status = TaskStatus::Done;
9758        queue.put(&mut t).unwrap();
9759
9760        resweep_superseded_attempts(&queue, &home);
9761        assert_eq!(
9762            RunState::load_under(&first.id, &home).unwrap().status,
9763            RunStatus::Blocked,
9764            "still live on the first pass, so still untouched"
9765        );
9766
9767        // Stand in for the manual process no longer being the one driving
9768        // this run: same pid (this test process really is still alive), but
9769        // an identity marker that no longer matches it - see
9770        // `RunState::liveness`'s own doc for why a mismatched
9771        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
9772        let mut stale = RunState::load_under(&first.id, &home).unwrap();
9773        stale.driver_started_at = Some("1".to_owned());
9774        stale.save_under(&home).unwrap();
9775
9776        resweep_superseded_attempts(&queue, &home);
9777        assert_eq!(
9778            RunState::load_under(&first.id, &home).unwrap().status,
9779            RunStatus::Superseded,
9780            "the second pass catches up what the first one correctly skipped"
9781        );
9782    }
9783
9784    #[test]
9785    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
9786        crate::run::pin_test_home();
9787        let mut first = run_state(RunStatus::Blocked);
9788        first.id = "20260101-000000-sup3".to_owned();
9789        first.save().unwrap();
9790        let mut second = run_state(RunStatus::Blocked);
9791        second.id = "20260101-000000-sup4".to_owned();
9792        second.save().unwrap();
9793
9794        let mut t = task();
9795        t.runs = vec![first.id.clone(), second.id.clone()];
9796        // Still retrying: nothing about this task's story is settled yet, so
9797        // neither Blocked run may be relabelled, even though a later attempt
9798        // already exists.
9799        t.status = TaskStatus::Failed;
9800
9801        supersede_prior_runs(&t, &crate::run::home());
9802
9803        assert_eq!(
9804            RunState::load(&first.id).unwrap().status,
9805            RunStatus::Blocked
9806        );
9807        assert_eq!(
9808            RunState::load(&second.id).unwrap().status,
9809            RunStatus::Blocked
9810        );
9811    }
9812
9813    #[test]
9814    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9815        // `magi task done` (or the API's equivalent) can close a task with no
9816        // run of its own ever having succeeded - there is nothing here that
9817        // counts as "the attempt that finished it", so nothing is rewritten.
9818        crate::run::pin_test_home();
9819        let mut first = run_state(RunStatus::Blocked);
9820        first.id = "20260101-000000-sup5".to_owned();
9821        first.save().unwrap();
9822
9823        let mut t = task();
9824        t.runs = vec![first.id.clone()];
9825        t.status = TaskStatus::Done;
9826
9827        supersede_prior_runs(&t, &crate::run::home());
9828
9829        assert_eq!(
9830            RunState::load(&first.id).unwrap().status,
9831            RunStatus::Blocked,
9832            "a single-attempt task has no earlier run to supersede"
9833        );
9834    }
9835
9836    #[test]
9837    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9838        // `magi task done` (or the web/conductor equivalents) can close a
9839        // task in any status, including one whose *last* recorded attempt is
9840        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
9841        // never watched, say. `runs.last()` being `Done`-adjacent is not
9842        // proof it actually succeeded, so nothing earlier may be relabelled
9843        // on its say-so alone.
9844        crate::run::pin_test_home();
9845        let mut first = run_state(RunStatus::Blocked);
9846        first.id = "20260101-000000-supb".to_owned();
9847        first.save().unwrap();
9848        let mut second = run_state(RunStatus::Failed);
9849        second.id = "20260101-000000-supc".to_owned();
9850        second.save().unwrap();
9851
9852        let mut t = task();
9853        t.runs = vec![first.id.clone(), second.id.clone()];
9854        t.status = TaskStatus::Done;
9855
9856        supersede_prior_runs(&t, &crate::run::home());
9857
9858        assert_eq!(
9859            RunState::load(&first.id).unwrap().status,
9860            RunStatus::Blocked,
9861            "the task's last attempt never landed, so there is nothing here \
9862             actually superseding it"
9863        );
9864    }
9865
9866    #[test]
9867    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9868        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
9869        // to look" - `Failed` and `VerifiedNoop` are already their own
9870        // terminal answers and must not be relabelled into a third one.
9871        crate::run::pin_test_home();
9872        let mut failed = run_state(RunStatus::Failed);
9873        failed.id = "20260101-000000-sup6".to_owned();
9874        failed.save().unwrap();
9875        let mut noop = run_state(RunStatus::VerifiedNoop);
9876        noop.id = "20260101-000000-sup7".to_owned();
9877        noop.save().unwrap();
9878        let mut winner = run_state(RunStatus::Ready);
9879        winner.id = "20260101-000000-sup8".to_owned();
9880        winner.save().unwrap();
9881
9882        let mut t = task();
9883        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9884        t.status = TaskStatus::Done;
9885
9886        supersede_prior_runs(&t, &crate::run::home());
9887
9888        assert_eq!(
9889            RunState::load(&failed.id).unwrap().status,
9890            RunStatus::Failed
9891        );
9892        assert_eq!(
9893            RunState::load(&noop.id).unwrap().status,
9894            RunStatus::VerifiedNoop
9895        );
9896    }
9897
9898    fn approval_question(run: &str) -> ask::Question {
9899        ask::Question::new(
9900            run.to_owned(),
9901            land::APPROVAL_NODE.to_owned(),
9902            "land".to_owned(),
9903            "merge?".to_owned(),
9904            String::new(),
9905            vec!["merge".to_owned(), "hold".to_owned()],
9906        )
9907    }
9908
9909    #[test]
9910    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9911        crate::run::pin_test_home();
9912        let mut state = run_state(RunStatus::Landing);
9913        state.id = "20260101-000000-fre1".to_owned();
9914        state.parked = true;
9915        state.save().unwrap();
9916        ask::Questions::open()
9917            .put(&mut approval_question(&state.id))
9918            .unwrap();
9919
9920        let mut t = task();
9921        t.runs.push(state.id.clone());
9922        assert_eq!(
9923            land_resume_state(&t),
9924            LandResume::StillWaiting,
9925            "nobody has answered and the timeout has not passed"
9926        );
9927    }
9928
9929    #[test]
9930    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9931        crate::run::pin_test_home();
9932        let mut state = run_state(RunStatus::Gating);
9933        state.id = "20260101-000000-gt01".to_owned();
9934        state.parked = true;
9935        state.config.graph.answer_timeout = 60;
9936        state.github_text = Some(crate::run::GithubTextAsk {
9937            rewrite: None,
9938            fingerprint: "f".into(),
9939            title: true,
9940            body: false,
9941            categories: vec!["title-language".into()],
9942            question: None,
9943            asks: 1,
9944            resolved: false,
9945            chosen_title: None,
9946            choice: None,
9947            publication: None,
9948        });
9949        state.save().unwrap();
9950        let store = ask::Questions::open();
9951        let mut q = ask::Question::new(
9952            state.id.clone(),
9953            crate::github_text::ASK_NODE.to_owned(),
9954            crate::github_text::ASK_SEAT.to_owned(),
9955            "s".into(),
9956            String::new(),
9957            vec!["use fallback".into()],
9958        );
9959        store.put(&mut q).unwrap();
9960        let mut t = task();
9961        t.runs.push(state.id.clone());
9962        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9963        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9964        store.put(&mut q).unwrap();
9965        assert_eq!(land_resume_state(&t), LandResume::Ready);
9966        assert!(!store.get(&q.id).unwrap().status.open());
9967        // Once decided, a parked run is an ordinary candidate again.
9968        state.github_text.as_mut().unwrap().resolved = true;
9969        state.save().unwrap();
9970        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9971    }
9972
9973    #[test]
9974    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9975        // `ask::ask_and_wait`'s own deadline used to retire a question
9976        // nobody answered; land's approval bypasses that wait (see
9977        // `land::approval_gate`), so this is now the only place
9978        // `graph.answer_timeout` is enforced for a land approval at all.
9979        crate::run::pin_test_home();
9980        let mut state = run_state(RunStatus::Landing);
9981        state.id = "20260101-000000-exp1".to_owned();
9982        state.parked = true;
9983        state.config.graph.answer_timeout = 60;
9984        state.save().unwrap();
9985
9986        let store = ask::Questions::open();
9987        let mut q = approval_question(&state.id);
9988        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9989        store.put(&mut q).unwrap();
9990
9991        let mut t = task();
9992        t.runs.push(state.id.clone());
9993        assert_eq!(
9994            land_resume_state(&t),
9995            LandResume::Ready,
9996            "an expired question must not be waited on forever"
9997        );
9998
9999        let after = store.get(&q.id).unwrap();
10000        assert!(
10001            !after.status.open(),
10002            "the question is abandoned, not silently ignored"
10003        );
10004        assert!(
10005            after.resolution().is_none(),
10006            "an abandoned question is not read as a decision"
10007        );
10008    }
10009
10010    #[test]
10011    fn reclaim_settles_a_running_task_against_its_last_run() {
10012        let mut t = task();
10013        t.start("20260904-000000-4043".to_owned());
10014        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
10015        assert_eq!(
10016            t.status,
10017            TaskStatus::Done,
10018            "a run that actually finished must not stay `running` forever"
10019        );
10020    }
10021
10022    #[test]
10023    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
10024        let dir = tempfile::tempdir().unwrap();
10025        let queue = Queue::at(dir.path().join("queue"));
10026        let mut task = task();
10027        let mut run = run_state(RunStatus::Blocked);
10028        run.reserve_under(dir.path()).unwrap();
10029        run.driver_exited = true;
10030        run.save_under(dir.path()).unwrap();
10031        queue.put(&mut task).unwrap();
10032        let stale = task.clone();
10033        task.resume_override = Some(crate::queue::OperatorResume {
10034            question_id: "pending-resume".into(),
10035            at: Timestamp::now(),
10036            conductor_rehold: None,
10037            forced: true,
10038            pinned_run: Some(run.id.clone()),
10039        });
10040        task.start(run.id.clone());
10041        queue.put(&mut task).unwrap();
10042        // Discard every in-memory handoff, as a worker death before execute does.
10043        let mut recovered = queue.get(&task.id).unwrap();
10044        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
10045        reclaim(&mut recovered, Some(disk), 2, "en");
10046        queue.put(&mut recovered).unwrap();
10047        assert!(recovered.resume_override.is_none());
10048        assert_eq!(
10049            recovered.dispatched_resumes.get("pending-resume"),
10050            Some(&run.id)
10051        );
10052        let mut stale = stale;
10053        queue.put(&mut stale).unwrap();
10054        assert_eq!(
10055            stale.dispatched_resumes, recovered.dispatched_resumes,
10056            "a stale task writer cannot erase dispatch ownership"
10057        );
10058        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
10059        assert!(resumed.decision_starts.is_empty());
10060        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
10061        assert!(
10062            resumed.decision_starts.is_empty(),
10063            "handoff is not execution proof"
10064        );
10065        resumed.begin_pass();
10066        resumed.save_under(dir.path()).unwrap();
10067        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
10068        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
10069        disk.carry_dispatched_resumes(&recovered);
10070        disk.begin_pass();
10071        assert_eq!(
10072            disk.decision_starts.get("pending-resume"),
10073            Some(&0),
10074            "later execution must preserve the original pass receipt"
10075        );
10076    }
10077
10078    #[test]
10079    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
10080        let mut t = task();
10081        t.start("20260904-000000-4043".to_owned());
10082        t.last_error = Some("earlier trouble".to_owned());
10083        let mut state = run_state(RunStatus::Judging);
10084        state.parked = true;
10085        reclaim(&mut t, Some(state), 1, "en");
10086        assert_eq!(t.status, TaskStatus::Parked);
10087        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
10088        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10089        assert!(t.park_reason.is_some());
10090        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
10091        assert!(!t.fresh_start);
10092        assert!(t.status.runnable());
10093    }
10094
10095    #[test]
10096    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
10097        let mut t = task();
10098        t.start("20260904-000000-4043".to_owned());
10099        t.last_error = Some("earlier trouble".to_owned());
10100        settle(
10101            &mut t,
10102            Verdict {
10103                status: RunStatus::Judging,
10104                left_pr: false,
10105                quota_hit: false,
10106                parked: true,
10107                no_viable_candidates: false,
10108            },
10109            "parked after `judging`",
10110            1,
10111        );
10112        assert_eq!(t.status, TaskStatus::Parked);
10113        assert_eq!(t.attempts, 0);
10114        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10115        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
10116        assert_eq!(t.schema, crate::queue::SCHEMA);
10117        assert!(
10118            crate::notices::task_held(&t).is_none(),
10119            "a park is not news"
10120        );
10121        t.start("20260904-000000-4043".to_owned());
10122        assert_eq!(t.park_reason, None);
10123    }
10124
10125    #[test]
10126    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
10127        // A blocked run with attempts left goes back to `Failed`, exactly as
10128        // it would from `attempt` itself - `reclaim` must not invent a second
10129        // policy for a task a daemon merely stopped without reporting.
10130        let mut t = task();
10131        t.start("20260904-000000-4043".to_owned());
10132        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
10133        assert_eq!(t.status, TaskStatus::Failed);
10134        assert!(t.status.runnable());
10135    }
10136
10137    #[test]
10138    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
10139        let mut t = task();
10140        t.start("20260904-000000-4043".to_owned());
10141        assert_eq!(t.attempts, 1);
10142        let mut run = run_state(RunStatus::Implementing);
10143        run.id = "20260904-000000-4043".to_owned();
10144        run.begin_pass();
10145        let cause = crate::run::ParkCause::Upgrade {
10146            from: "0.121.0".to_owned(),
10147            to: Some("0.121.1".to_owned()),
10148        };
10149        run.end_pass_parked(cause.clone());
10150        run.parked = true;
10151        let verdict = Verdict {
10152            status: run.status,
10153            left_pr: false,
10154            quota_hit: false,
10155            parked: true,
10156            no_viable_candidates: false,
10157        };
10158        // A crash after the checkpoint but before queue settlement must
10159        // recover exactly the same scheduling evidence and refund.
10160        let mut orphan = t.clone();
10161        reclaim(&mut orphan, Some(run.clone()), 2, "en");
10162        assert_eq!(orphan.status, TaskStatus::Parked);
10163        assert_eq!(orphan.attempts, 0);
10164        assert_eq!(
10165            orphan.upgrade_resume_key(),
10166            Some((run.passes[0].started_at, orphan.id.as_str()))
10167        );
10168        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
10169        assert_eq!(t.attempts, 0);
10170        assert_eq!(t.passes.len(), 1);
10171        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10172        assert_eq!(t.passes[0].parked, Some(cause));
10173        assert_eq!(t.passes[0].pass_index, 0);
10174        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
10175        assert!(t.upgrade_resume_key().is_some());
10176
10177        // A resumed pass that then fails spends its attempt, and the earlier
10178        // pass's entry is untouched.
10179        t.start("20260904-000000-4043".to_owned());
10180        run.begin_pass();
10181        run.status = RunStatus::Failed;
10182        let verdict = Verdict {
10183            status: RunStatus::Failed,
10184            left_pr: false,
10185            quota_hit: false,
10186            parked: false,
10187            no_viable_candidates: false,
10188        };
10189        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
10190        assert_eq!(t.passes.len(), 2);
10191        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10192        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
10193        assert_eq!(t.passes[1].pass_index, 1);
10194        assert_eq!(t.attempts, 1);
10195    }
10196
10197    #[test]
10198    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
10199        let mut t = task();
10200        t.start("20260904-000000-4043".to_owned());
10201        reclaim(&mut t, None, 2, "en");
10202        assert_eq!(t.status, TaskStatus::Held);
10203        assert!(
10204            t.last_error
10205                .as_deref()
10206                .is_some_and(|e| e.contains("running")),
10207            "the operator needs to know why this task was held"
10208        );
10209    }
10210
10211    #[test]
10212    fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
10213        let dir = tempfile::tempdir().unwrap();
10214        let queue = Queue::at(dir.path().to_path_buf());
10215        let mut task = task();
10216        let run = "20261124-000000-dead";
10217        task.link_run(run);
10218        task.attempts = 2;
10219        task.status = TaskStatus::Running;
10220        task.sync_only = Some(crate::base_sync_only::Request {
10221            run: run.into(),
10222            at: Timestamp::now(),
10223        });
10224        queue.put(&mut task).unwrap();
10225        assert_eq!(
10226            reclaim_orphaned_running(&queue, 3, &Default::default()),
10227            vec![task.id.clone()]
10228        );
10229        let saved = queue.get(&task.id).unwrap();
10230        assert_eq!(saved.status, TaskStatus::Held);
10231        assert_eq!(saved.attempts, 2);
10232        assert_eq!(saved.execution_runs(), [run]);
10233        assert!(
10234            saved
10235                .last_error
10236                .unwrap()
10237                .contains("verification was not allowed")
10238        );
10239        assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
10240    }
10241
10242    #[test]
10243    fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
10244        use crate::base_sync_only::{Outcome, Pass, Request};
10245
10246        let mut state = run_state(RunStatus::Blocked);
10247        let mut task = task();
10248        let request = Request {
10249            run: state.id.clone(),
10250            at: Timestamp::now(),
10251        };
10252        task.start(state.id.clone());
10253        task.sync_only = Some(request.clone());
10254        // Dedicated dispatch saves Running with the pre-pass attempt count.
10255        task.attempts = 2;
10256        let mut pass = Pass::new(request, &state);
10257        pass.result = Outcome::AlreadyCurrent;
10258        state.sync_only_passes.push(pass);
10259        state.begin_pass();
10260
10261        reclaim(&mut task, Some(state), 3, "en");
10262
10263        assert_eq!(task.status, TaskStatus::Held);
10264        assert_eq!(task.attempts, 2);
10265        assert!(task.sync_only.is_none());
10266        let detail = task.hold_reason.unwrap();
10267        assert!(detail.contains("HEAD already contains the base"));
10268        assert!(detail.contains("verification was not allowed"));
10269    }
10270
10271    #[test]
10272    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
10273        let dir = tempfile::tempdir().unwrap();
10274        let queue = Queue::at(dir.path().to_path_buf());
10275
10276        // No run recorded, so this never has to touch `RunState::load`.
10277        let mut orphaned = task();
10278        orphaned.id = "20260904-000000-orph".to_owned();
10279        orphaned.status = TaskStatus::Running;
10280        orphaned.attempts = 1;
10281        queue.put(&mut orphaned).unwrap();
10282
10283        let mut alive = task();
10284        alive.id = "20260904-000000-live".to_owned();
10285        alive.status = TaskStatus::Running;
10286        alive.attempts = 1;
10287        queue.put(&mut alive).unwrap();
10288        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
10289
10290        let mut queued = task();
10291        queued.id = "20260904-000000-wait".to_owned();
10292        queue.put(&mut queued).unwrap();
10293
10294        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10295        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
10296
10297        assert_eq!(
10298            queue.get(&orphaned.id).unwrap().status,
10299            TaskStatus::Held,
10300            "nothing was driving it and there was no run to recover"
10301        );
10302        assert_eq!(
10303            queue.get(&alive.id).unwrap().status,
10304            TaskStatus::Running,
10305            "a live claim must protect the task it belongs to"
10306        );
10307        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
10308    }
10309
10310    /// Read a run.json back from an explicit `home`, the same way
10311    /// `reclaim_abandoned_runs` itself does - never through the
10312    /// process-global `RunState::load`, which this test's own `home` (an
10313    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
10314    /// use at all.
10315    fn read_run_under(home: &Path, id: &str) -> RunState {
10316        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10317        serde_json::from_str(&body).unwrap()
10318    }
10319
10320    #[test]
10321    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
10322        let dir = tempfile::tempdir().unwrap();
10323        let home = dir.path().to_path_buf();
10324        let now = Timestamp::now();
10325        let overrun_seat = || crate::run::ActiveSeat {
10326            node: "implement".to_owned(),
10327            started_at: now - jiff::SignedDuration::new(21_000, 0),
10328            timeout_secs: 3_600,
10329            attempt: 0,
10330            task: None,
10331            command: None,
10332            index: None,
10333            total: None,
10334        };
10335
10336        let mut dead = run_state(RunStatus::Implementing);
10337        dead.id = "20260101-000000-dead".to_owned();
10338        dead.active.insert("impl-A".to_owned(), overrun_seat());
10339        // A `driver_pid` the injected query below confirms gone outright —
10340        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
10341        dead.driver_pid = Some(4242);
10342        dead.save_under(&home).unwrap();
10343
10344        // Same shape, but a live daemon's heartbeat names it: must be left
10345        // exactly alone, however far past its own timeout the seat sits.
10346        let mut alive = run_state(RunStatus::Implementing);
10347        alive.id = "20260101-000000-aliv".to_owned();
10348        alive.active.insert("impl-A".to_owned(), overrun_seat());
10349        alive.save_under(&home).unwrap();
10350        let mut status = Status::new();
10351        status.current = vec![Current {
10352            worker: None,
10353            task: "20260101-000000-task".to_owned(),
10354            run: alive.id.clone(),
10355        }];
10356        write_status_to(&home.join("daemon.json"), &status).unwrap();
10357
10358        // The abandoned seat left an open question behind: nobody is left to
10359        // read an answer once the run is failed, and this must not wait for
10360        // some later daemon startup's own sweep to notice that.
10361        let questions = Questions::at(home.join("questions"));
10362        let mut q = ask::Question::new(
10363            dead.id.clone(),
10364            "implement".to_owned(),
10365            "impl-A".to_owned(),
10366            "Which storage backend?".to_owned(),
10367            String::new(),
10368            vec!["SQLite".to_owned(), "Redis".to_owned()],
10369        );
10370        questions.put(&mut q).unwrap();
10371
10372        let abandoned = reclaim_abandoned_runs_with(
10373            &home,
10374            now,
10375            |pid| if pid == 4242 { Some(false) } else { None },
10376            |_| panic!("a query answering Dead outright needs no identity corroboration"),
10377        );
10378        assert_eq!(abandoned, vec![dead.id.clone()]);
10379
10380        let reloaded = read_run_under(&home, &dead.id);
10381        assert_eq!(reloaded.status, RunStatus::Failed);
10382        assert!(reloaded.active.is_empty());
10383        assert!(
10384            !questions.get(&q.id).unwrap().status.open(),
10385            "the failed run's own open question must be settled in the same pass"
10386        );
10387
10388        let still_alive = read_run_under(&home, &alive.id);
10389        assert_eq!(
10390            still_alive.status,
10391            RunStatus::Implementing,
10392            "a live daemon's claim protects it"
10393        );
10394        assert!(!still_alive.active.is_empty());
10395    }
10396
10397    /// The exact shape a review round flagged as broken: `magi serve` running
10398    /// in this same `home` scans *every* run on disk, including a manual
10399    /// `magi review` / `magi run` this daemon never started and that
10400    /// therefore claims no heartbeat of its own. Before this scan asked
10401    /// `liveness` rather than just `is_working_on`, a manual run whose active
10402    /// seat merely ran a little past its own timeout — the CLI finishing up,
10403    /// its result still being collected — got wiped and failed by a daemon
10404    /// that had nothing to do with it, out from under a process that was
10405    /// still very much running.
10406    #[test]
10407    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
10408        let dir = tempfile::tempdir().unwrap();
10409        let home = dir.path().to_path_buf();
10410        let now = Timestamp::now();
10411
10412        let mut manual = run_state(RunStatus::Reviewing);
10413        manual.id = "20260101-000000-manl".to_owned();
10414        manual.active.insert(
10415            "review-1".to_owned(),
10416            crate::run::ActiveSeat {
10417                node: "review".to_owned(),
10418                started_at: now - jiff::SignedDuration::new(21_000, 0),
10419                timeout_secs: 3_600,
10420                attempt: 0,
10421                task: None,
10422                command: None,
10423                index: None,
10424                total: None,
10425            },
10426        );
10427        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
10428        // but a real, still-running process: `liveness` must corroborate this
10429        // as `Live`, not read the missing daemon claim as death.
10430        manual.driver_pid = Some(4242);
10431        manual.driver_started_at = Some("1790000000".to_owned());
10432        manual.save_under(&home).unwrap();
10433
10434        let abandoned = reclaim_abandoned_runs_with(
10435            &home,
10436            now,
10437            |pid| if pid == 4242 { Some(true) } else { None },
10438            |pid| {
10439                if pid == 4242 {
10440                    Some("1790000000".to_owned())
10441                } else {
10442                    None
10443                }
10444            },
10445        );
10446        assert!(
10447            abandoned.is_empty(),
10448            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
10449        );
10450
10451        let reloaded = read_run_under(&home, &manual.id);
10452        assert_eq!(reloaded.status, RunStatus::Reviewing);
10453        assert!(!reloaded.active.is_empty());
10454    }
10455
10456    #[test]
10457    fn an_already_claimed_task_is_skipped_rather_than_failed() {
10458        let dir = tempfile::tempdir().unwrap();
10459        let queue = Queue::at(dir.path().to_path_buf());
10460        let mut only = task();
10461        queue.put(&mut only).unwrap();
10462
10463        let _elsewhere = queue.claim(&only.id).unwrap();
10464        let candidates = runnable(&queue);
10465        assert_eq!(candidates.len(), 1, "the task is still runnable");
10466        assert!(
10467            queue.claim(&candidates[0].id).is_err(),
10468            "the loop cannot take a claim somebody else holds"
10469        );
10470
10471        let after = queue.get(&only.id).unwrap();
10472        assert_eq!(after.status, TaskStatus::Queued);
10473        assert_eq!(
10474            after.attempts, 0,
10475            "losing the race is not an attempt at the task"
10476        );
10477        assert_eq!(after.last_error, None);
10478    }
10479
10480    #[test]
10481    fn the_status_file_round_trips_and_its_heartbeat_advances() {
10482        let dir = tempfile::tempdir().unwrap();
10483        let path = dir.path().join("daemon.json");
10484
10485        let mut status = Status::new();
10486        status.idle = false;
10487        status.completed = 7;
10488        status.current = vec![Current {
10489            worker: None,
10490            task: "20260902-000000-t111".to_owned(),
10491            run: "20260902-000001-r111".to_owned(),
10492        }];
10493        write_status_to(&path, &status).unwrap();
10494        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10495        assert_eq!(first.schema, SCHEMA);
10496        assert_eq!(first.pid, std::process::id());
10497        assert!(!first.idle);
10498        assert_eq!(first.completed, 7);
10499        assert_eq!(first.current, status.current);
10500        assert!(
10501            !path.with_extension("json.tmp").exists(),
10502            "the temp file is renamed, not left behind"
10503        );
10504
10505        std::thread::sleep(Duration::from_millis(5));
10506        status.updated_at = Timestamp::now();
10507        status.polls = 3;
10508        write_status_to(&path, &status).unwrap();
10509        let second: Status =
10510            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10511        assert!(
10512            second.updated_at > first.updated_at,
10513            "a reader can only detect staleness if the heartbeat moves"
10514        );
10515        assert_eq!(
10516            second.started_at, first.started_at,
10517            "the start time is not a heartbeat"
10518        );
10519        assert_eq!(second.polls, 3);
10520    }
10521
10522    #[test]
10523    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
10524        let dir = tempfile::tempdir().unwrap();
10525
10526        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
10527
10528        let mut status = Status::new();
10529        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
10530        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10531        let stale = read_status(dir.path()).unwrap();
10532        assert!(
10533            !stale.running(Timestamp::now()),
10534            "a minute without a heartbeat is a dead daemon, not a busy one"
10535        );
10536        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
10537
10538        status.updated_at = Timestamp::now();
10539        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10540        let fresh = read_status(dir.path()).unwrap();
10541        assert!(fresh.running(Timestamp::now()));
10542    }
10543
10544    #[test]
10545    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
10546        let dir = tempfile::tempdir().unwrap();
10547        let now = Timestamp::now();
10548        let mine = "20260903-080619-01c2";
10549
10550        assert!(
10551            !is_working_on(dir.path(), mine, now),
10552            "no status file means nobody is working on anything"
10553        );
10554
10555        let mut status = Status::new();
10556        status.current = vec![Current {
10557            worker: None,
10558            task: "20260903-080340-0167".to_owned(),
10559            run: mine.to_owned(),
10560        }];
10561        status.updated_at = now;
10562        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10563        assert!(is_working_on(dir.path(), mine, now));
10564        assert!(
10565            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
10566            "a daemon busy with one run is not working on another"
10567        );
10568
10569        // A killed daemon stops writing heartbeats but leaves the file behind
10570        // naming the run it died in. That run must not be undeletable forever.
10571        status.updated_at = now - jiff::SignedDuration::from_secs(600);
10572        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10573        assert!(
10574            !is_working_on(dir.path(), mine, now),
10575            "a stale heartbeat is a dead daemon, so its run is a leftover"
10576        );
10577    }
10578
10579    #[test]
10580    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
10581        let dir = tempfile::tempdir().unwrap();
10582        let now = Timestamp::now();
10583
10584        assert!(
10585            !is_working_on_short(dir.path(), "01c2", now),
10586            "no status file means nobody is working on anything"
10587        );
10588
10589        let mut status = Status::new();
10590        status.current = vec![Current {
10591            worker: None,
10592            task: "20260903-080340-0167".to_owned(),
10593            run: "20260903-080619-01c2".to_owned(),
10594        }];
10595        status.updated_at = now;
10596        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10597        assert!(
10598            is_working_on_short(dir.path(), "01c2", now),
10599            "the run's short id is the last block of its full id"
10600        );
10601        assert!(
10602            !is_working_on_short(dir.path(), "3cbf", now),
10603            "a daemon busy with one worktree bay is not working on another"
10604        );
10605    }
10606
10607    #[test]
10608    fn a_newer_status_file_still_yields_a_reading() {
10609        let dir = tempfile::tempdir().unwrap();
10610        // A field this build has never heard of must not turn the reading into
10611        // nothing at all; that is the whole reason the reader is permissive.
10612        std::fs::write(
10613            dir.path().join("daemon.json"),
10614            serde_json::json!({
10615                "schema": 2,
10616                "updated_at": Timestamp::now().to_string(),
10617                "idle": true,
10618                "surprise": { "nested": [1, 2, 3] },
10619            })
10620            .to_string(),
10621        )
10622        .unwrap();
10623
10624        let reading = read_status(dir.path()).expect("a forward-compatible read");
10625        assert!(reading.running(Timestamp::now()));
10626        assert!(reading.idle);
10627        assert!(reading.current.is_empty());
10628    }
10629
10630    #[test]
10631    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
10632        // A daemon started before `current` became a list keeps writing this
10633        // shape on every heartbeat until it is restarted. A rolling upgrade
10634        // - a newer `magi web` or `magi doctor` reading an older `magi
10635        // serve`'s heartbeat - must still see the run it is on, not "no
10636        // daemon" from a type mismatch failing the whole struct.
10637        let dir = tempfile::tempdir().unwrap();
10638        std::fs::write(
10639            dir.path().join("daemon.json"),
10640            serde_json::json!({
10641                "schema": 1,
10642                "pid": 4242,
10643                "updated_at": Timestamp::now().to_string(),
10644                "idle": false,
10645                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
10646                "completed": 3,
10647                "polls": 9,
10648            })
10649            .to_string(),
10650        )
10651        .unwrap();
10652
10653        let reading = read_status(dir.path()).expect("an older shape must still parse");
10654        assert!(reading.running(Timestamp::now()));
10655        assert_eq!(
10656            reading.current,
10657            vec![Current {
10658                worker: None,
10659                task: "20260902-140501-aaaa".to_owned(),
10660                run: "20260902-140502-bbbb".to_owned(),
10661            }]
10662        );
10663    }
10664
10665    #[test]
10666    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
10667        let dir = tempfile::tempdir().unwrap();
10668        std::fs::write(
10669            dir.path().join("daemon.json"),
10670            serde_json::json!({
10671                "schema": 1,
10672                "updated_at": Timestamp::now().to_string(),
10673                "idle": true,
10674                "current": null,
10675            })
10676            .to_string(),
10677        )
10678        .unwrap();
10679        let with_null = read_status(dir.path()).expect("null must still parse");
10680        assert!(with_null.current.is_empty());
10681
10682        std::fs::write(
10683            dir.path().join("daemon.json"),
10684            serde_json::json!({
10685                "schema": 1,
10686                "updated_at": Timestamp::now().to_string(),
10687                "idle": true,
10688            })
10689            .to_string(),
10690        )
10691        .unwrap();
10692        let absent = read_status(dir.path()).expect("a missing field must still parse");
10693        assert!(absent.current.is_empty());
10694    }
10695
10696    #[test]
10697    fn a_task_without_a_repository_runs_in_the_daemons_default() {
10698        let fallback = Path::new("/default");
10699        let mut blank = task();
10700        blank.repo = PathBuf::new();
10701        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
10702        let mut dot = task();
10703        dot.repo = PathBuf::from(".");
10704        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
10705        assert_eq!(
10706            repo_for(&task(), fallback),
10707            PathBuf::from("/repo"),
10708            "a task that names a repository keeps it"
10709        );
10710    }
10711
10712    #[test]
10713    fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
10714        let dir = tempfile::tempdir().unwrap();
10715        let repo = dir.path();
10716        let path = repo.join("explicit.toml");
10717        std::fs::write(
10718            &path,
10719            "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
10720        )
10721        .unwrap();
10722        let opts = Opts {
10723            config: Some(path),
10724            ..Opts::default()
10725        };
10726        let queue = Queue::at(repo.join("queue"));
10727        let mut new = task();
10728        queue.put(&mut new).unwrap();
10729        let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
10730        assert_eq!(
10731            resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
10732            BuildCache::Isolated
10733        );
10734
10735        let mut old = task();
10736        old.schema = 22;
10737        queue.put(&mut old).unwrap();
10738        let mut old = queue.get(&old.id).unwrap();
10739        let config = resolved(&old);
10740        assert_eq!(config.verify.build_cache, BuildCache::Shared);
10741        assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
10742        old.hold_manual(Some("wait".into()));
10743        queue.put(&mut old).unwrap();
10744
10745        let mut saved = queue.get(&old.id).unwrap();
10746        assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
10747        saved
10748            .overrides
10749            .as_mut()
10750            .unwrap()
10751            .merge_over(&crate::queue::RunOverrides {
10752                build_cache: Some(BuildCache::Isolated),
10753                ..Default::default()
10754            });
10755        queue.put(&mut saved).unwrap();
10756        assert_eq!(
10757            resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
10758            BuildCache::Isolated
10759        );
10760    }
10761
10762    #[test]
10763    fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
10764        let dir = tempfile::tempdir().unwrap();
10765        let path = dir.path().join("explicit.toml");
10766        let write = |verify: &str| {
10767            std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
10768        };
10769        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
10770        let opts = Opts {
10771            config: Some(path.clone()),
10772            ..Opts::default()
10773        };
10774        let mut task = task();
10775        task.set_urgent(true).unwrap();
10776        let resolved = |task: &Task| {
10777            prepare_for(dir.path(), &opts, task)
10778                .unwrap()
10779                .verify
10780                .build_cache
10781        };
10782        assert_eq!(resolved(&task), BuildCache::Isolated);
10783        task.change_build_cache(Some(BuildCache::Shared)).unwrap();
10784        assert_eq!(resolved(&task), BuildCache::Shared);
10785        task.change_build_cache(None).unwrap();
10786        assert_eq!(resolved(&task), BuildCache::Isolated);
10787        task.set_urgent(false).unwrap();
10788        assert_eq!(resolved(&task), BuildCache::Shared);
10789
10790        // Urgent work must never be the one stopped by isolation: with no
10791        // shared cache to wait behind, or with a verification command isolated
10792        // mode cannot run, an urgent task keeps the configured mode.
10793        task.set_urgent(true).unwrap();
10794        write("e2e = [\"npm test\"]\n");
10795        assert_eq!(resolved(&task), BuildCache::Shared);
10796        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
10797        assert_eq!(resolved(&task), BuildCache::Shared);
10798        // An explicit choice stays strict and is applied as asked.
10799        task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
10800        assert_eq!(resolved(&task), BuildCache::Isolated);
10801    }
10802
10803    #[test]
10804    fn task_implementers_edit_inherits_daemon_config_and_merge() {
10805        let dir = tempfile::tempdir().unwrap();
10806        let path = dir.path().join("explicit.toml");
10807        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
10808        let opts = Opts {
10809            config: Some(path),
10810            merge: Some("none".into()),
10811            ..Default::default()
10812        };
10813        let mut t = task();
10814        t.set_implementers(
10815            2,
10816            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10817                .unwrap(),
10818        )
10819        .unwrap();
10820        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10821        assert_eq!(cfg.graph.implementers, 2);
10822        assert_eq!(cfg.graph.judges, 1);
10823        assert_eq!(cfg.merge.mode, MergeMode::None);
10824        t.set_implementers(1, &cfg).unwrap();
10825        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10826        apply_task_implementers(&mut cfg, &t);
10827        assert_eq!(cfg.graph.implementers, 1);
10828        assert_eq!(cfg.graph.judges, 1);
10829        assert_eq!(cfg.merge.mode, MergeMode::None);
10830    }
10831
10832    #[test]
10833    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
10834        let dir = tempfile::tempdir().unwrap();
10835        let repo = dir.path().join("repo");
10836        std::fs::create_dir(&repo).unwrap();
10837        std::fs::write(
10838            repo.join("magi.toml"),
10839            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
10840        )
10841        .unwrap();
10842        let daemon_config = dir.path().join("daemon.toml");
10843        std::fs::write(
10844            &daemon_config,
10845            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
10846        )
10847        .unwrap();
10848        let opts = Opts {
10849            config: Some(daemon_config),
10850            merge: Some("pr".into()),
10851            ..Default::default()
10852        };
10853        let q = Queue::at(dir.path().join("queue"));
10854        let validation: Config =
10855            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10856                .unwrap();
10857        // No provenance field on legacy direct tasks: both shapes stay isolated.
10858        for record in ["{}", r#"{"candidates":2}"#] {
10859            let overrides = serde_json::from_str(record).unwrap();
10860            let filing = crate::direct::Filing {
10861                instruction: "work".into(),
10862                title: "direct".into(),
10863                repo: repo.clone(),
10864                source: crate::queue::Source::Human,
10865                solo: false,
10866                overrides,
10867                review_of: None,
10868                sources: Default::default(),
10869            };
10870            let filed =
10871                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
10872            let crate::direct::Filed::Standalone {
10873                mut task,
10874                claim: _claim,
10875            } = filed
10876            else {
10877                panic!("local filing")
10878            };
10879            let before = prepare_for(&repo, &opts, &task).unwrap();
10880            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
10881            assert_eq!(
10882                before.merge.mode,
10883                MergeMode::None,
10884                "daemon --merge must not leak"
10885            );
10886            for n in [2, 1, 2] {
10887                task.set_implementers(n, &validation).unwrap();
10888                q.put(&mut task).unwrap();
10889                task = q.get(&task.id).unwrap();
10890                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
10891                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
10892                apply_task_implementers(&mut cfg, &task);
10893                assert_eq!(cfg.graph.implementers, usize::from(n));
10894                assert_eq!(cfg.graph.judges, 2);
10895                assert_eq!(cfg.merge.mode, MergeMode::None);
10896            }
10897        }
10898    }
10899
10900    #[test]
10901    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
10902        let cfg: Config =
10903            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10904                .unwrap();
10905        let mut t = task();
10906        t.review_of = Some("review-target".into());
10907        t.hold_manual(Some("retry".into()));
10908        let mut previous = RunState::new(
10909            PathBuf::from("/repo"),
10910            "main".into(),
10911            "abc1234".into(),
10912            "review".into(),
10913            cfg.clone(),
10914        );
10915        previous.config.graph.implementers = 2;
10916        for count in [1, 3] {
10917            t.set_implementers(count, &cfg).unwrap();
10918            t.release();
10919            assert_eq!(t.review_of.as_deref(), Some("review-target"));
10920            for proposed in [
10921                Starter::Resume(previous.id.clone()),
10922                Starter::Review("recovery-target".into()),
10923            ] {
10924                assert_eq!(
10925                    starter_with_implementers(&t, Some(&previous), proposed),
10926                    Starter::Review("review-target".into())
10927                );
10928            }
10929            let mut configured = cfg.clone();
10930            apply_task_implementers(&mut configured, &t);
10931            assert_eq!(configured.graph.implementers, usize::from(count));
10932            assert_eq!(previous.config.graph.implementers, 2);
10933        }
10934    }
10935
10936    #[test]
10937    fn task_implementers_dispatch_and_resume_agree() {
10938        let mut t = task();
10939        let cfg: crate::config::Config =
10940            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10941                .unwrap();
10942        let mut run = RunState::new(
10943            PathBuf::from("/repo"),
10944            "main".into(),
10945            "abc1234".into(),
10946            "work".into(),
10947            cfg.clone(),
10948        );
10949        run.config.graph.implementers = 2;
10950        for n in [2, 1, 3, 2] {
10951            t.set_implementers(n, &cfg).unwrap();
10952            let mut dispatched = cfg.clone();
10953            apply_task_implementers(&mut dispatched, &t);
10954            assert_eq!(dispatched.graph.implementers, usize::from(n));
10955            assert_eq!(implementers_match(&t, &run), n == 2);
10956            for proposed in [
10957                Starter::Resume(run.id.clone()),
10958                Starter::Review("old-branch".into()),
10959            ] {
10960                let expected = if n == 2 {
10961                    proposed.clone()
10962                } else {
10963                    Starter::Start
10964                };
10965                assert_eq!(
10966                    starter_with_implementers(&t, Some(&run), proposed),
10967                    expected
10968                );
10969            }
10970            assert_eq!(
10971                run.config.graph.implementers, 2,
10972                "history must not be rewritten"
10973            );
10974        }
10975        t.solo = false;
10976        t.overrides = None;
10977        assert!(implementers_match(&t, &run));
10978    }
10979
10980    #[test]
10981    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
10982        // Three seats said out loud. What `solo` promises is one candidate
10983        // *whatever the config asks for*, so the contrast has to be a number
10984        // this test owns - it used to be `Config::default()`'s, which became
10985        // 1 when one implementation became the default and left the two
10986        // halves of this test asserting the same thing.
10987        let mut solo_cfg = Config::default();
10988        solo_cfg.graph.implementers = 3;
10989        let mut solo_task = task();
10990        solo_task.solo = true;
10991        apply_task_implementers(&mut solo_cfg, &solo_task);
10992        assert_eq!(solo_cfg.graph.implementers, 1);
10993
10994        let mut plain_cfg = Config::default();
10995        plain_cfg.graph.implementers = 3;
10996        let plain_task = task();
10997        assert!(!plain_task.solo);
10998        apply_task_implementers(&mut plain_cfg, &plain_task);
10999        assert_eq!(
11000            plain_cfg.graph.implementers, 3,
11001            "a task that did not ask to run alone keeps the config's candidates"
11002        );
11003    }
11004
11005    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
11006        QuotaLoss {
11007            cause: crate::agent::QuotaCause::UsageLimit,
11008            agent: String::new(),
11009            seat: seat.into(),
11010            node: "judge".into(),
11011            at: at.parse().unwrap(),
11012            reset: reset.map(str::to_string),
11013        }
11014    }
11015
11016    #[test]
11017    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
11018        let now = Timestamp::now();
11019        for reset in [None, Some("in 1h")] {
11020            let auth = crate::agent::Quota {
11021                cause: crate::agent::QuotaCause::Authentication,
11022                agent: "alpha".into(),
11023                reset: reset.map(str::to_owned),
11024            };
11025            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
11026            assert_eq!(cooldown_until(&[loss], now), None);
11027        }
11028    }
11029
11030    #[test]
11031    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
11032        let old: Vec<QuotaLoss> = (1..=4)
11033            .map(|i| {
11034                loss(
11035                    &format!("judge-{i}"),
11036                    "2026-09-23T05:23:00Z",
11037                    Some("2:40pm (Asia/Tokyo)"),
11038                )
11039            })
11040            .collect();
11041        let fresh = losses_this_attempt(&old, &old);
11042        assert!(fresh.is_empty());
11043        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
11044        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
11045    }
11046
11047    #[test]
11048    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
11049        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
11050        let now = Timestamp::now();
11051        let mut after = old.clone();
11052        after.push(loss("judge-2", &now.to_string(), None));
11053        let fresh = losses_this_attempt(&old, &after);
11054        assert_eq!(fresh, vec![after[1].clone()]);
11055        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
11056        assert_eq!(
11057            until,
11058            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
11059        );
11060    }
11061
11062    #[test]
11063    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
11064        // `recover_stall` removes judge-1's loss and the retry then hits quota
11065        // again: the vector is the same length, so an index diff sees nothing.
11066        let before = vec![
11067            loss("judge-1", "2026-09-23T05:23:00Z", None),
11068            loss("judge-2", "2026-09-23T05:24:00Z", None),
11069        ];
11070        let after = vec![
11071            loss("judge-2", "2026-09-23T05:24:00Z", None),
11072            loss("judge-1", "2026-09-24T01:00:00Z", None),
11073        ];
11074        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
11075    }
11076
11077    #[test]
11078    fn merge_overrides_are_parsed_or_refused() {
11079        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
11080        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
11081        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
11082        assert!(merge_mode("squash").is_err());
11083    }
11084
11085    #[test]
11086    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
11087        let now = Timestamp::now();
11088        let fallback = Duration::from_secs(300);
11089        let cap = Duration::from_secs(1800);
11090
11091        // No reset hint at all: the fallback.
11092        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
11093
11094        // A reset ten minutes out, well inside the cap: waited for exactly.
11095        let soon = now + jiff::SignedDuration::from_secs(600);
11096        assert_eq!(
11097            quota_wait(Some(soon), now, fallback, cap),
11098            Duration::from_secs(600)
11099        );
11100
11101        // A reset already in the past is not trusted: the fallback, not a
11102        // zero or negative wait that would spin the loop right back around.
11103        let past = now - jiff::SignedDuration::from_secs(60);
11104        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
11105
11106        // A reset further out than the cap is trusted for direction but not
11107        // for magnitude: a parsing slip must not sleep the loop for a day.
11108        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
11109        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
11110    }
11111
11112    #[test]
11113    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
11114        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11115
11116        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
11117        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
11118
11119        // Same clock reading, but it has already gone by today: read as
11120        // tomorrow's, since the CLI would not still be reporting a limit past
11121        // its own stated reset.
11122        let already_past =
11123            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
11124        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
11125
11126        assert!(
11127            parse_reset_hint("session limit reached", now, now).is_none(),
11128            "free text with no recognised shape is not guessed at"
11129        );
11130        assert!(
11131            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
11132            "an unresolvable zone name is not guessed at either"
11133        );
11134    }
11135
11136    #[test]
11137    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
11138        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11139
11140        let at = parse_reset_hint(
11141            "You've hit your usage limit. Visit \
11142             https://chatgpt.com/codex/settings/usage to purchase more \
11143             credits or try again at Sep 19th, 2026 5:10 PM.",
11144            now,
11145            now,
11146        )
11147        .expect("the codex reset wording is a recognised shape");
11148        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
11149
11150        // The month is explicit, so a date already earlier in the same
11151        // sentence-implied year than `now` is trusted as written rather than
11152        // rolled forward a year the way the bracketed shape rolls a
11153        // same-day clock reading to tomorrow.
11154        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
11155            .expect("an explicit year needs no rollover");
11156        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
11157
11158        assert!(
11159            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
11160            "a two-digit year is not the documented shape and is not guessed at"
11161        );
11162        assert!(
11163            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
11164            "a four-letter month name is not the documented three-letter abbreviation"
11165        );
11166        assert!(
11167            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
11168            "an explicit zone on the dated shape is a format nobody has \
11169             documented, and is refused rather than guessed at as UTC"
11170        );
11171    }
11172
11173    #[test]
11174    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
11175        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
11176        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
11177
11178        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
11179        assert_eq!(at.as_second() - recorded.as_second(), 3769);
11180
11181        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
11182        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
11183
11184        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
11185            assert!(
11186                parse_reset_hint(bad, now, recorded).is_none(),
11187                "{bad:?} must not be guessed at"
11188            );
11189        }
11190    }
11191
11192    /// A loop whose queue lives in a temp tree and whose poll interval is far
11193    /// longer than the test's patience, so anything that waits out a poll
11194    /// instead of noticing the stop fails rather than merely being slow.
11195    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
11196        let config = dir.join("magi.toml");
11197        std::fs::write(
11198            &config,
11199            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
11200        )
11201        .unwrap();
11202        let opts = Opts {
11203            poll: Duration::from_secs(30),
11204            config: Some(config),
11205            // The explicit fixture config keeps startup cleanup from reading
11206            // machine configuration. This fictional repository likewise
11207            // keeps any best-effort git cleanup away from this checkout.
11208            repo: dir.join("repo"),
11209            ..Opts::default()
11210        };
11211        // The status file goes in a directory that does not exist yet, so its
11212        // creation is itself evidence the loop published one. `worktrees`
11213        // must be just as fictional: the janitor reclaims worktrees under it
11214        // for real, and a test that let it fall through to
11215        // `crate::run::default_worktree_root()` would have it reclaim
11216        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
11217        // which is exactly what happened before this function took the
11218        // parameter at all.
11219        let home = dir.join("home");
11220        // These control-only fixtures do not launch native workers. Give the
11221        // independently tested maintenance services a fresh cadence receipt.
11222        let stamps = home.join("service-ticks");
11223        std::fs::create_dir_all(&stamps).unwrap();
11224        for service in ["waiter", "deputies", "release-watch"] {
11225            std::fs::write(
11226                stamps.join(service),
11227                Timestamp::now().as_second().to_string(),
11228            )
11229            .unwrap();
11230        }
11231        for operation in [
11232            "conductor",
11233            "maintenance",
11234            "housekeeping",
11235            "disk-pressure",
11236            "cache",
11237            "fetch",
11238            "chat-goals",
11239        ] {
11240            std::fs::write(
11241                stamps.join(format!("daemon-{operation}")),
11242                serde_json::to_vec(&Timestamp::now()).unwrap(),
11243            )
11244            .unwrap();
11245        }
11246        let worktrees = dir.join("wt");
11247        (
11248            opts,
11249            Queue::at(dir.join("queue")),
11250            home.join("daemon.json"),
11251            home,
11252            worktrees,
11253        )
11254    }
11255
11256    #[tokio::test]
11257    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
11258        let dir = tempfile::tempdir().unwrap();
11259        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11260        let mut waiting = task();
11261        waiting.repo = opts.repo.clone();
11262        waiting.hold_machine(crate::disk::gate(1, 100));
11263        waiting.mark_disk_capacity();
11264        waiting.attempts = 2;
11265        queue.put(&mut waiting).unwrap();
11266        let mut busy = task();
11267        busy.status = TaskStatus::Running;
11268        queue.put(&mut busy).unwrap();
11269        let payload = serde_json::to_value(ServiceWorker {
11270            opts,
11271            queue: queue.root().to_owned(),
11272            worktrees_root: worktrees,
11273            operation: "maintenance".into(),
11274        })
11275        .unwrap();
11276        run_service_worker(&home, payload.clone()).await.unwrap();
11277        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
11278        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11279        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
11280        run_service_worker(&home, payload).await.unwrap();
11281        assert!(
11282            crate::worker::active(&home).unwrap().is_empty(),
11283            "monitoring only queues; normal dispatch owns launches"
11284        );
11285        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11286    }
11287
11288    #[tokio::test]
11289    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
11290        let dir = tempfile::tempdir().unwrap();
11291        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11292        let cfg = Config::default();
11293        start_service(
11294            &home,
11295            &opts,
11296            &queue,
11297            &worktrees,
11298            "housekeeping",
11299            Some(&cfg),
11300            true,
11301        )
11302        .await
11303        .unwrap();
11304        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
11305        let read = |path: &Path| -> serde_json::Value {
11306            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
11307        };
11308        assert_eq!(read(&receipt)["detail"], "cadence not due");
11309        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
11310        start_service(
11311            &home,
11312            &opts,
11313            &queue,
11314            &worktrees,
11315            "housekeeping",
11316            Some(&cfg),
11317            true,
11318        )
11319        .await
11320        .unwrap();
11321        assert_eq!(
11322            read(&receipt)["detail"],
11323            "active work or runnable task queue"
11324        );
11325        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
11326        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
11327        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
11328        start_service(
11329            &home,
11330            &opts,
11331            &queue,
11332            &worktrees,
11333            "disk-pressure",
11334            Some(&cfg),
11335            false,
11336        )
11337        .await
11338        .unwrap();
11339        assert_eq!(
11340            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
11341            "no active work; idle housekeeping owns scan"
11342        );
11343        assert!(crate::worker::active(&home).unwrap().is_empty());
11344    }
11345
11346    #[tokio::test]
11347    async fn goal_observation_service_does_not_block_scheduler_decisions() {
11348        let dir = tempfile::tempdir().unwrap();
11349        let (opts, _, _, home, worktrees) = idle_loop(dir.path());
11350        let queue = Queue::at(home.join("queue"));
11351        let mut task = task();
11352        task.repo = opts.repo.clone();
11353        task.chat = Some("decision-chat".into());
11354        task.hold_machine(Some("waiting for a decision".into()));
11355        queue.put(&mut task).unwrap();
11356        let questions = Questions::at(home.join("questions"));
11357        let mut question = action_question(&task.id, ask::ChoiceAction::Done);
11358        question.node = crate::conduct::NODE.into();
11359        question.status = ask::QuestionStatus::Open;
11360        question.answer = None;
11361        question.answered_at = None;
11362        questions.put(&mut question).unwrap();
11363        questions
11364            .update(&question.id, |q| {
11365                q.answer(ask::Answer::Choice("resume で続行する".into()))
11366            })
11367            .unwrap();
11368
11369        let talks = crate::talk::Talks::at(home.join("talks"));
11370        let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
11371        decision_chat.pending = "Keep this unsent status question".into();
11372        talks.put(&mut decision_chat).unwrap();
11373        let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
11374        talk.goals.push(serde_json::from_value(serde_json::json!({
11375            "id":"goal","purpose":"follow the retained job","scope":"one task",
11376            "condition":{"description":"land the result","kind":"runs_merged"},
11377            "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
11378            "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
11379            "started":1,"wakes":1,"last_checked":null,"fingerprint":""
11380        })).unwrap());
11381        talks.put(&mut talk).unwrap();
11382
11383        // A retained service lease models an observation still waiting on its
11384        // external dependency. Admission must neither await nor repeat it.
11385        let directory = home.join("workers/jobs/abcdef");
11386        std::fs::create_dir_all(&directory).unwrap();
11387        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11388        crate::pr_head::try_lock_file(&lease).unwrap();
11389        let mut job = crate::worker::Job {
11390            id: "abcdef".into(),
11391            sequence: 1,
11392            kind: "daemon-service".into(),
11393            key: "service:daemon-chat-goals".into(),
11394            payload: serde_json::Value::Null,
11395            generation: "fixture".into(),
11396            version: None,
11397            status: crate::worker::Status::Running,
11398            result: None,
11399            pid: Some(std::process::id()),
11400            created_at: Timestamp::now().as_second() as u64,
11401            finished_at: None,
11402        };
11403        let record = directory.join("job.json");
11404        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11405        let status = Arc::new(Mutex::new(Status::new()));
11406        let stop = Stop::new();
11407        let mut dispatch = Box::pin(poll(
11408            &opts,
11409            &queue,
11410            &status,
11411            &home,
11412            &worktrees,
11413            &stop,
11414            DispatchLimits {
11415                max_concurrent: 1,
11416                pause_for_interrupts: false,
11417                recovery_cfg: None,
11418            },
11419        ));
11420        std::future::poll_fn(|cx| {
11421            assert!(dispatch.as_mut().poll(cx).is_pending());
11422            std::task::Poll::Ready(())
11423        })
11424        .await;
11425        assert!(lock(&status).polls > 0);
11426        let saved = queue.get(&task.id).unwrap();
11427        assert_eq!(saved.status, TaskStatus::Done);
11428        assert!(saved.action_applied(&question.id));
11429        assert!(
11430            talks
11431                .get("decision-chat")
11432                .unwrap()
11433                .pending
11434                .contains("Keep this unsent status question")
11435        );
11436        let goal = talks.get(&talk.id).unwrap().goals.remove(0);
11437        assert_eq!(goal.state, crate::chat_goal::State::Runnable);
11438        assert_eq!(
11439            goal.started,
11440            Some(1),
11441            "only the observation worker may reconcile its goal"
11442        );
11443        assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
11444
11445        stop.stop();
11446        dispatch.await.unwrap();
11447        job.status = crate::worker::Status::Finished;
11448        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
11449        drop(lease);
11450    }
11451
11452    #[test]
11453    fn a_stop_is_idempotent_and_once_set_stays_set() {
11454        let stop = Stop::new();
11455        assert!(!stop.stopped());
11456
11457        stop.stop();
11458        assert!(stop.stopped());
11459        stop.stop();
11460        assert!(stop.stopped(), "a second stop is not a toggle");
11461
11462        let shared = stop.clone();
11463        assert!(
11464            shared.stopped(),
11465            "a clone is the same stop; that is how the loop and its caller share one"
11466        );
11467    }
11468
11469    #[tokio::test]
11470    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
11471        for operation in ["conductor", "maintenance", "housekeeping"] {
11472            let dir = tempfile::tempdir().unwrap();
11473            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
11474            opts.once = true;
11475            opts.poll = Duration::from_millis(1);
11476            let mut task = task();
11477            task.runs.push("fixture-run".into());
11478            queue.put(&mut task).unwrap();
11479            let claim = queue.claim(&task.id).unwrap();
11480
11481            // Model a live service holding the task's claim across the
11482            // scheduler's dispatch scan. No real subprocess or timed race.
11483            let directory = home.join("workers/jobs/abcdef");
11484            std::fs::create_dir_all(&directory).unwrap();
11485            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11486            crate::pr_head::try_lock_file(&lease).unwrap();
11487            let mut job = crate::worker::Job {
11488                id: "abcdef".into(),
11489                sequence: 1,
11490                kind: "daemon-service".into(),
11491                key: format!("service:daemon-{operation}"),
11492                payload: serde_json::Value::Null,
11493                generation: "fixture".into(),
11494                version: None,
11495                status: crate::worker::Status::Running,
11496                result: None,
11497                pid: Some(std::process::id()),
11498                created_at: Timestamp::now().as_second() as u64,
11499                finished_at: None,
11500            };
11501            let record = directory.join("job.json");
11502            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11503
11504            let status = Arc::new(Mutex::new(Status::new()));
11505            let stop = Stop::new();
11506            let mut drain = Box::pin(poll(
11507                &opts,
11508                &queue,
11509                &status,
11510                &home,
11511                &worktrees,
11512                &stop,
11513                DispatchLimits {
11514                    max_concurrent: 1,
11515                    pause_for_interrupts: false,
11516                    recovery_cfg: None,
11517                },
11518            ));
11519            std::future::poll_fn(|cx| {
11520                use std::future::Future;
11521                assert!(
11522                    drain.as_mut().poll(cx).is_pending(),
11523                    "--once must wait for {operation} to release its queue claim"
11524                );
11525                std::task::Poll::Ready(())
11526            })
11527            .await;
11528            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
11529
11530            // An answer arrives while the service still owns the claim. A
11531            // fresh scheduling pass must apply it before declaring idle.
11532            let questions = Questions::at(home.join("questions"));
11533            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
11534            questions.put(&mut q).unwrap();
11535            drop(claim);
11536            // Model services that took longer than their cadence, without a
11537            // wall-clock sleep. The final scans must not respawn them even
11538            // though their receipts now permit another periodic invocation.
11539            let expired =
11540                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
11541            for service in [operation, "housekeeping"] {
11542                std::fs::write(
11543                    home.join("service-ticks").join(format!("daemon-{service}")),
11544                    &expired,
11545                )
11546                .unwrap();
11547            }
11548            job.status = crate::worker::Status::Finished;
11549            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11550            drop(lease);
11551            tokio::time::timeout(Duration::from_secs(2), drain)
11552                .await
11553                .expect("the settled service must allow the drain to finish")
11554                .unwrap();
11555            let after = queue.get(&task.id).unwrap();
11556            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
11557            assert!(after.action_applied(&q.id));
11558            for service in [operation, "housekeeping"] {
11559                assert_eq!(
11560                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
11561                        .unwrap(),
11562                    expired,
11563                    "the final once rescan must not restart {service}"
11564                );
11565            }
11566        }
11567    }
11568
11569    #[test]
11570    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
11571        let stop = Stop::new();
11572        stop.busy.store(1, Ordering::SeqCst);
11573        assert!(
11574            !stop.finishing(),
11575            "a busy loop nobody has asked to stop is just running"
11576        );
11577
11578        stop.stop();
11579        assert!(
11580            stop.finishing(),
11581            "a stop asked for mid-run has not landed until the run is settled"
11582        );
11583
11584        stop.busy.store(0, Ordering::SeqCst);
11585        assert!(
11586            !stop.finishing(),
11587            "once the run is settled the stop has landed and there is nothing to finish"
11588        );
11589    }
11590
11591    #[test]
11592    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
11593        let stop = Stop::new();
11594        stop.busy.store(2, Ordering::SeqCst);
11595        stop.stop();
11596        assert!(stop.finishing(), "two runs still in flight");
11597
11598        stop.busy.store(1, Ordering::SeqCst);
11599        assert!(
11600            stop.finishing(),
11601            "one run finished, but a sibling is still working"
11602        );
11603
11604        stop.busy.store(0, Ordering::SeqCst);
11605        assert!(
11606            !stop.finishing(),
11607            "the last run out is what actually lands the stop"
11608        );
11609    }
11610
11611    #[tokio::test]
11612    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
11613        let dir = tempfile::tempdir().unwrap();
11614        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11615        let stop = Stop::new();
11616        stop.stop();
11617
11618        let began = std::time::Instant::now();
11619        tokio::time::timeout(
11620            Duration::from_secs(2),
11621            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11622        )
11623        .await
11624        .expect("a stopped loop must return, not sit out its poll interval")
11625        .expect("the loop's own setup and teardown must not fail");
11626        assert!(
11627            began.elapsed() < opts.poll,
11628            "returned only after {:?}, which is a poll interval, not a stop",
11629            began.elapsed()
11630        );
11631    }
11632
11633    #[tokio::test]
11634    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
11635        let dir = tempfile::tempdir().unwrap();
11636        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11637        let stop = Stop::new();
11638
11639        // Asked for after the loop is already parked on its empty queue, which
11640        // is the case an operator tapping stop on a phone actually hits.
11641        let asker = {
11642            let stop = stop.clone();
11643            tokio::spawn(async move {
11644                tokio::time::sleep(Duration::from_millis(20)).await;
11645                stop.stop();
11646            })
11647        };
11648
11649        let began = std::time::Instant::now();
11650        tokio::time::timeout(
11651            Duration::from_secs(2),
11652            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11653        )
11654        .await
11655        .expect("a stop asked for while idle must wake the wait")
11656        .expect("the loop's own setup and teardown must not fail");
11657        asker.await.unwrap();
11658        assert!(
11659            began.elapsed() < opts.poll,
11660            "returned only after {:?}, so the stop waited on the sleep",
11661            began.elapsed()
11662        );
11663    }
11664
11665    #[tokio::test]
11666    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
11667        let dir = tempfile::tempdir().unwrap();
11668        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11669        let stop = Stop::new();
11670        stop.stop();
11671
11672        tokio::time::timeout(
11673            Duration::from_secs(2),
11674            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11675        )
11676        .await
11677        .expect("a stopped loop must return")
11678        .expect("the loop's own setup and teardown must not fail");
11679
11680        assert!(
11681            home.is_dir(),
11682            "the loop did publish a status file, so its removal is the teardown and not an absence"
11683        );
11684        assert!(
11685            !status_file.exists(),
11686            "a stopped loop clears its status file"
11687        );
11688        assert!(
11689            read_status(&home).is_none(),
11690            "a reader must see no daemon at all, not a heartbeat that merely stopped"
11691        );
11692    }
11693
11694    #[tokio::test]
11695    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
11696        let dir = tempfile::tempdir().unwrap();
11697        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11698
11699        let mut settled = RunState::new(
11700            dir.path().join("repo"),
11701            "main".to_owned(),
11702            "abc1234".to_owned(),
11703            "fixture".to_owned(),
11704            Config::default(),
11705        );
11706        settled.status = RunStatus::Ready;
11707        let run_dir = home.join("runs").join(&settled.id);
11708        std::fs::create_dir_all(&run_dir).unwrap();
11709        std::fs::write(
11710            run_dir.join("run.json"),
11711            serde_json::to_string_pretty(&settled).unwrap(),
11712        )
11713        .unwrap();
11714        let questions = Questions::at(home.join("questions"));
11715        let mut question = ask::Question::new(
11716            settled.id.clone(),
11717            "review".to_owned(),
11718            "reviewer-1".to_owned(),
11719            "Continue?".to_owned(),
11720            String::new(),
11721            Vec::new(),
11722        );
11723        questions.put(&mut question).unwrap();
11724
11725        run_service_worker(
11726            &home,
11727            serde_json::to_value(ServiceWorker {
11728                opts,
11729                queue: queue.root().to_path_buf(),
11730                worktrees_root: worktrees,
11731                operation: "housekeeping".to_owned(),
11732            })
11733            .unwrap(),
11734        )
11735        .await
11736        .unwrap();
11737
11738        assert_eq!(
11739            questions.get(&question.id).unwrap().status,
11740            ask::QuestionStatus::Abandoned,
11741            "the independent housekeeping worker settles ended-run questions"
11742        );
11743    }
11744
11745    #[test]
11746    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
11747        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11748
11749        assert!(
11750            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
11751            "never checked before: due at once"
11752        );
11753
11754        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
11755        assert!(
11756            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
11757            "well inside the interval: not due yet"
11758        );
11759
11760        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
11761        assert!(
11762            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
11763            "exactly at the edge: not yet due, same convention as `clean::due`"
11764        );
11765
11766        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11767        assert!(
11768            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
11769            "past the interval: due again"
11770        );
11771    }
11772
11773    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
11774    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
11775    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
11776    /// and the congestion test below both need, and must not drift apart.
11777    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
11778        let config = dir.join("magi.toml");
11779        // A literal (single-quoted) TOML string, not a basic one: the cache
11780        // path is a Windows path full of backslashes, and a basic string
11781        // would have TOML try to interpret `\U` (from `\Users\...`) as a
11782        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
11783        // `{{ vars.cache }}` rendering documents.
11784        std::fs::write(
11785            &config,
11786            format!(
11787                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
11788                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
11789                cache_dir.display()
11790            ),
11791        )
11792        .unwrap();
11793        Opts {
11794            config: Some(config),
11795            repo: dir.join("repo"),
11796            ..Opts::default()
11797        }
11798    }
11799
11800    #[tokio::test]
11801    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
11802        let dir = tempfile::tempdir().unwrap();
11803        let home = dir.path().join("home");
11804        let cache_dir = dir.path().join("cache");
11805        std::fs::create_dir_all(&cache_dir).unwrap();
11806        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11807        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11808
11809        // Nobody has asked this daemon to stop, which is the ordinary case;
11810        // the skip that a stop buys is asserted by its own test below.
11811        let running = Stop::new();
11812        let mut last_checked = None;
11813        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11814        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
11815            .await;
11816        assert_eq!(
11817            crate::disk::dir_size(&cache_dir),
11818            0,
11819            "over the cap on the first check ever: pruned at once, no idle queue required"
11820        );
11821        assert_eq!(last_checked, Some(t0));
11822
11823        // A fresh oversized file lands, but the next check is not due yet.
11824        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
11825        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
11826        maybe_prune_cache_between_runs(
11827            &opts.repo,
11828            &opts,
11829            &home,
11830            &running,
11831            &mut last_checked,
11832            too_soon,
11833        )
11834        .await;
11835        assert_eq!(
11836            crate::disk::dir_size(&cache_dir),
11837            10,
11838            "too soon since the last check: left alone rather than rescanned every call"
11839        );
11840        assert_eq!(
11841            last_checked,
11842            Some(t0),
11843            "an idle check does not reset the clock"
11844        );
11845
11846        // Once the interval elapses, the same oversized cache is caught again.
11847        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11848        maybe_prune_cache_between_runs(
11849            &opts.repo,
11850            &opts,
11851            &home,
11852            &running,
11853            &mut last_checked,
11854            due_again,
11855        )
11856        .await;
11857        assert_eq!(
11858            crate::disk::dir_size(&cache_dir),
11859            0,
11860            "due again: pruned back under the cap"
11861        );
11862    }
11863
11864    /// A stop must not queue behind housekeeping. The prune below is a
11865    /// synchronous walk of the whole cache with no await point in it, so a
11866    /// loop that entered it could not get back to its own `stopped()` test
11867    /// until the walk finished - and because no run is in flight at this
11868    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
11869    /// the stop had already landed. The idle branch has always made this same
11870    /// check before reaching `janitor`; the between-runs path makes it too.
11871    #[tokio::test]
11872    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
11873        let dir = tempfile::tempdir().unwrap();
11874        let home = dir.path().join("home");
11875        let cache_dir = dir.path().join("cache");
11876        std::fs::create_dir_all(&cache_dir).unwrap();
11877        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11878        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11879
11880        let stop = Stop::new();
11881        stop.stop();
11882        assert!(
11883            !stop.finishing(),
11884            "no run is in flight at a between-runs boundary, so nothing else \
11885             would tell the operator this stop had not taken effect yet"
11886        );
11887
11888        let mut last_checked = None;
11889        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11890        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
11891            .await;
11892        assert_eq!(
11893            crate::disk::dir_size(&cache_dir),
11894            10,
11895            "over its cap, and due for the first check ever, but a stop outranks \
11896             it: the cap is a standing policy the next start measures again"
11897        );
11898        assert_eq!(
11899            last_checked, None,
11900            "a check that never happened must not claim the interval"
11901        );
11902    }
11903
11904    /// A backlog must not starve cache pruning. The finite cache worker runs
11905    /// independently of queue drain and must not consume any task attempts.
11906    #[tokio::test]
11907    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
11908        let dir = tempfile::tempdir().unwrap();
11909        let cache_dir = dir.path().join("cache");
11910        std::fs::create_dir_all(&cache_dir).unwrap();
11911        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
11912
11913        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
11914        opts.poll = Duration::from_millis(20);
11915        opts.max_attempts = 1_000;
11916
11917        let queue = Queue::at(dir.path().join("queue"));
11918        for i in 0..128 {
11919            let mut task = Task::new(
11920                format!("queued work {i}"),
11921                format!("queued work {i}"),
11922                opts.repo.clone(),
11923                Source::Human,
11924            );
11925            queue.put(&mut task).unwrap();
11926        }
11927
11928        let home = dir.path().join("home");
11929        let worktrees = dir.path().join("wt");
11930        run_service_worker(
11931            &home,
11932            serde_json::to_value(ServiceWorker {
11933                opts,
11934                queue: queue.root().to_path_buf(),
11935                worktrees_root: worktrees,
11936                operation: "cache".to_owned(),
11937            })
11938            .unwrap(),
11939        )
11940        .await
11941        .unwrap();
11942        let after = queue.list();
11943        assert_eq!(after.len(), 128);
11944        assert!(
11945            after
11946                .iter()
11947                .all(|task| task.status.runnable() && task.attempts == 0)
11948        );
11949
11950        assert_eq!(
11951            crate::disk::dir_size(&cache_dir),
11952            0,
11953            "an oversized cache must not be left to grow unboundedly just because the \
11954             queue kept the loop busy the whole time"
11955        );
11956    }
11957
11958    #[test]
11959    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
11960        let dir = tempfile::tempdir().unwrap();
11961        let queue = Queue::at(dir.path().join("queue"));
11962        let questions = Questions::at(dir.path().join("questions"));
11963        let mut task = task();
11964        queue.put(&mut task).unwrap();
11965
11966        let mut task_question = ask::Question::new(
11967            task.id.clone(),
11968            crate::conduct::NODE.to_owned(),
11969            "conduct".to_owned(),
11970            "Which backend?".to_owned(),
11971            String::new(),
11972            Vec::new(),
11973        );
11974        questions.put(&mut task_question).unwrap();
11975        task.block(vec![task_question.id.clone()], None);
11976        queue.put(&mut task).unwrap();
11977
11978        let mut run_question = ask::Question::new(
11979            "20260101-000000-run1".to_owned(),
11980            "review".to_owned(),
11981            "reviewer-1".to_owned(),
11982            "Run question".to_owned(),
11983            String::new(),
11984            Vec::new(),
11985        );
11986        questions.put(&mut run_question).unwrap();
11987
11988        // A question from another node whose `run` happens to equal this
11989        // task's id — the same field, filled in for an unrelated reason. Only
11990        // `crate::conduct::NODE` questions use `run` as a task id; this one
11991        // must never be touched by this reconciliation, even after release.
11992        let mut coincidental = ask::Question::new(
11993            task.id.clone(),
11994            "review".to_owned(),
11995            "reviewer-1".to_owned(),
11996            "Unrelated review question".to_owned(),
11997            String::new(),
11998            Vec::new(),
11999        );
12000        questions.put(&mut coincidental).unwrap();
12001
12002        reconcile_task_questions(&queue, &questions);
12003        assert!(questions.get(&task_question.id).unwrap().status.open());
12004        assert!(questions.get(&run_question.id).unwrap().status.open());
12005        assert!(questions.get(&coincidental.id).unwrap().status.open());
12006
12007        task.release();
12008        queue.put(&mut task).unwrap();
12009        reconcile_task_questions(&queue, &questions);
12010        assert_eq!(
12011            questions.get(&task_question.id).unwrap().status,
12012            ask::QuestionStatus::Abandoned
12013        );
12014        assert!(
12015            questions.get(&run_question.id).unwrap().status.open(),
12016            "run questions remain the run janitor's responsibility"
12017        );
12018        assert!(
12019            questions.get(&coincidental.id).unwrap().status.open(),
12020            "a non-conductor question must not be abandoned just because its \
12021             run id coincides with a task id"
12022        );
12023    }
12024
12025    #[test]
12026    fn a_freshly_started_running_task_is_never_stalled() {
12027        let dir = tempfile::tempdir().unwrap();
12028        let mut t = task();
12029        t.start("run-1".to_owned());
12030        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
12031        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
12032        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
12033    }
12034
12035    #[test]
12036    fn a_long_running_task_with_no_live_daemon_is_stalled() {
12037        let dir = tempfile::tempdir().unwrap();
12038        let mut t = task();
12039        t.start("run-1".to_owned());
12040        t.updated_at = Timestamp::now()
12041            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12042        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
12043        assert_eq!(
12044            stalled_tasks(
12045                &Queue::at(dir.path().join("q")),
12046                dir.path(),
12047                Timestamp::now()
12048            )
12049            .len(),
12050            0,
12051            "the task was never written to this queue"
12052        );
12053    }
12054
12055    #[test]
12056    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
12057        let dir = tempfile::tempdir().unwrap();
12058        let mut t = task();
12059        t.id = "20260903-080340-0167".to_owned();
12060        t.start("20260903-080619-01c2".to_owned());
12061        t.updated_at = Timestamp::now()
12062            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12063
12064        let mut status = Status::new();
12065        status.current = vec![Current {
12066            worker: None,
12067            task: t.id.clone(),
12068            run: "20260903-080619-01c2".to_owned(),
12069        }];
12070        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12071
12072        assert!(
12073            !is_stalled(&t, dir.path(), Timestamp::now()),
12074            "a live daemon's own heartbeat rules out stalled, however long the task has run"
12075        );
12076    }
12077
12078    /// Rewrite a task's `updated_at` on disk directly, bypassing
12079    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
12080    /// a fixture look like it has genuinely been `running` for a while.
12081    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
12082        let path = queue.path_of(id);
12083        let body = std::fs::read_to_string(&path).unwrap();
12084        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
12085        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
12086        v["updated_at"] = serde_json::Value::String(old.to_string());
12087        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
12088    }
12089
12090    #[test]
12091    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
12092        // The realistic `poll()` ordering, not `is_stalled` in isolation:
12093        // `reclaim_orphaned_running` runs first, on every poll, and settles
12094        // any `running` task whose claim it can actually take. For most
12095        // crashes that is immediate - a dead pid is proof enough for
12096        // `sweep_stale_claims` to drop the lock the same tick, and the very
12097        // next claim attempt succeeds. But a lock whose pid cannot be parsed
12098        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
12099        // `sweep_stale_claims`'s own doc), so the lock - and the claim
12100        // failure behind it - can legitimately outlive many polls. This is
12101        // exactly the gap `stalled_tasks` exists to surface well before that
12102        // six-hour sweep would: reclaim leaves the task `running`, and it
12103        // must still reach the conductor as stalled.
12104        let dir = tempfile::tempdir().unwrap();
12105        let queue = Queue::at(dir.path().join("queue"));
12106        let home = dir.path().join("home");
12107
12108        let mut t = task();
12109        t.id = "20260101-000001-lock".to_owned();
12110        t.start("run-1".to_owned());
12111        queue.put(&mut t).unwrap();
12112        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12113        std::fs::write(
12114            dir.path().join("queue").join(format!("{}.lock", t.id)),
12115            "not a pid",
12116        )
12117        .unwrap();
12118
12119        let now = Timestamp::now();
12120        assert!(
12121            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
12122            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
12123             and reclaim must leave the task alone"
12124        );
12125        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
12126
12127        let stalled = stalled_tasks(&queue, &home, now);
12128        assert_eq!(
12129            stalled.len(),
12130            1,
12131            "reclaim's inability to claim it yet must not hide it from the conductor"
12132        );
12133        assert_eq!(stalled[0].id, t.id);
12134    }
12135
12136    #[test]
12137    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
12138        let dir = tempfile::tempdir().unwrap();
12139        crate::run::set_home(dir.path().join("run-home"));
12140        let queue = Queue::at(dir.path().join("queue"));
12141        let home = dir.path().join("home");
12142        let questions = Questions::at(dir.path().join("questions"));
12143
12144        let mut t = task();
12145        t.id = "20260101-000003-dead".to_owned();
12146        t.start("missing-run".to_owned());
12147        queue.put(&mut t).unwrap();
12148        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12149
12150        // This is the real poll ordering: retain the deterministic stalled
12151        // input before a claim proves the owner is gone and reclaims it.
12152        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12153        assert_eq!(
12154            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
12155            [&t.id]
12156        );
12157        assert_eq!(
12158            reclaim_orphaned_running(&queue, 2, &Default::default()),
12159            [t.id.clone()]
12160        );
12161        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12162
12163        // Reclaim drops its guard before conductor decisions are applied, so
12164        // the decision for the captured stalled input has a real write path.
12165        crate::conduct::apply(
12166            &queue,
12167            &questions,
12168            &crate::conduct::Verdict {
12169                decisions: vec![crate::conduct::Decision {
12170                    id: t.id.clone(),
12171                    recovery: Some(crate::conduct::Recovery::Requeue),
12172                    ..crate::conduct::Decision::default()
12173                }],
12174            },
12175        )
12176        .unwrap();
12177        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12178    }
12179
12180    #[test]
12181    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
12182        let dir = tempfile::tempdir().unwrap();
12183        let queue = Queue::at(dir.path().join("queue"));
12184        let home = dir.path().join("home");
12185
12186        let mut fresh = task();
12187        fresh.id = "20260101-000001-aaaa".to_owned();
12188        fresh.start("run-1".to_owned());
12189        queue.put(&mut fresh).unwrap();
12190
12191        let mut old = task();
12192        old.id = "20260101-000002-bbbb".to_owned();
12193        old.start("run-2".to_owned());
12194        queue.put(&mut old).unwrap();
12195        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
12196
12197        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12198        assert_eq!(stalled.len(), 1);
12199        assert_eq!(stalled[0].id, old.id);
12200    }
12201
12202    #[test]
12203    fn queued_and_finished_task_views_partition_by_status() {
12204        let dir = tempfile::tempdir().unwrap();
12205        let queue = Queue::at(dir.path().join("queue"));
12206
12207        let mut queued = task();
12208        queued.id = "20260101-000001-aaaa".to_owned();
12209        queue.put(&mut queued).unwrap();
12210
12211        let mut failed = task();
12212        failed.id = "20260101-000002-bbbb".to_owned();
12213        failed.start("run-1".to_owned());
12214        failed.fail("gate red", 5);
12215        queue.put(&mut failed).unwrap();
12216
12217        let mut held = task();
12218        held.id = "20260101-000003-cccc".to_owned();
12219        held.hold_machine(None);
12220        queue.put(&mut held).unwrap();
12221
12222        let mut running = task();
12223        running.id = "20260101-000004-dddd".to_owned();
12224        running.start("run-2".to_owned());
12225        queue.put(&mut running).unwrap();
12226
12227        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
12228        assert_eq!(queued_ids, [queued.id.clone()]);
12229
12230        let mut finished_ids: Vec<String> =
12231            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
12232        finished_ids.sort_unstable();
12233        let mut want = vec![failed.id.clone(), held.id.clone()];
12234        want.sort_unstable();
12235        assert_eq!(finished_ids, want);
12236    }
12237
12238    #[test]
12239    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
12240        for short in [false, true] {
12241            let dir = tempfile::tempdir().unwrap();
12242            let queue = Queue::at(dir.path().join("queue"));
12243            let questions = ask::Questions::at(dir.path().join("questions"));
12244            let mut running = task();
12245            running.id = "20261013-192213-feb2".into();
12246            running.start("existing-run".into());
12247            queue.put(&mut running).unwrap();
12248            let mut middle = task();
12249            middle.id = "20261013-193611-ca5b".into();
12250            middle.block(
12251                vec![if short {
12252                    "feb2".into()
12253                } else {
12254                    running.id.clone()
12255                }],
12256                None,
12257            );
12258            queue.put(&mut middle).unwrap();
12259            let mut waiting = task();
12260            waiting.id = "20261013-202849-ee37".into();
12261            waiting.block(
12262                vec![if short {
12263                    "ca5b".into()
12264                } else {
12265                    middle.id.clone()
12266                }],
12267                Some("wait for implementation".into()),
12268            );
12269            queue.put(&mut waiting).unwrap();
12270            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
12271            let inv = crate::blockers::Inventory::load(&queue, &questions);
12272            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
12273            assert!(inv.stuck().is_empty());
12274            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12275            assert!(report.quarantined.is_empty());
12276            assert!(report.asked.is_empty());
12277            resolve_blockers(&queue, &questions);
12278            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12279            assert!(questions.list().is_empty());
12280            // Finishing the transitive prerequisite alone does not satisfy
12281            // the task's direct dependency.
12282            running.succeed();
12283            queue.put(&mut running).unwrap();
12284            resolve_blockers(&queue, &questions);
12285            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
12286            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12287            middle = queue.get(&middle.id).unwrap();
12288            middle.succeed();
12289            queue.put(&mut middle).unwrap();
12290            resolve_blockers(&queue, &questions);
12291            let after = queue.get(&waiting.id).unwrap();
12292            assert_eq!(after.status, TaskStatus::Queued);
12293            assert!(after.blocked_by.is_empty());
12294            assert_eq!(after.instruction, waiting.instruction);
12295        }
12296    }
12297
12298    #[test]
12299    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
12300        for future_schema in [false, true] {
12301            let name = "20261013-193611-ca5b";
12302            let mut future = task();
12303            future.id = name.into();
12304            future.schema = crate::queue::SCHEMA + 1;
12305            let contents = if future_schema {
12306                serde_json::to_string(&future).unwrap()
12307            } else {
12308                "corrupt".into()
12309            };
12310            let dir = tempfile::tempdir().unwrap();
12311            let queue = Queue::at(dir.path().join("queue"));
12312            let questions = ask::Questions::at(dir.path().join("questions"));
12313            let mut waiting = task();
12314            waiting.id = "20261013-202849-ee37".into();
12315            waiting.block(vec!["ca5b".into()], None);
12316            queue.put(&mut waiting).unwrap();
12317            std::fs::write(queue.path_of(name), contents).unwrap();
12318            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
12319            assert!(
12320                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
12321            );
12322            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12323            assert!(report.asked.is_empty());
12324            resolve_blockers(&queue, &questions);
12325            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12326            assert!(questions.list().is_empty());
12327        }
12328        let dir = tempfile::tempdir().unwrap();
12329        let queue = Queue::at(dir.path().join("queue"));
12330        let questions = ask::Questions::at(dir.path().join("questions"));
12331        let mut waiting = task();
12332        waiting.id = "20261013-202849-ee37".into();
12333        waiting.block(vec!["ca5b".into()], None);
12334        queue.put(&mut waiting).unwrap();
12335        let mut done = task();
12336        done.id = "20261013-193611-ca5b".into();
12337        done.succeed();
12338        queue.put(&mut done).unwrap();
12339        // An unreadable second match must not disappear from uniqueness
12340        // checks just because Queue::list skips it.
12341        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
12342        assert!(queue.get("ca5b").is_err());
12343        assert_eq!(
12344            crate::queue::dependency(&queue, &questions, "ca5b"),
12345            crate::queue::Dependency::Ambiguous
12346        );
12347        resolve_blockers(&queue, &questions);
12348        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12349        assert!(report.asked.is_empty());
12350        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12351        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
12352    }
12353
12354    #[test]
12355    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
12356        for held in [false, true] {
12357            for question in [false, true] {
12358                for reference in ["ca5b", "20261013-193611-ca5b"] {
12359                    let dir = tempfile::tempdir().unwrap();
12360                    let queue = Queue::at(dir.path().join("queue"));
12361                    let questions = ask::Questions::at(dir.path().join("questions"));
12362                    let mut prerequisite = task();
12363                    prerequisite.id = "20261013-193611-ca5b".into();
12364                    prerequisite.start("existing-run".into());
12365                    queue.put(&mut prerequisite).unwrap();
12366                    let mut waiting = task();
12367                    waiting.id = "20261013-202849-ee37".into();
12368                    if held {
12369                        waiting.hold_machine(Some("waiting for separate consent".into()));
12370                    }
12371                    queue.put(&mut waiting).unwrap();
12372                    let reason = "Deleting saved data requires separate owner consent";
12373                    crate::conduct::apply(
12374                        &queue,
12375                        &questions,
12376                        &crate::conduct::Verdict {
12377                            decisions: vec![crate::conduct::Decision {
12378                                id: waiting.id.clone(),
12379                                blocked_by: vec![reference.into()],
12380                                question: question.then(|| "May the saved data be deleted?".into()),
12381                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
12382                                reason: Some(reason.into()),
12383                                ..crate::conduct::Decision::default()
12384                            }],
12385                        },
12386                    )
12387                    .unwrap();
12388                    let before = queue.get(&waiting.id).unwrap();
12389                    if question {
12390                        assert_eq!(before.status, TaskStatus::Blocked);
12391                        let q = questions.get(&before.blocked_by[0]).unwrap();
12392                        assert_eq!(q.summary, "May the saved data be deleted?");
12393                        assert!(q.status.open());
12394                    } else {
12395                        assert_eq!(before.status, TaskStatus::Held);
12396                        let recorded_reason = before.hold_reason.as_deref().unwrap();
12397                        assert!(recorded_reason.starts_with(reason));
12398                        if held {
12399                            assert!(recorded_reason.contains("waiting for separate consent"));
12400                        }
12401                    }
12402                    prerequisite.succeed();
12403                    queue.put(&mut prerequisite).unwrap();
12404                    resolve_blockers(&queue, &questions);
12405                    let after = queue.get(&waiting.id).unwrap();
12406                    assert_eq!(after.status, before.status);
12407                    assert_eq!(after.blocked_by, before.blocked_by);
12408                    assert_eq!(after.hold_reason, before.hold_reason);
12409                    assert_eq!(after.instruction, waiting.instruction);
12410                    if question {
12411                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
12412                    }
12413                    assert!(
12414                        queue.next_runnable().is_none(),
12415                        "dependency completion is not consent"
12416                    );
12417                }
12418            }
12419        }
12420    }
12421
12422    #[test]
12423    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
12424        let dir = tempfile::tempdir().unwrap();
12425        let queue = Queue::at(dir.path().join("queue"));
12426        let questions = ask::Questions::at(dir.path().join("questions"));
12427
12428        let mut dep = task();
12429        dep.id = "20260101-000001-dep0".to_owned();
12430        dep.succeed();
12431        queue.put(&mut dep).unwrap();
12432
12433        let mut still_going = task();
12434        still_going.id = "20260101-000002-dep1".to_owned();
12435        queue.put(&mut still_going).unwrap();
12436
12437        let mut blocked = task();
12438        blocked.id = "20260101-000003-main".to_owned();
12439        blocked.block(
12440            vec![dep.id.clone(), still_going.id.clone()],
12441            Some("waits on both".to_owned()),
12442        );
12443        queue.put(&mut blocked).unwrap();
12444
12445        resolve_blockers(&queue, &questions);
12446
12447        let after = queue.get(&blocked.id).unwrap();
12448        assert_eq!(
12449            after.status,
12450            TaskStatus::Blocked,
12451            "one dependency is still outstanding"
12452        );
12453        assert_eq!(after.blocked_by, [still_going.id.clone()]);
12454    }
12455
12456    #[test]
12457    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
12458        let dir = tempfile::tempdir().unwrap();
12459        let queue = Queue::at(dir.path().join("queue"));
12460        let questions = ask::Questions::at(dir.path().join("questions"));
12461
12462        let mut q = crate::ask::Question::new(
12463            "20260101-000001-main".to_owned(),
12464            crate::conduct::NODE.to_owned(),
12465            "conduct".to_owned(),
12466            "Which backend?".to_owned(),
12467            String::new(),
12468            Vec::new(),
12469        );
12470        questions.put(&mut q).unwrap();
12471        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
12472            .unwrap();
12473        questions.put(&mut q).unwrap();
12474
12475        let mut blocked = task();
12476        blocked.id = "20260101-000001-main".to_owned();
12477        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
12478        queue.put(&mut blocked).unwrap();
12479
12480        resolve_blockers(&queue, &questions);
12481
12482        let after = queue.get(&blocked.id).unwrap();
12483        assert_eq!(
12484            after.status,
12485            TaskStatus::Queued,
12486            "the only blocker resolved"
12487        );
12488        assert_eq!(after.answers.len(), 1);
12489        assert_eq!(after.answers[0].question, "Which backend?");
12490        assert_eq!(after.answers[0].answer, "SQLite");
12491
12492        // And the run this task starts next is told about it.
12493        let instruction = instruction_for(&after);
12494        assert!(instruction.contains("Which backend?"));
12495        assert!(instruction.contains("SQLite"));
12496    }
12497
12498    #[test]
12499    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
12500        let dir = tempfile::tempdir().unwrap();
12501        let queue = Queue::at(dir.path().join("queue"));
12502        let questions = ask::Questions::at(dir.path().join("questions"));
12503
12504        let mut q = crate::ask::Question::new(
12505            "20260101-000001-main".to_owned(),
12506            crate::conduct::NODE.to_owned(),
12507            "conduct".to_owned(),
12508            "Is the setup done?".to_owned(),
12509            String::new(),
12510            Vec::new(),
12511        );
12512        q.abandon("no answer within 60s of asking");
12513        questions.put(&mut q).unwrap();
12514
12515        let mut blocked = task();
12516        blocked.id = "20260101-000001-main".to_owned();
12517        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
12518        queue.put(&mut blocked).unwrap();
12519
12520        resolve_blockers(&queue, &questions);
12521
12522        let after = queue.get(&blocked.id).unwrap();
12523        assert_eq!(
12524            after.status,
12525            TaskStatus::Held,
12526            "never left blocked on nothing"
12527        );
12528        assert!(!after.operator_held(), "a machine hold, for triage");
12529        assert!(
12530            after
12531                .hold_reason
12532                .as_deref()
12533                .unwrap_or_default()
12534                .contains("went unanswered")
12535        );
12536    }
12537
12538    #[test]
12539    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
12540        // Reproduces the reported bug (task 3958): a task held out of
12541        // attempts, blocked on a `crate::conduct` follow-up question, must
12542        // come back `held` once that question is answered - never `queued`,
12543        // whatever the answer said - or it silently re-enters the
12544        // competition queue with its attempts already exhausted.
12545        let dir = tempfile::tempdir().unwrap();
12546        let queue = Queue::at(dir.path().join("queue"));
12547        let questions = ask::Questions::at(dir.path().join("questions"));
12548
12549        let mut q = crate::ask::Question::new(
12550            "20260101-000001-main".to_owned(),
12551            crate::conduct::NODE.to_owned(),
12552            "conduct".to_owned(),
12553            "How should this be handled?".to_owned(),
12554            String::new(),
12555            Vec::new(),
12556        );
12557        questions.put(&mut q).unwrap();
12558        q.answer(crate::ask::Answer::Text(
12559            "leave it held, a human will look at it later".to_owned(),
12560        ))
12561        .unwrap();
12562        questions.put(&mut q).unwrap();
12563
12564        let mut held = task();
12565        held.id = "20260101-000001-main".to_owned();
12566        held.hold_machine(Some("out of attempts".to_owned()));
12567        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
12568        queue.put(&mut held).unwrap();
12569
12570        resolve_blockers(&queue, &questions);
12571
12572        let after = queue.get(&held.id).unwrap();
12573        assert_eq!(after.status, TaskStatus::Held);
12574        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
12575        assert_eq!(
12576            after.answers[0].answer,
12577            "leave it held, a human will look at it later"
12578        );
12579    }
12580
12581    #[test]
12582    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
12583        let dir = tempfile::tempdir().unwrap();
12584        let queue = Queue::at(dir.path().join("queue"));
12585        let questions = ask::Questions::at(dir.path().join("questions"));
12586        let mut dep = task();
12587        dep.id = "20260101-000001-gone".to_owned();
12588        queue.put(&mut dep).unwrap();
12589        let mut blocked = task();
12590        blocked.id = "20260101-000003-main".to_owned();
12591        blocked.block(vec![dep.id.clone()], None);
12592        queue.put(&mut blocked).unwrap();
12593
12594        // Claimed, so `remove` cannot rewrite it and the resolver must.
12595        let claim = queue.claim(&blocked.id).unwrap();
12596        queue.remove(&dep.id, false, &questions).unwrap();
12597        drop(claim);
12598        resolve_blockers(&queue, &questions);
12599
12600        let after = queue.get(&blocked.id).unwrap();
12601        assert_eq!(after.status, TaskStatus::Queued);
12602        assert!(after.blocked_by.is_empty());
12603    }
12604
12605    #[test]
12606    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
12607        // Reproduces the reported bug: a task blocked on a task id that was
12608        // removed (`magi task rm`, or deleted by hand) can never see that id
12609        // reach `Done`, so the ordinary per-id loop has nothing to notice and
12610        // would otherwise leave the task `blocked` forever with no way for an
12611        // operator to find out why.
12612        let dir = tempfile::tempdir().unwrap();
12613        let queue = Queue::at(dir.path().join("queue"));
12614        let questions = ask::Questions::at(dir.path().join("questions"));
12615
12616        let mut still_going = task();
12617        still_going.id = "20260101-000002-dep1".to_owned();
12618        queue.put(&mut still_going).unwrap();
12619
12620        let mut blocked = task();
12621        blocked.id = "20260101-000003-main".to_owned();
12622        blocked.block(
12623            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
12624            Some("waits on both".to_owned()),
12625        );
12626        queue.put(&mut blocked).unwrap();
12627
12628        resolve_blockers(&queue, &questions);
12629
12630        let after = queue.get(&blocked.id).unwrap();
12631        assert_eq!(
12632            after.status,
12633            TaskStatus::Held,
12634            "a missing dependency must not leave the task blocked forever"
12635        );
12636        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
12637        assert!(after.blocked_by.is_empty());
12638        let reason = after.hold_reason.as_deref().unwrap_or_default();
12639        assert!(
12640            reason.contains("20260101-000001-gone"),
12641            "the missing id must be named so an operator can tell what happened: {reason}"
12642        );
12643        assert!(
12644            reason.contains(&still_going.id),
12645            "the still-valid dependency must not silently vanish from the record: {reason}"
12646        );
12647    }
12648
12649    #[test]
12650    fn instruction_for_is_unchanged_without_any_answers() {
12651        let t = task();
12652        assert_eq!(instruction_for(&t), t.instruction);
12653    }
12654
12655    #[test]
12656    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
12657        let dir = tempfile::tempdir().unwrap();
12658        let q = Queue::at(dir.path().join("queue"));
12659        let src = dir.path().join("shot.png");
12660        std::fs::write(&src, "x").unwrap();
12661        let mut t = task();
12662        q.attach(&mut t, &[src]).unwrap();
12663        let paths = task_attachments(&q, &t).unwrap();
12664        assert_eq!(paths.len(), 1);
12665        assert!(paths[0].is_absolute() && paths[0].is_file());
12666        std::fs::remove_file(&paths[0]).unwrap();
12667        let err = task_attachments(&q, &t).unwrap_err().to_string();
12668        assert!(err.contains("shot.png"), "{err}");
12669    }
12670
12671    #[tokio::test]
12672    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
12673        let dir = tempfile::tempdir().unwrap();
12674        let queue_path = dir.path().join("queue");
12675        let queue = Queue::at(queue_path.clone());
12676        let mut t = task();
12677        t.source = Source::Agent {
12678            run: "originating-chat".into(),
12679            node: crate::queue::CHAT_NODE.into(),
12680        };
12681        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
12682            stage: "config-fetch",
12683            target: "origin/main".into(),
12684        });
12685        record_config_failure(&mut t, &fetch);
12686        t.hold_machine(Some(format!("{fetch:#}")));
12687        let fetch_key = t.chat_notice_due().unwrap();
12688        t.chat_notices.push(fetch_key.clone());
12689        queue.put(&mut t).unwrap();
12690
12691        let queue = Queue::at(queue_path);
12692        let mut t = queue.get(&t.id).unwrap();
12693        let a = dir.path().join("a.toml");
12694        let b = dir.path().join("b.toml");
12695        for (path, text, new_cause) in [
12696            (&a, "[graph", true),
12697            (&a, "[verify", false),
12698            (&a, "[graph]\nimplementers = 'invalid-type'", true),
12699            (&b, "[graph]\nimplementers = 'invalid-type'", true),
12700        ] {
12701            t.release_operator("test", None);
12702            std::fs::write(path, text).unwrap();
12703            let error = Config::discover_fetched(dir.path(), Some(path))
12704                .await
12705                .unwrap_err();
12706            record_config_failure(&mut t, &error);
12707            t.hold_machine(Some(format!("{error:#}")));
12708            let due = t.chat_notice_due();
12709            assert_eq!(due.is_some(), new_cause, "{error:#}");
12710            if let Some(key) = due {
12711                assert_ne!(key, fetch_key);
12712                t.chat_notices.push(key);
12713            }
12714        }
12715        t.succeed();
12716        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
12717    }
12718
12719    #[test]
12720    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
12721        let dir = tempfile::tempdir().unwrap();
12722        let queue_path = dir.path().join("queue");
12723        let queue = Queue::at(queue_path.clone());
12724        let mut t = task();
12725        t.source = crate::queue::Source::Agent {
12726            run: "originating-chat".into(),
12727            node: crate::queue::CHAT_NODE.into(),
12728        };
12729        let a = dir.path().join("a.png");
12730        let b = dir.path().join("b.png");
12731        std::fs::write(&a, "a").unwrap();
12732        std::fs::write(&b, "b").unwrap();
12733        queue.attach(&mut t, &[a, b]).unwrap();
12734        let paths = task_attachments(&queue, &t).unwrap();
12735        for path in &paths {
12736            std::fs::remove_file(path).unwrap();
12737        }
12738        let missing = task_attachments(&queue, &t).unwrap_err();
12739        t.attempts += 1;
12740        let reason = missing.to_string();
12741        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12742        let first = t.chat_notice_due().expect("first attachment notice");
12743        t.chat_notices.push(first.clone());
12744        queue.put(&mut t).unwrap();
12745
12746        let queue = Queue::at(queue_path.clone());
12747        let mut t = queue.get(&t.id).unwrap();
12748        assert!(t.chat_notice_due().is_none(), "restart does not replay");
12749        t.release_operator("test", None);
12750        t.attempts += 1;
12751        let missing = task_attachments(&queue, &t).unwrap_err();
12752        t.fail_startup_target(
12753            "startup-attachments",
12754            missing.name,
12755            "same missing attachment with regenerated wording",
12756            1,
12757        );
12758        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
12759
12760        std::fs::write(&paths[0], "restored").unwrap();
12761        t.release_operator("test", None);
12762        t.attempts += 1;
12763        let missing = task_attachments(&queue, &t).unwrap_err();
12764        let reason = missing.to_string();
12765        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12766        let second = t
12767            .chat_notice_due()
12768            .expect("different attachment must notify");
12769        assert_ne!(first, second);
12770        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
12771    }
12772
12773    #[test]
12774    fn resumed_instruction_is_unchanged_without_any_answers() {
12775        let t = task();
12776        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
12777    }
12778
12779    #[test]
12780    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
12781        let mut t = task();
12782        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12783        // The run's own instruction on disk predates the answer: it is the
12784        // plain original text `Runner::start` saved before the operator was
12785        // ever asked anything.
12786        let old = t.instruction.clone();
12787
12788        let refreshed = resumed_instruction(&old, &t);
12789        assert!(refreshed.starts_with(&old), "the original text is kept");
12790        assert!(refreshed.contains("Which backend?"));
12791        assert!(refreshed.contains("SQLite"));
12792    }
12793
12794    #[test]
12795    fn resumed_instruction_keeps_an_original_answers_heading() {
12796        let mut t = task();
12797        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
12798        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12799
12800        let refreshed = resumed_instruction(&t.instruction, &t);
12801
12802        assert!(
12803            refreshed.starts_with(&t.instruction),
12804            "an answers heading in the original instruction is not the appended block"
12805        );
12806        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
12807        assert!(refreshed.contains("Which backend?"));
12808        assert!(refreshed.contains("SQLite"));
12809
12810        let repeated = resumed_instruction(&refreshed, &t);
12811        assert_eq!(
12812            repeated, refreshed,
12813            "only the final appended block is refreshed"
12814        );
12815    }
12816
12817    #[test]
12818    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
12819        let mut t = task();
12820        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12821
12822        // A first resume appends the block; a second resume of the same run,
12823        // with no new answer in between, must reproduce exactly the same
12824        // text rather than appending the block a second time.
12825        let once = resumed_instruction(&t.instruction, &t);
12826        let twice = resumed_instruction(&once, &t);
12827        assert_eq!(once, twice);
12828        assert_eq!(once.matches("Which backend?").count(), 1);
12829
12830        // A later answer replaces the block wholesale rather than growing it.
12831        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
12832        let refreshed = resumed_instruction(&once, &t);
12833        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
12834        assert!(refreshed.contains("Which backend?"));
12835        assert!(refreshed.contains("Which cache?"));
12836    }
12837
12838    #[test]
12839    fn prepare_instruction_covers_all_three_starters() {
12840        let mut t = task();
12841        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12842
12843        // Start: a fresh run gets the task text plus every answer so far —
12844        // exactly `instruction_for`.
12845        assert_eq!(
12846            prepare_instruction(&Starter::Start, None, &t),
12847            Some(instruction_for(&t))
12848        );
12849
12850        // Resume: the run's prior instruction is refreshed with the answer,
12851        // not discarded and not left stale.
12852        let old = t.instruction.clone();
12853        assert_eq!(
12854            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
12855            Some(resumed_instruction(&old, &t))
12856        );
12857
12858        // Review: a review-only pass builds its own instruction from the
12859        // branch's history in `crate::graph`, with no task statement at all -
12860        // this boundary must leave it alone.
12861        assert_eq!(
12862            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
12863            None
12864        );
12865    }
12866
12867    #[test]
12868    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
12869        assert_eq!(
12870            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
12871            Starter::Review("magi/eba2/A".to_owned())
12872        );
12873    }
12874
12875    #[test]
12876    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
12877        assert_eq!(
12878            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
12879            Starter::Start,
12880            "a vanished review branch must not fall back to resuming the old run either"
12881        );
12882    }
12883
12884    #[test]
12885    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
12886        let mut t = task();
12887        t.start("old-run".to_owned());
12888        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
12889        t.release();
12890        let branch = t.review_branch.take();
12891        assert_eq!(
12892            choose_starter(branch.as_deref(), true, Some("old-run")),
12893            Starter::Review("magi/eba2/A".to_owned()),
12894            "a review wins over resuming the old run"
12895        );
12896    }
12897
12898    #[test]
12899    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
12900        assert_eq!(
12901            choose_starter(None, false, Some("some-run")),
12902            Starter::Resume("some-run".to_owned())
12903        );
12904        assert_eq!(choose_starter(None, false, None), Starter::Start);
12905    }
12906
12907    #[test]
12908    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
12909        let mut released = task();
12910        released.start("stalled-run".to_owned());
12911        released.requeue();
12912        let unfinished = (!released.fresh_start)
12913            .then(|| Some("stalled-run".to_owned()))
12914            .flatten();
12915        assert_eq!(
12916            choose_starter(None, false, unfinished.as_deref()),
12917            Starter::Start,
12918            "release keeps run history but must not resume it"
12919        );
12920        assert_eq!(released.runs, ["stalled-run"]);
12921    }
12922
12923    #[test]
12924    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
12925        let dir = tempfile::tempdir().unwrap();
12926        let queue = Queue::at(dir.path().join("queue"));
12927        let mut state = run_state(RunStatus::Blocked);
12928        state.merge_decision = Some(crate::merge_decision::Decision {
12929            question: "hold-inquiry".into(),
12930            target: crate::merge_decision::Target {
12931                pr: "https://example.test/pull/1".into(),
12932                head: "reviewed-head".into(),
12933                language: "en".into(),
12934            },
12935            choice: land::HOLD.into(),
12936            closed: false,
12937            replacement_run: None,
12938            replacement_pr: None,
12939        });
12940        let mut t = task();
12941        t.start(state.id.clone());
12942        settle_and_diagnose(
12943            &mut t,
12944            Verdict {
12945                status: RunStatus::Blocked,
12946                left_pr: true,
12947                quota_hit: false,
12948                parked: false,
12949                no_viable_candidates: false,
12950            },
12951            "held",
12952            2,
12953            &state,
12954        );
12955        queue.put(&mut t).unwrap();
12956        t.release_operator("chat", None);
12957        t.edit("revised".into(), "revised instruction".into())
12958            .unwrap();
12959        queue.put(&mut t).unwrap();
12960        drop(state);
12961        assert_eq!(
12962            queue
12963                .get(&t.id)
12964                .unwrap()
12965                .decision_effects
12966                .get("hold-inquiry"),
12967            Some(&format!("decision: {}", land::HOLD))
12968        );
12969    }
12970
12971    fn stopped_public_run(status: RunStatus) -> RunState {
12972        let mut state = run_state(status);
12973        state.driver_exited = true;
12974        state.config.graph.land = true;
12975        state.config.graph.review_rounds = 1;
12976        state.reviews = vec![review_round(1)];
12977        state.merge = Some(crate::run::MergeOutcome {
12978            mode: MergeMode::Pr,
12979            ok: false,
12980            detail: "landing stopped".into(),
12981            empty: false,
12982        });
12983        state.pr = Some(crate::run::PrRecord {
12984            url: "https://example.test/pull/1".into(),
12985            number: 1,
12986            state: "open".into(),
12987            checks: "red".into(),
12988            round: 1,
12989            rounds: 1,
12990            red_at_merge: Vec::new(),
12991        });
12992        state
12993    }
12994
12995    #[test]
12996    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
12997        for status in [RunStatus::Blocked, RunStatus::Gating] {
12998            let home = tempfile::tempdir().unwrap();
12999            let mut state = stopped_public_run(status);
13000            state.save_under(home.path()).unwrap();
13001            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
13002            assert!(!exhausted_review_budget(&state));
13003            let mut task = held_task_with(&state.id);
13004            task.release();
13005            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13006            assert_eq!(
13007                choose_starter(None, false, unfinished.as_deref()),
13008                Starter::Resume(state.id.clone())
13009            );
13010            let question = action_question(&state.id, resume_action(&state.id));
13011            assert_eq!(
13012                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13013                    state.clone()
13014                )),
13015                ActionDecision::Resume(state.id.clone())
13016            );
13017            // The control-plane command uses this same preflight before pinning.
13018            assert_eq!(
13019                crate::resume::validate(home.path(), &state.id).unwrap().id,
13020                state.id
13021            );
13022            let queue = Queue::at(home.path().join("queue"));
13023            let mut controlled = Task::new(
13024                "resume land".into(),
13025                state.instruction.clone(),
13026                state.repo.clone(),
13027                Source::Agent {
13028                    run: "talk".into(),
13029                    node: crate::queue::CHAT_NODE.into(),
13030                },
13031            );
13032            controlled.runs.push(state.id.clone());
13033            controlled.hold_machine(Some("land stopped".into()));
13034            queue.put(&mut controlled).unwrap();
13035            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13036            assert_eq!(resumed.status, TaskStatus::Queued);
13037            assert_eq!(
13038                resumed.resume_override.unwrap().pinned_run,
13039                Some(state.id.clone())
13040            );
13041            assert_eq!(resumed.attempts, 0);
13042        }
13043    }
13044
13045    #[test]
13046    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
13047        for review_rounds in [0, 1] {
13048            let home = tempfile::tempdir().unwrap();
13049            let mut state = run_state(RunStatus::Blocked);
13050            state.config.graph.review_rounds = review_rounds;
13051            if review_rounds > 0 {
13052                let mut review = review_round(1);
13053                review.clean = true;
13054                state.reviews = vec![review];
13055            }
13056            state.gate_ran = true;
13057            state.gate = vec![crate::run::CommandOutcome {
13058                command: "verify".into(),
13059                code: Some(1),
13060                output_tail: "gate failed after repair budget exhausted".into(),
13061                duration_ms: 0,
13062                resource_blocked: false,
13063            }];
13064            state.save_under(home.path()).unwrap();
13065            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13066            assert!(exhausted_review_budget(&state));
13067            let mut task = held_task_with(&state.id);
13068            task.release();
13069            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
13070            let question = action_question(&state.id, resume_action(&state.id));
13071            assert_ne!(
13072                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13073                    state.clone()
13074                )),
13075                ActionDecision::Resume(state.id.clone())
13076            );
13077            let error = crate::resume::validate(home.path(), &state.id)
13078                .unwrap_err()
13079                .to_string();
13080            assert!(!error.contains("review budget exhausted"), "{error}");
13081            assert!(
13082                error.contains(if review_rounds == 0 {
13083                    "review is disabled"
13084                } else {
13085                    "gate already ran"
13086                }),
13087                "{error}"
13088            );
13089
13090            // An unexecuted gate still has work to do with or without reviews.
13091            state.gate_ran = false;
13092            state.gate.clear();
13093            assert!(!exhausted_review_budget(&state));
13094            assert_eq!(
13095                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
13096                Some(state.id)
13097            );
13098        }
13099    }
13100
13101    #[test]
13102    fn resource_blocked_verification_resumes_the_same_run() {
13103        for (kind, stage) in [
13104            ("cache", "clean"),
13105            ("coordination", "clean"),
13106            ("cache", "review-e2e"),
13107            ("coordination", "no-reviews"),
13108            ("coordination", "handoff"),
13109        ] {
13110            let home = tempfile::tempdir().unwrap();
13111            let mut state = run_state(RunStatus::Blocked);
13112            state.config.graph.review_rounds = 1;
13113            let mut review = review_round(1);
13114            review.clean = true;
13115            state.reviews = vec![review];
13116            if stage == "review-e2e" {
13117                let review = &mut state.reviews[0];
13118                review.clean = false;
13119                review.blocking = 1;
13120                review.e2e = vec![crate::run::CommandOutcome {
13121                    command: "verify".into(),
13122                    code: None,
13123                    output_tail: "resource wait expired".into(),
13124                    duration_ms: 0,
13125                    resource_blocked: true,
13126                }];
13127            } else if stage == "no-reviews" {
13128                state.config.graph.review_rounds = 0;
13129                state.reviews.clear();
13130            } else if stage == "handoff" {
13131                // A completed final verification can hand off to the gate
13132                // even when the review still carries contested findings.
13133                let review = &mut state.reviews[0];
13134                review.clean = false;
13135                review.blocking = 1;
13136                review.e2e = vec![crate::run::CommandOutcome {
13137                    command: "verify".into(),
13138                    code: Some(0),
13139                    output_tail: String::new(),
13140                    duration_ms: 0,
13141                    resource_blocked: false,
13142                }];
13143            }
13144            state.gate_ran = false;
13145            state.resource_block = Some(crate::run::ResourceBlock {
13146                cause: crate::run::ResourceBlockCause::Other,
13147                node: if stage == "review-e2e" {
13148                    "review"
13149                } else {
13150                    "gate"
13151                }
13152                .into(),
13153                kind: kind.into(),
13154                detail: "resource wait expired".into(),
13155                at: jiff::Timestamp::now(),
13156            });
13157            state.save_under(home.path()).unwrap();
13158            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13159            assert!(!exhausted_review_budget(&state));
13160            let mut task = held_task_with(&state.id);
13161            task.release();
13162            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13163            assert_eq!(
13164                choose_starter(None, false, unfinished.as_deref()),
13165                Starter::Resume(state.id.clone())
13166            );
13167            let question = action_question(&state.id, resume_action(&state.id));
13168            assert_eq!(
13169                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13170                    state.clone()
13171                )),
13172                ActionDecision::Resume(state.id.clone())
13173            );
13174            assert_eq!(
13175                crate::resume::validate(home.path(), &state.id).unwrap().id,
13176                state.id
13177            );
13178            let queue = Queue::at(home.path().join("queue"));
13179            let mut controlled = Task::new(
13180                "resume verification".into(),
13181                state.instruction.clone(),
13182                state.repo.clone(),
13183                Source::Agent {
13184                    run: "talk".into(),
13185                    node: crate::queue::CHAT_NODE.into(),
13186                },
13187            );
13188            controlled.runs.push(state.id.clone());
13189            controlled.hold_machine(Some("verification resource unavailable".into()));
13190            queue.put(&mut controlled).unwrap();
13191            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13192            assert_eq!(resumed.status, TaskStatus::Queued);
13193            assert_eq!(
13194                resumed.resume_override.unwrap().pinned_run,
13195                Some(state.id.clone())
13196            );
13197            assert_eq!(resumed.attempts, 0);
13198
13199            // A genuinely unresolved final review still exhausts the budget.
13200            state.config.graph.review_rounds = 1;
13201            let mut unresolved = review_round(1);
13202            unresolved.blocking = 1;
13203            state.reviews = vec![unresolved];
13204            state.resource_block = None;
13205            state.save_under(home.path()).unwrap();
13206            assert!(exhausted_review_budget(&state));
13207            assert!(crate::resume::validate(home.path(), &state.id).is_err());
13208        }
13209    }
13210
13211    #[tokio::test]
13212    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
13213        if !crate::standalone_test(
13214            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
13215        ) {
13216            return;
13217        }
13218        let home = tempfile::tempdir().unwrap();
13219        let mut owner = stopped_public_run(RunStatus::Blocked);
13220        owner.save_under(home.path()).unwrap();
13221        let history = vec![owner.id.clone()];
13222        let repo = owner.repo.clone();
13223        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
13224        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
13225        let initial =
13226            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
13227        assert!(
13228            initial.is_pending(),
13229            "a busy record must not hold or resume the task"
13230        );
13231        owner.retired_to = Some("20260101-000001-bbbb".into());
13232        owner.save_under(home.path()).unwrap();
13233        drop(lock);
13234        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
13235            .await
13236            .expect("ownership lock released")
13237            .expect("read settled owner");
13238        assert!(
13239            result.is_none(),
13240            "the retired owner must not be resumed from a stale read"
13241        );
13242    }
13243
13244    #[tokio::test]
13245    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
13246        if !crate::standalone_test(
13247            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
13248        ) {
13249            return;
13250        }
13251        let home = tempfile::tempdir().unwrap();
13252        let mut owner = stopped_public_run(RunStatus::Blocked);
13253        let repo = tempfile::tempdir().unwrap();
13254        crate::git::git(repo.path(), &["init"]).await.unwrap();
13255        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
13256        owner.id = "20260101-000000-aaaa".into();
13257        owner.save_under(home.path()).unwrap();
13258        let mut successor = run_state(RunStatus::Blocked);
13259        successor.id = "20260101-000001-bbbb".into();
13260        successor.save_under(home.path()).unwrap();
13261        let runs = vec![owner.id.clone(), successor.id.clone()];
13262        assert_eq!(
13263            public_resume_owner(home.path(), &runs, &owner.repo)
13264                .await
13265                .unwrap()
13266                .unwrap()
13267                .id,
13268            owner.id
13269        );
13270        let subdir = owner.repo.join("nested");
13271        std::fs::create_dir(&subdir).unwrap();
13272        assert_eq!(
13273            public_resume_owner(home.path(), &runs, &subdir)
13274                .await
13275                .unwrap()
13276                .unwrap()
13277                .id,
13278            owner.id
13279        );
13280        #[cfg(unix)]
13281        {
13282            let alias = home.path().join("repo-alias");
13283            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
13284            assert_eq!(
13285                public_resume_owner(home.path(), &runs, &alias.join("nested"))
13286                    .await
13287                    .unwrap()
13288                    .unwrap()
13289                    .id,
13290                owner.id
13291            );
13292        }
13293        let different = tempfile::tempdir().unwrap();
13294        crate::git::git(different.path(), &["init"]).await.unwrap();
13295        assert!(
13296            public_resume_owner(home.path(), &runs, different.path())
13297                .await
13298                .is_err()
13299        );
13300        std::fs::remove_file(
13301            home.path()
13302                .join("runs")
13303                .join(&successor.id)
13304                .join("run.json"),
13305        )
13306        .unwrap();
13307        assert!(
13308            public_resume_owner(home.path(), &runs, &owner.repo)
13309                .await
13310                .is_err()
13311        );
13312    }
13313
13314    #[test]
13315    fn an_ordinary_release_keeps_a_resumable_run_available() {
13316        let mut released = task();
13317        released.start("stalled-run".to_owned());
13318        released.release();
13319        let unfinished = (!released.fresh_start)
13320            .then(|| Some("stalled-run".to_owned()))
13321            .flatten();
13322        assert_eq!(
13323            choose_starter(None, false, unfinished.as_deref()),
13324            Starter::Resume("stalled-run".to_owned()),
13325            "manual release must preserve the normal resume path"
13326        );
13327    }
13328
13329    #[test]
13330    fn resume_refusals_explain_admission_without_changing_task_or_run() {
13331        use crate::handover::{ResumeRefusal, resume_refusal_under};
13332        let home = tempfile::tempdir().unwrap();
13333        let mut exhausted = run_state(RunStatus::Blocked);
13334        exhausted.driver_exited = true;
13335        exhausted.config.graph.review_rounds = 3;
13336        exhausted.reviews = (1..=3).map(review_round).collect();
13337        for refusal in [
13338            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
13339            ResumeRefusal::Status(RunStatus::Ready),
13340            ResumeRefusal::Released("20261022-000000-aaaa".into()),
13341            ResumeRefusal::Retired("retirement-successor".into()),
13342            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
13343        ] {
13344            let mut state = exhausted.clone();
13345            let expected = match refusal {
13346                ResumeRefusal::Status(_) => {
13347                    state.status = RunStatus::Ready;
13348                    "status `ready`"
13349                }
13350                ResumeRefusal::Released(ref target) => {
13351                    state.released_to = Some(target.clone());
13352                    "execution was released"
13353                }
13354                ResumeRefusal::Retired(ref target) => {
13355                    state.retired_to = Some(target.clone());
13356                    "execution was retired"
13357                }
13358                ResumeRefusal::OwnershipTransferred(ref target) => {
13359                    state.pr_taken_over_by = Some(target.clone());
13360                    "PR ownership was transferred"
13361                }
13362                _ => "review budget exhausted (3/3 rounds used)",
13363            };
13364            assert_eq!(
13365                resume_refusal_under(&state, Some(home.path())),
13366                Some(refusal.clone())
13367            );
13368            assert_eq!(
13369                refusal.successor(),
13370                state
13371                    .released_to
13372                    .as_deref()
13373                    .or(state.retired_to.as_deref())
13374                    .or(state.pr_taken_over_by.as_deref())
13375            );
13376            state.save_under(home.path()).unwrap();
13377            let queue = Queue::at(home.path().join("queue"));
13378            let mut task = Task::new(
13379                "retained implementation".into(),
13380                state.instruction.clone(),
13381                state.repo.clone(),
13382                Source::Agent {
13383                    run: "talk".into(),
13384                    node: crate::queue::CHAT_NODE.into(),
13385                },
13386            );
13387            task.runs.push(state.id.clone());
13388            task.hold_machine(Some("stopped".into()));
13389            queue.put(&mut task).unwrap();
13390            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
13391            let before_run = serde_json::to_value(&state).unwrap();
13392            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
13393                .unwrap_err()
13394                .to_string();
13395            assert!(error.contains(expected), "{error}");
13396            assert!(!error.contains("only a stalled or blocked"), "{error}");
13397            if matches!(refusal, ResumeRefusal::Status(_)) {
13398                assert!(
13399                    error.contains("is final; there is nothing left to resume"),
13400                    "{error}"
13401                );
13402            }
13403            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
13404                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
13405                assert!(error.contains("review-only successor with a new review budget"));
13406                assert!(error.contains("does not resume this run"));
13407            }
13408            for target in [
13409                &state.released_to,
13410                &state.retired_to,
13411                &state.pr_taken_over_by,
13412            ]
13413            .into_iter()
13414            .flatten()
13415            {
13416                let short = if state.retired_to.as_ref() == Some(target) {
13417                    target.as_str()
13418                } else {
13419                    crate::run::short_of(target)
13420                };
13421                assert!(
13422                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
13423                    "{error}"
13424                );
13425                if short != target {
13426                    assert!(!error.contains(target), "full successor id leaked: {error}");
13427                }
13428            }
13429            assert_eq!(
13430                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
13431                before_task
13432            );
13433            assert_eq!(
13434                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
13435                    .unwrap(),
13436                before_run
13437            );
13438            let question = action_question(&state.id, resume_action(&state.id));
13439            for phrases in [&PHRASES_EN, &PHRASES_JA] {
13440                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
13441                    RunState::load_under(id, home.path())
13442                });
13443                let ActionDecision::Refuse(detail) = decision else {
13444                    panic!(
13445                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
13446                        state.id,
13447                        home.path().display()
13448                    );
13449                };
13450                assert!(detail.contains(expected), "{detail}");
13451            }
13452        }
13453        // Preserve predicate ordering, while keeping every recorded destination visible.
13454        exhausted.status = RunStatus::Ready;
13455        exhausted.released_to = Some("released".into());
13456        exhausted.retired_to = Some("retired".into());
13457        exhausted.pr_taken_over_by = Some("owner".into());
13458        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
13459        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
13460        let detail = reason.diagnostic(&exhausted);
13461        for target in ["released", "retired", "owner"] {
13462            assert!(detail.contains(&format!("magi show {target}")));
13463        }
13464    }
13465
13466    #[test]
13467    fn resume_action_ignores_question_checkpoints_in_another_home() {
13468        crate::run::pin_test_home();
13469        let home = tempfile::tempdir().unwrap();
13470        let mut state = run_state(RunStatus::Blocked);
13471        // The private directory reserves this fixture's identity even while
13472        // other tests write questions into the process-wide store.
13473        state.id = format!(
13474            "resume-context-{}",
13475            home.path().file_name().unwrap().to_str().unwrap()
13476        );
13477        state.driver_exited = true;
13478        state.config.graph.review_rounds = 1;
13479        state.reviews = vec![review_round(1)];
13480        state.save_under(home.path()).unwrap();
13481        let task = held_task_with(&state.id);
13482        let answer = action_question(&state.id, resume_action(&state.id));
13483        let mut checkpoint = approval_question(&state.id);
13484        let foreign = Questions::open();
13485        foreign.put(&mut checkpoint).unwrap();
13486        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
13487        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13488            RunState::load_under(id, home.path())
13489        });
13490        let matching: Vec<_> = foreign
13491            .list()
13492            .into_iter()
13493            .filter(|q| q.run == state.id && q.status.open())
13494            .collect();
13495        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
13496        assert!(
13497            matches!(decision, ActionDecision::Refuse(_)),
13498            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
13499            state.id,
13500            home.path().display(),
13501            crate::run::test_home().display()
13502        );
13503        assert_eq!(
13504            refusal,
13505            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
13506        );
13507        let local = Questions::at(home.path().join("questions"));
13508        for status in [
13509            ask::QuestionStatus::Open,
13510            ask::QuestionStatus::Answered,
13511            ask::QuestionStatus::Abandoned,
13512        ] {
13513            let mut question = checkpoint.clone();
13514            match status {
13515                ask::QuestionStatus::Open => {}
13516                ask::QuestionStatus::Answered => {
13517                    question
13518                        .answer(ask::Answer::Choice(question.choices[0].clone()))
13519                        .unwrap();
13520                }
13521                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
13522            }
13523            local.put(&mut question).unwrap();
13524            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13525                RunState::load_under(id, home.path())
13526            });
13527            if status.open() {
13528                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
13529            } else {
13530                assert!(
13531                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
13532                    "status={status:?}, decision={decision:?}"
13533                );
13534            }
13535        }
13536    }
13537
13538    #[test]
13539    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
13540        let home = tempfile::tempdir().unwrap();
13541        let mut state = run_state(RunStatus::Stalled);
13542        state.id = format!(
13543            "resume-driver-{}",
13544            home.path().file_name().unwrap().to_str().unwrap()
13545        );
13546        state.driver_claimed = Some(false);
13547        state.save_under(home.path()).unwrap();
13548        let task = held_task_with(&state.id);
13549        let question = action_question(&state.id, resume_action(&state.id));
13550        let decide = || {
13551            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
13552                RunState::load_under(id, home.path())
13553            })
13554        };
13555        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
13556        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
13557        assert_eq!(
13558            decide(),
13559            ActionDecision::Refuse("run already has a live driver".into())
13560        );
13561        drop(lease);
13562        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
13563    }
13564
13565    #[test]
13566    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
13567        let home = tempfile::tempdir().unwrap();
13568        let mut state = run_state(RunStatus::Blocked);
13569        state.driver_exited = true;
13570        state.config.graph.review_rounds = 1;
13571        state.reviews = vec![review_round(1)];
13572        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
13573        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
13574            let mut saved = state.clone();
13575            match checkpoint {
13576                "publication" => saved.pr_publication_pending = true,
13577                "approval" => {
13578                    saved.land_approval = Some(crate::run::LandApproval {
13579                        question: "approval".into(),
13580                        head: "head".into(),
13581                    })
13582                }
13583                "armed" => saved.land_armed_head = Some("head".into()),
13584                "landing" => saved.status = RunStatus::Landing,
13585                _ => {
13586                    let mut question = ask::Question::new(
13587                        saved.id.clone(),
13588                        "review".into(),
13589                        "review-1".into(),
13590                        "continue?".into(),
13591                        String::new(),
13592                        vec!["continue".into()],
13593                    );
13594                    ask::Questions::at(home.path().join("questions"))
13595                        .put(&mut question)
13596                        .unwrap();
13597                }
13598            }
13599            saved.save_under(home.path()).unwrap();
13600            assert!(
13601                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
13602                "{checkpoint}"
13603            );
13604            assert!(
13605                crate::resume::validate(home.path(), &saved.id).is_ok(),
13606                "{checkpoint}"
13607            );
13608        }
13609    }
13610
13611    #[test]
13612    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
13613        let mut state = run_state(RunStatus::Blocked);
13614        state.config.graph.review_rounds = 3;
13615        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
13616        assert!(exhausted_review_budget(&state));
13617
13618        // One round still unused: resuming can still ask a reviewer something.
13619        state.reviews.pop();
13620        assert!(!exhausted_review_budget(&state));
13621
13622        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
13623        // count: only a `Blocked` run re-enters the review loop on resume.
13624        let mut stalled = run_state(RunStatus::Stalled);
13625        stalled.config.graph.review_rounds = 1;
13626        stalled.reviews = vec![review_round(1)];
13627        assert!(!exhausted_review_budget(&stalled));
13628    }
13629
13630    fn review_round(round: usize) -> crate::run::ReviewRound {
13631        crate::run::ReviewRound {
13632            round,
13633            head: "deadbeef".to_owned(),
13634            verified_head: None,
13635            verified_at: None,
13636            reviews: Vec::new(),
13637            e2e: Vec::new(),
13638            verify_retried: false,
13639            e2e_deferred: false,
13640            e2e_defer_reason: None,
13641            fix: None,
13642            blocking: 0,
13643            answered: 1,
13644            expected: 1,
13645            clean: false,
13646            progressed: true,
13647            vote_split: false,
13648            reconsideration: Vec::new(),
13649            verdict: None,
13650        }
13651    }
13652
13653    #[test]
13654    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
13655        let mut run = RunState::new(
13656            PathBuf::from("/repo"),
13657            "main".to_owned(),
13658            "abc1234def".to_owned(),
13659            "add retries".to_owned(),
13660            Config::default(),
13661        );
13662        run.status = RunStatus::Judging;
13663        run.parked = true;
13664        let mut task = Task::new(
13665            "add retries".to_owned(),
13666            "add retries".to_owned(),
13667            PathBuf::from("/repo"),
13668            crate::queue::Source::Human,
13669        );
13670        task.status = TaskStatus::Failed;
13671        task.runs = vec![run.id.clone()];
13672        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
13673        assert!(with(&task, &run), "parked after judging is the case");
13674        let mut parked_task = task.clone();
13675        parked_task.status = TaskStatus::Parked;
13676        assert!(with(&parked_task, &run), "the Parked status is the case");
13677
13678        let mut not_parked = run.clone();
13679        not_parked.parked = false;
13680        not_parked.status = RunStatus::Stalled;
13681        assert!(!with(&task, &not_parked), "a stall is the conductor's");
13682
13683        let mut fresh = task.clone();
13684        fresh.fresh_start = true;
13685        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
13686
13687        let mut review = task.clone();
13688        review.review_branch = Some("magi/x/A".to_owned());
13689        assert!(!with(&review, &run), "review is ranked before resume");
13690
13691        let mut held = task.clone();
13692        held.status = TaskStatus::Held;
13693        assert!(!with(&held, &run), "a hold stays visible to the conductor");
13694
13695        let mut released = run.clone();
13696        released.released_to = Some("20260901-000000-new1".to_owned());
13697        assert!(!with(&task, &released), "nothing left to resume into");
13698
13699        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
13700            "unreadable"
13701        )));
13702    }
13703
13704    #[test]
13705    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
13706        let mut released = RunState::new(
13707            PathBuf::from("/repo"),
13708            "main".to_owned(),
13709            "abc1234def".to_owned(),
13710            "add retries".to_owned(),
13711            Config::default(),
13712        );
13713        released.status = RunStatus::Blocked;
13714        assert_eq!(
13715            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13716            Some(released.id.clone())
13717        );
13718        released.released_to = Some("20260901-000000-new1".to_owned());
13719        assert_eq!(
13720            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13721            None,
13722            "there is nothing left to resume it into"
13723        );
13724    }
13725
13726    #[test]
13727    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
13728        // Mirrors the failure this exists to close: a task's last run ended
13729        // `Blocked` with the review budget spent, `crate::conduct` chose
13730        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
13731        // evidence), and without this check `attempt` would go on treating
13732        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
13733        // review loop iterates zero times over an already-spent budget, so
13734        // the resumed run settles right back to `Blocked` having asked nobody
13735        // anything, and `Requeue`'s promised fresh competition never happens.
13736        let mut exhausted = RunState::new(
13737            PathBuf::from("/repo"),
13738            "main".to_owned(),
13739            "abc1234def".to_owned(),
13740            "add retries".to_owned(),
13741            Config::default(),
13742        );
13743        exhausted.status = RunStatus::Blocked;
13744        exhausted.config.graph.review_rounds = 1;
13745        exhausted.reviews = vec![review_round(1)];
13746
13747        assert_eq!(
13748            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
13749            None,
13750            "an exhausted `Blocked` run must not be offered as resumable"
13751        );
13752
13753        // A `Blocked` run with rounds still unused is genuinely worth
13754        // resuming, and must still be found.
13755        let mut has_budget_left = RunState::new(
13756            PathBuf::from("/repo"),
13757            "main".to_owned(),
13758            "abc1234def".to_owned(),
13759            "add retries".to_owned(),
13760            Config::default(),
13761        );
13762        has_budget_left.status = RunStatus::Blocked;
13763        has_budget_left.config.graph.review_rounds = 3;
13764        has_budget_left.reviews = vec![review_round(1)];
13765
13766        assert_eq!(
13767            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
13768                Ok(has_budget_left.clone())
13769            }),
13770            Some(has_budget_left.id.clone())
13771        );
13772    }
13773
13774    #[test]
13775    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
13776        let mut run = RunState::new(
13777            PathBuf::from("/repo"),
13778            "main".to_owned(),
13779            "abc1234def".to_owned(),
13780            "add retries".to_owned(),
13781            Config::default(),
13782        );
13783        run.status = RunStatus::Blocked;
13784        run.config.graph.review_rounds = 1;
13785        run.reviews = vec![review_round(1)];
13786        run.pr_publication_pending = true;
13787        assert_eq!(
13788            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
13789            Some(run.id.clone()),
13790            "a spent review budget must not turn a failed publication into a re-competition"
13791        );
13792    }
13793
13794    #[test]
13795    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
13796        let mut task = Task::new(
13797            "recover work".into(),
13798            "recover work".into(),
13799            PathBuf::from("/repo"),
13800            crate::queue::Source::Human,
13801        );
13802        let mut history = std::collections::BTreeMap::new();
13803        for index in 0..8 {
13804            let mut run = run_state(RunStatus::Blocked);
13805            run.id = format!("20260101-000000-{index:04}");
13806            run.base_commit = format!("upstream-{index}");
13807            // Seven empty newer attempts must not erase the old recovery owner.
13808            if index > 0 {
13809                run.candidates.clear();
13810            }
13811            task.runs.extend([run.id.clone(), run.id.clone()]);
13812            history.insert(run.id.clone(), run);
13813            task.requeue();
13814        }
13815        let check = |task: &Task, starter: &Starter, limit| {
13816            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
13817        };
13818        assert!(
13819            check(&task, &Starter::Start, 8)
13820                .unwrap()
13821                .contains("8 unretired")
13822        );
13823        assert!(check(&task, &Starter::Start, 9).is_none());
13824        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
13825        task.release_operator("owner", None);
13826        assert_eq!(task.attempts, 0);
13827        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13828        assert!(check(&restored, &Starter::Start, 8).is_some());
13829        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
13830        assert!(check(&restored, &Starter::Start, 0).is_none());
13831    }
13832
13833    #[test]
13834    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
13835        let tmp = tempfile::tempdir().unwrap();
13836        let mut task = Task::new(
13837            "recover selected PR".into(),
13838            "preserve implementation".into(),
13839            tmp.path().join("repo"),
13840            crate::queue::Source::Human,
13841        );
13842        let mut failed = run_state(RunStatus::Failed);
13843        failed.id = "20260101-000000-fail".into();
13844        failed.candidates.clear();
13845        failed.prep_complete = Some(false);
13846        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
13847        failed.startup = Some(crate::run::Startup {
13848            kind: "pr-recovery".into(),
13849            branch: Some("selected-public-head".into()),
13850            stage: "worktree-setup".into(),
13851            complete: false,
13852            failure: Some("setup modified a tracked file and failed".into()),
13853        });
13854        // Setup may fail before a candidate is recorded; its dirty worktree
13855        // still needs protection and consumes the independent retained bound.
13856        let worktree = failed.worktree_root().join("under-review");
13857        std::fs::create_dir_all(&worktree).unwrap();
13858        let retained_edit = worktree.join("implementation");
13859        std::fs::write(&retained_edit, "retained setup edit").unwrap();
13860        task.record_startup_failure(crate::run::StartupFailure {
13861            run: failed.id.clone(),
13862            stage: "worktree-setup".into(),
13863        });
13864        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13865        assert!(task.runs.is_empty() && task.passes.is_empty());
13866        assert_eq!(task.attempts, 0);
13867        let starter = Starter::Review("selected-public-head".into());
13868        assert!(
13869            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
13870                .unwrap()
13871                .contains("1 unretired")
13872        );
13873        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
13874        assert!(
13875            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
13876                .unwrap()
13877                .contains("Cannot verify")
13878        );
13879        // Older or mixed writers can link the same reservation in both lists.
13880        let mut mixed = task.clone();
13881        mixed.runs.push(failed.id.clone());
13882        mixed
13883            .startup_failures
13884            .push(task.startup_failures[0].clone());
13885        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
13886        failed.retired_to = Some("verified-recovery-owner".into());
13887        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
13888        assert!(
13889            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
13890                panic!("resuming the existing owner must not allocate a new attempt")
13891            })
13892            .is_none()
13893        );
13894        assert_eq!(
13895            std::fs::read_to_string(retained_edit).unwrap(),
13896            "retained setup edit"
13897        );
13898        assert!(task.runs.is_empty() && task.passes.is_empty());
13899        assert_eq!(task.attempts, 0);
13900    }
13901
13902    #[test]
13903    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
13904        let mut task = Task::new(
13905            "recover work".into(),
13906            "recover work".into(),
13907            PathBuf::from("/repo"),
13908            crate::queue::Source::Human,
13909        );
13910        let mut run = run_state(RunStatus::Superseded);
13911        run.candidates.clear();
13912        task.runs.push(run.id.clone());
13913        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
13914        run.retired_to = Some("authority".into());
13915        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13916        run.retired_to = None;
13917        run.released_to = Some("authority".into());
13918        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13919        assert!(
13920            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
13921                .unwrap()
13922                .contains("Cannot verify")
13923        );
13924        // Resuming an existing owner needs no new inventory or worktree budget.
13925        assert!(
13926            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
13927                panic!("resume must not load historical attempts")
13928            })
13929            .is_none()
13930        );
13931    }
13932
13933    #[test]
13934    fn retired_resume_requires_a_valid_same_repository_authority() {
13935        let mut source = run_state(RunStatus::Blocked);
13936        let mut empty = run_state(RunStatus::Blocked);
13937        empty.retired_to = Some(source.id.clone());
13938        let runs = vec![source.id.clone(), empty.id.clone()];
13939        let resolve = |source: &RunState, empty: &RunState| {
13940            unfinished_run_with(&runs, "fixture", |id| {
13941                if id == source.id {
13942                    Ok(source.clone())
13943                } else if id == empty.id {
13944                    Ok(empty.clone())
13945                } else {
13946                    bail!("unreadable authority")
13947                }
13948            })
13949        };
13950        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
13951        assert_eq!(
13952            choose_starter(None, false, resolve(&source, &empty).as_deref()),
13953            Starter::Resume(source.id.clone())
13954        );
13955        source.retired_to = Some(empty.id.clone());
13956        assert!(
13957            resolve(&source, &empty).is_none(),
13958            "cycles do not revive obsolete runs"
13959        );
13960        source.retired_to = None;
13961        source.repo = PathBuf::from("/another-repository");
13962        assert!(resolve(&source, &empty).is_none());
13963        source.repo = empty.repo.clone();
13964        source.released_to = Some("later".into());
13965        assert!(resolve(&source, &empty).is_none());
13966        empty.retired_to = Some("unlisted-run".into());
13967        assert!(resolve(&source, &empty).is_none());
13968    }
13969
13970    #[test]
13971    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
13972        // A task whose history holds an *older* run that still looks
13973        // resumable (say, a competition `Runner::review` was started
13974        // alongside after that older run went `Stalled`) and a *newest* run
13975        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
13976        // on this task must mean a fresh competition — falling back to the
13977        // stale, superseded `Stalled` run instead would resurrect history
13978        // nothing asked to revisit and silently defeat the requeue.
13979        let mut older_stalled = RunState::new(
13980            PathBuf::from("/repo"),
13981            "main".to_owned(),
13982            "abc1234def".to_owned(),
13983            "add retries".to_owned(),
13984            Config::default(),
13985        );
13986        older_stalled.status = RunStatus::Stalled;
13987
13988        let mut newest_exhausted = RunState::new(
13989            PathBuf::from("/repo"),
13990            "main".to_owned(),
13991            "abc1234def".to_owned(),
13992            "add retries".to_owned(),
13993            Config::default(),
13994        );
13995        newest_exhausted.status = RunStatus::Blocked;
13996        newest_exhausted.config.graph.review_rounds = 1;
13997        newest_exhausted.reviews = vec![review_round(1)];
13998
13999        assert_eq!(
14000            unfinished_run_with(
14001                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
14002                "t",
14003                |_| Ok(newest_exhausted.clone())
14004            ),
14005            None,
14006            "the newest run is exhausted, so nothing here is worth resuming - \
14007             least of all the older, already-superseded run"
14008        );
14009    }
14010
14011    #[test]
14012    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
14013        assert_eq!(
14014            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
14015                Err(anyhow::anyhow!("fixture is absent"))
14016            }),
14017            None
14018        );
14019    }
14020
14021    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
14022        let mut q = ask::Question::new(
14023            run.to_owned(),
14024            "implement".to_owned(),
14025            "impl-A".to_owned(),
14026            "continue?".to_owned(),
14027            String::new(),
14028            vec!["resume で続行する".to_owned(), "other".to_owned()],
14029        );
14030        q.actions.insert("resume で続行する".to_owned(), action);
14031        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
14032            .unwrap();
14033        q
14034    }
14035
14036    fn held_task_with(run: &str) -> Task {
14037        let mut t = task();
14038        t.runs = vec![run.to_owned()];
14039        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
14040        t
14041    }
14042
14043    fn resume_action(run: &str) -> ask::ChoiceAction {
14044        ask::ChoiceAction::Resume { run: run.into() }
14045    }
14046
14047    #[test]
14048    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
14049        let home = crate::run::test_home();
14050        for parked in [false, true] {
14051            let mut t = task();
14052            t.start("A".into());
14053            t.start("B".into());
14054            assert_eq!(t.runs, vec!["A", "B"]);
14055            t.start("A".into());
14056            let mut resumed = run_state(RunStatus::Blocked);
14057            resumed.id = "A".into();
14058            resumed.parked = parked;
14059            resumed.driver_exited = true;
14060            t.hold_machine(Some("resumed run stopped".into()));
14061            let q = action_question("A", resume_action("A"));
14062            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14063            assert_eq!(
14064                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
14065                    assert_eq!(id, "A");
14066                    Ok(resumed.clone())
14067                }),
14068                ActionDecision::Resume("A".into())
14069            );
14070            assert_eq!(
14071                action_standing(&t, &action_question("B", resume_action("B"))),
14072                ActionStanding::Stale
14073            );
14074            t.release_operator("cli", None);
14075            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
14076                assert_eq!(id, "A");
14077                Ok(resumed.clone())
14078            });
14079            assert_eq!(
14080                choose_starter(None, false, unfinished.as_deref()),
14081                Starter::Resume("A".into())
14082            );
14083            assert_eq!(t.runs, vec!["B", "A"]);
14084        }
14085    }
14086
14087    #[test]
14088    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
14089        let home = crate::run::test_home();
14090        let mut state = crate::land::tests::repair_state(true, true);
14091        state.status = RunStatus::Landing;
14092        state.parked = true;
14093        state.driver_exited = true;
14094        let mut q = ask::Question::new(
14095            state.id.clone(),
14096            land::APPROVAL_NODE.into(),
14097            "land".into(),
14098            "Merge?".into(),
14099            String::new(),
14100            vec![land::APPROVE.into(), land::HOLD.into()],
14101        );
14102        q.id = state.id.clone();
14103        state.land_approval = Some(crate::run::LandApproval {
14104            question: q.id.clone(),
14105            head: "current-head".into(),
14106        });
14107        assert!(land::upgrade_repair_choice(&mut q, &state));
14108        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14109        let mut task = held_task_with(&state.id);
14110        task.status = TaskStatus::Parked;
14111        assert_eq!(
14112            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14113            ActionDecision::Resume(state.id.clone())
14114        );
14115        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14116        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
14117        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
14118        assert_eq!(
14119            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14120            ActionDecision::Resume(state.id.clone()),
14121            "a repair answer newer than the manual hold resumes the existing owner"
14122        );
14123        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14124        for answered_at in [q.answered_at, None] {
14125            let mut older = q.clone();
14126            older.answered_at = answered_at;
14127            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
14128                panic!("a later manual hold must prevent dispatch")
14129            });
14130            let ActionDecision::Refuse(reason) = refused else {
14131                panic!("expected an actionable refusal, got {refused:?}");
14132            };
14133            assert!(reason.contains("later operator decision"));
14134            assert!(reason.contains(&format!("magi task release {}", task.id)));
14135        }
14136        task.operator_decided_at = None;
14137        let mut superseded = state.clone();
14138        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
14139        assert_eq!(
14140            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
14141            ActionDecision::Stale
14142        );
14143        for case in 1..4 {
14144            let mut changed = state.clone();
14145            match case {
14146                1 => changed.status = RunStatus::Blocked,
14147                2 => changed.released_to = Some("new-owner".into()),
14148                _ => changed.land_approval.as_mut().unwrap().head.clear(),
14149            }
14150            assert!(matches!(
14151                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
14152                ActionDecision::Refuse(_)
14153            ));
14154        }
14155        assert!(matches!(
14156            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
14157                "missing owner"
14158            )),
14159            ActionDecision::Refuse(_)
14160        ));
14161        task.runs.push("replacement".into());
14162        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14163        assert_eq!(
14164            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
14165                "old owner must not load"
14166            )),
14167            ActionDecision::Stale
14168        );
14169    }
14170
14171    #[test]
14172    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
14173        let mut state = crate::land::tests::repair_state(true, true);
14174        state.status = RunStatus::Landing;
14175        state.parked = true;
14176        state.driver_exited = true;
14177        let mut q = ask::Question::new(
14178            state.id.clone(),
14179            land::APPROVAL_NODE.into(),
14180            "land".into(),
14181            "Merge?".into(),
14182            String::new(),
14183            vec![land::APPROVE.into(), land::HOLD.into()],
14184        );
14185        q.id = state.id.clone();
14186        state.land_approval = Some(crate::run::LandApproval {
14187            question: q.id.clone(),
14188            head: "current-head".into(),
14189        });
14190        state.save().unwrap();
14191        land::upgrade_repair_choice(&mut q, &state);
14192        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14193        Questions::open().put(&mut q).unwrap();
14194        let tmp = tempfile::tempdir().unwrap();
14195        let queue = Queue::at(tmp.path().join("queue"));
14196        let mut task = held_task_with(&state.id);
14197        task.status = TaskStatus::Parked;
14198        queue.put(&mut task).unwrap();
14199        let empty = Arc::new(tokio::sync::Semaphore::new(0));
14200        let free = Arc::new(tokio::sync::Semaphore::new(1));
14201        assert!(matches!(
14202            claim_dispatch(&queue, &task, false, &empty, &free),
14203            Err(SkipReason::OrdinaryCapacity)
14204        ));
14205        assert!(matches!(
14206            claim_dispatch(&queue, &task, true, &free, &free),
14207            Err(SkipReason::CoolingDown)
14208        ));
14209        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
14210        assert!(claim.permit.is_some());
14211        assert!(matches!(
14212            claim_dispatch(&queue, &task, false, &free, &free),
14213            Err(SkipReason::ClaimUnavailable)
14214        ));
14215        drop(claim);
14216        Questions::open()
14217            .update(&q.id, |q| {
14218                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
14219                Ok(())
14220            })
14221            .unwrap();
14222        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
14223        assert!(claim.permit.is_none());
14224        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
14225    }
14226
14227    #[test]
14228    fn decide_action_resumes_only_the_latest_resumable_run() {
14229        let home = crate::run::test_home();
14230        let t = held_task_with("r1");
14231        let q = action_question("r1", resume_action("r1"));
14232        let load = |s: RunState| move |_: &str| Ok(s);
14233        assert_eq!(
14234            decide_action(
14235                &home,
14236                &t,
14237                &q,
14238                &PHRASES_EN,
14239                load(run_state(RunStatus::Blocked))
14240            ),
14241            ActionDecision::Resume("r1".into())
14242        );
14243        // Not the latest run of the task.
14244        let q_other = action_question("r1", resume_action("r0"));
14245        assert!(matches!(
14246            decide_action(
14247                &home,
14248                &t,
14249                &q_other,
14250                &PHRASES_EN,
14251                load(run_state(RunStatus::Blocked))
14252            ),
14253            ActionDecision::Refuse(_)
14254        ));
14255        // A finished run cannot make progress.
14256        assert!(matches!(
14257            decide_action(
14258                &home,
14259                &t,
14260                &q,
14261                &PHRASES_EN,
14262                load(run_state(RunStatus::Ready))
14263            ),
14264            ActionDecision::Refuse(_)
14265        ));
14266        // A released one either.
14267        let mut released = run_state(RunStatus::Blocked);
14268        released.released_to = Some("elsewhere".into());
14269        assert!(matches!(
14270            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
14271            ActionDecision::Refuse(_)
14272        ));
14273        // Unreadable state is a refusal, never a fresh competition.
14274        assert!(matches!(
14275            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
14276            ActionDecision::Refuse(_)
14277        ));
14278    }
14279
14280    #[test]
14281    fn decide_action_ignores_a_question_about_an_earlier_run() {
14282        let home = crate::run::test_home();
14283        let mut t = held_task_with("r1");
14284        t.runs.push("r2".to_owned());
14285        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14286        assert_eq!(
14287            decide_action(
14288                &home,
14289                &t,
14290                &action_question("r1", ask::ChoiceAction::Done),
14291                &PHRASES_EN,
14292                never
14293            ),
14294            ActionDecision::Stale
14295        );
14296    }
14297
14298    #[test]
14299    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
14300        let home = crate::run::test_home();
14301        let mut t = held_task_with("r1");
14302        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14303        assert_eq!(
14304            decide_action(
14305                &home,
14306                &t,
14307                &action_question("r1", ask::ChoiceAction::Requeue),
14308                &PHRASES_EN,
14309                never
14310            ),
14311            ActionDecision::Requeue
14312        );
14313        let done_q = action_question("r1", ask::ChoiceAction::Done);
14314        assert_eq!(
14315            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14316            ActionDecision::Done
14317        );
14318        t.mark_action_applied(&done_q.id);
14319        assert_eq!(
14320            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14321            ActionDecision::Skip
14322        );
14323
14324        // A plain answer (no action for that label) does nothing.
14325        let mut plain = action_question("r1", ask::ChoiceAction::Done);
14326        plain.actions.clear();
14327        assert_eq!(
14328            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
14329            ActionDecision::Skip
14330        );
14331        // A running task is left alone.
14332        let mut running = held_task_with("r1");
14333        running.status = TaskStatus::Running;
14334        assert_eq!(
14335            decide_action(
14336                &home,
14337                &running,
14338                &action_question("r1", ask::ChoiceAction::Done),
14339                &PHRASES_EN,
14340                never
14341            ),
14342            ActionDecision::Skip
14343        );
14344    }
14345
14346    #[test]
14347    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
14348        crate::run::pin_test_home();
14349        for legacy in [false, true] {
14350            let dir = tempfile::tempdir().unwrap();
14351            let queue = Queue::at(dir.path().join("queue"));
14352            let questions = Questions::at(dir.path().join("questions"));
14353            let run = "20260101-000000-hold";
14354            let mut task = held_task_with(run);
14355            task.status = TaskStatus::Parked;
14356            let mut q = ask::Question::new(
14357                run.into(),
14358                land::APPROVAL_NODE.into(),
14359                "land".into(),
14360                "Repair?".into(),
14361                String::new(),
14362                vec![land::REPAIR.into()],
14363            );
14364            q.actions.insert(land::REPAIR.into(), resume_action(run));
14365            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14366            // Deterministically order the answer before the actual manual hold.
14367            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14368            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
14369            questions.put(&mut q).unwrap();
14370            task.hold_manual(Some("Keep this PR paused".into()));
14371            if legacy {
14372                task.hold_source = None;
14373            }
14374            queue.put(&mut task).unwrap();
14375
14376            apply_task_choice_actions(&queue, &questions, dir.path());
14377            let after = queue.get(&task.id).unwrap();
14378            assert!(after.operator_held());
14379            assert_eq!(after.hold_source, task.hold_source);
14380            assert_eq!(after.operator_decided_at, task.operator_decided_at);
14381            assert_eq!(after.runs, task.runs);
14382            assert_eq!(after.instruction, task.instruction);
14383            assert!(after.resume_override.is_none());
14384            assert!(after.action_applied(&q.id));
14385            let reason = after.hold_reason.as_deref().unwrap();
14386            assert!(reason.starts_with("Keep this PR paused"));
14387            assert!(reason.contains("later operator decision"));
14388            assert!(reason.contains(&format!("magi task release {}", task.id)));
14389
14390            for recovery in [
14391                crate::conduct::Recovery::Review,
14392                crate::conduct::Recovery::Requeue,
14393            ] {
14394                crate::conduct::apply(
14395                    &queue,
14396                    &questions,
14397                    &crate::conduct::Verdict {
14398                        decisions: vec![crate::conduct::Decision {
14399                            id: task.id.clone(),
14400                            recovery: Some(recovery),
14401                            ..Default::default()
14402                        }],
14403                    },
14404                )
14405                .unwrap();
14406            }
14407            // Reconciliation is idempotent, and automatic recovery cannot
14408            // reopen this owner after it observes the rejected repair answer.
14409            apply_task_choice_actions(&queue, &questions, dir.path());
14410            let still_held = queue.get(&task.id).unwrap();
14411            assert!(still_held.operator_held());
14412            assert_eq!(still_held.hold_reason, after.hold_reason);
14413            assert_eq!(still_held.runs, task.runs);
14414            assert!(still_held.review_branch.is_none());
14415            assert!(!still_held.fresh_start);
14416            assert!(queue.next_runnable().is_none());
14417        }
14418    }
14419
14420    #[test]
14421    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
14422        for held in [false, true] {
14423            for retry in [false, true] {
14424                let dir = tempfile::tempdir().unwrap();
14425                let queue = Queue::at(dir.path().join("queue"));
14426                let questions = Questions::at(dir.path().join("questions"));
14427                let home = dir.path().join("home");
14428                let mut t = task();
14429                if held {
14430                    t.hold_machine(Some("driver state unknown".into()));
14431                }
14432                queue.put(&mut t).unwrap();
14433                let verdict = serde_json::from_value(serde_json::json!({
14434                    "decisions": [{
14435                        "id": t.id,
14436                        "question": "Driver state unknown; retry the checks or hold?",
14437                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
14438                        "actions": {
14439                            "daemon: recheck and retry": {"do": "requeue"},
14440                            "daemon: hold the task": {"do": "hold"}
14441                        }
14442                    }]
14443                }))
14444                .unwrap();
14445                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
14446                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14447                let mut q = questions.list().pop().unwrap();
14448                let choice = if retry {
14449                    "daemon: recheck and retry"
14450                } else {
14451                    "daemon: hold the task"
14452                };
14453                assert_eq!(q.actions.len(), 2);
14454                q.answer(ask::Answer::Choice(choice.into())).unwrap();
14455                questions.put(&mut q).unwrap();
14456
14457                // A Web answer does not remove the deputy's fresh lease.
14458                questions.beat(&q.id, ask::WaiterKind::Deputy);
14459                for _ in 0..2 {
14460                    resolve_blockers(&queue, &questions);
14461                    apply_task_choice_actions(&queue, &questions, &home);
14462                    let waiting = queue.get(&t.id).unwrap();
14463                    assert_eq!(waiting.status, TaskStatus::Blocked);
14464                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
14465                    assert!(waiting.answers.is_empty());
14466                    assert!(!waiting.action_applied(&q.id));
14467                    assert!(runnable(&queue).is_empty());
14468                    let free = Arc::new(tokio::sync::Semaphore::new(1));
14469                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
14470                }
14471                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14472
14473                // Releasing the blocker and applying the operation share one save.
14474                resolve_blockers(&queue, &questions);
14475                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14476                apply_task_choice_actions(&queue, &questions, &home);
14477                let after = queue.get(&t.id).unwrap();
14478                assert_eq!(
14479                    after.status,
14480                    if retry {
14481                        TaskStatus::Queued
14482                    } else {
14483                        TaskStatus::Held
14484                    }
14485                );
14486                assert!(after.action_applied(&q.id));
14487                assert_eq!(after.operator_held(), !retry);
14488                assert_eq!(after.answers.len(), 1);
14489
14490                // A later operator decision must not replay this answer.
14491                let mut changed = after;
14492                if retry {
14493                    changed.hold_manual(Some("later hold".into()));
14494                } else {
14495                    changed.release_operator("test", None);
14496                }
14497                let expected = changed.status;
14498                queue.put(&mut changed).unwrap();
14499                apply_task_choice_actions(&queue, &questions, &home);
14500                assert_eq!(queue.get(&t.id).unwrap().status, expected);
14501            }
14502        }
14503    }
14504
14505    #[test]
14506    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
14507        let dir = tempfile::tempdir().unwrap();
14508        let queue = Queue::at(dir.path().join("queue"));
14509        let questions = Questions::at(dir.path().join("questions"));
14510        let home = dir.path().join("home");
14511        let mut state = run_state(RunStatus::Blocked);
14512        state.id = "20260101-000000-act1".to_owned();
14513        state.save_under(&home).unwrap();
14514
14515        let mut t = held_task_with(&state.id);
14516        queue.put(&mut t).unwrap();
14517        let mut q = action_question(&state.id, resume_action(&state.id));
14518        questions.put(&mut q).unwrap();
14519
14520        apply_task_choice_actions(&queue, &questions, &home);
14521        let after = queue.get(&t.id).unwrap();
14522        assert_eq!(after.status, TaskStatus::Queued);
14523        assert!(!after.fresh_start);
14524        assert!(after.action_applied(&q.id));
14525        let pin = after.resume_override.clone().unwrap();
14526        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
14527        assert!(pin.forced);
14528
14529        // Held again later: the same answer does not release it a second time.
14530        let mut again = queue.get(&t.id).unwrap();
14531        again.hold_machine(Some("later".into()));
14532        queue.put(&mut again).unwrap();
14533        apply_task_choice_actions(&queue, &questions, &home);
14534        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14535    }
14536
14537    #[test]
14538    fn a_delivered_answer_is_still_acted_on_exactly_once() {
14539        let dir = tempfile::tempdir().unwrap();
14540        let queue = Queue::at(dir.path().join("queue"));
14541        let questions = Questions::at(dir.path().join("questions"));
14542        let home = dir.path().join("home");
14543        let mut state = run_state(RunStatus::Blocked);
14544        state.id = "20260101-000000-act2".to_owned();
14545        state.save_under(&home).unwrap();
14546
14547        let mut t = held_task_with(&state.id);
14548        queue.put(&mut t).unwrap();
14549        let mut q = action_question(&state.id, resume_action(&state.id));
14550        q.answer_delivered = true;
14551        questions.put(&mut q).unwrap();
14552
14553        // Delivered, and the agent then died: the task is still held, so the
14554        // chosen action applies.
14555        apply_task_choice_actions(&queue, &questions, &home);
14556        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14557        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
14558
14559        // Held again: the same answer does nothing a second time.
14560        let mut again = queue.get(&t.id).unwrap();
14561        again.hold_machine(Some("later".into()));
14562        queue.put(&mut again).unwrap();
14563        apply_task_choice_actions(&queue, &questions, &home);
14564        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14565    }
14566
14567    #[test]
14568    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
14569        let dir = tempfile::tempdir().unwrap();
14570        let queue = Queue::at(dir.path().join("queue"));
14571        let questions = Questions::at(dir.path().join("questions"));
14572        let home = dir.path().join("home");
14573        let mut state = run_state(RunStatus::Blocked);
14574        state.id = "20260101-000000-act3".to_owned();
14575        state.save_under(&home).unwrap();
14576        let mut t = held_task_with(&state.id);
14577        queue.put(&mut t).unwrap();
14578        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
14579        questions.put(&mut q).unwrap();
14580
14581        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
14582        apply_task_choice_actions(&queue, &questions, &home);
14583        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14584
14585        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14586        apply_task_choice_actions(&queue, &questions, &home);
14587        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14588    }
14589
14590    #[test]
14591    fn action_standing_tells_the_reasons_apart() {
14592        let mut t = held_task_with("r1");
14593        let q = action_question("r1", ask::ChoiceAction::Requeue);
14594        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14595        let mut plain = q.clone();
14596        plain.actions.clear();
14597        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
14598
14599        // Applied wins over everything, even a running task.
14600        t.mark_action_applied(&q.id);
14601        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
14602
14603        // A newer attempt running: the old question is Stale, not Busy.
14604        let mut t = held_task_with("r1");
14605        t.start("r2".to_owned());
14606        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
14607        // The same question about the latest run just waits.
14608        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
14609        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14610        t.status = TaskStatus::Blocked;
14611        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14612
14613        // A conductor question is keyed by the task, never stale.
14614        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
14615        c.node = crate::conduct::NODE.to_owned();
14616        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
14617        assert!(!ActionStanding::Busy.daemon_owns());
14618    }
14619
14620    #[test]
14621    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
14622        let dir = tempfile::tempdir().unwrap();
14623        let queue = Queue::at(dir.path().join("queue"));
14624        let questions = Questions::at(dir.path().join("questions"));
14625        let home = dir.path().join("home");
14626        let mut state = run_state(RunStatus::Blocked);
14627        state.id = "20260101-000000-act4".to_owned();
14628        state.save_under(&home).unwrap();
14629        let mut t = held_task_with(&state.id);
14630        t.status = TaskStatus::Running;
14631        queue.put(&mut t).unwrap();
14632        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
14633        q.cwd = Some(dir.path().display().to_string());
14634        questions.put(&mut q).unwrap();
14635
14636        // While the task runs the daemon will not act, so the waiter still
14637        // delivers the word to the dead asker's seat ...
14638        let running = queue.get(&t.id).unwrap();
14639        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
14640        assert!(matches!(
14641            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
14642            crate::waiter::Action::Deliver(_)
14643        ));
14644        // ... and the daemon waits while the task runs, then applies once.
14645        apply_task_choice_actions(&queue, &questions, &home);
14646        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14647        let mut back = queue.get(&t.id).unwrap();
14648        back.hold_machine(Some("later".into()));
14649        queue.put(&mut back).unwrap();
14650        apply_task_choice_actions(&queue, &questions, &home);
14651        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
14652        let mut again = queue.get(&t.id).unwrap();
14653        again.hold_machine(Some("again".into()));
14654        queue.put(&mut again).unwrap();
14655        apply_task_choice_actions(&queue, &questions, &home);
14656        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14657    }
14658}