Skip to main content

magi/
daemon.rs

1//! The unattended scheduler and independently leased task workers.
2//!
3//! The scheduler chooses tasks and execution lanes; a detached worker owns each
4//! queue claim, graph driver and outcome settlement. Replacing the scheduler
5//! reconstructs occupied slots from live worker jobs, without touching their
6//! attempts, passes or paid agent calls. Finite maintenance jobs follow the same
7//! lifetime rule. Explicit parking is durable control, never an upgrade step.
8//!
9//! # A crashed worker is legible
10//!
11//! A task is written `Running`, with its run id, before graph execution. The
12//! worker keeps its claim until the outcome is recorded. Recovery requires both
13//! no live worker reservation and an obtainable task claim, and settles the
14//! saved run through the same policy as a live finish. A scheduler's missing
15//! heartbeat alone is never evidence that a run died.
16//!
17//! # Retries are bounded
18//!
19//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
20//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
21//! exception is a run that ended `Stalled`: the panel collapsed because the
22//! agent CLIs hit their quota, which is a fact about the machine and not about
23//! the task, so it must not spend an attempt. Without that exception a quota
24//! outage would quietly hold the entire backlog, and the operator would come
25//! back to a reset quota and nothing left that the loop is willing to run.
26
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Mutex, MutexGuard};
31use std::time::Duration;
32
33use anyhow::{Context, Result, bail};
34use jiff::Timestamp;
35use serde::{Deserialize, Serialize};
36use tokio::sync::Notify;
37
38use crate::ask::{self, Questions};
39use crate::clean;
40use crate::conduct::Conductor;
41use crate::config::{BuildCache, Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{CompletionActor, CompletionContext, Queue, Task, TaskStatus};
46use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
47use crate::triage;
48
49/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
50pub const SCHEMA: u32 = 1;
51
52/// How often the status file is refreshed. A reader treats a status file older
53/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
54/// that a busy daemon is never mistaken for a dead one.
55pub const HEARTBEAT: Duration = Duration::from_secs(5);
56
57/// How old a heartbeat may be before a reader calls the daemon dead. Six
58/// missed beats: long enough to survive a slow filesystem, short enough that
59/// a crashed daemon is not still reported as running a task.
60///
61/// The single threshold every reader shares — the web UI's `/api/health` and
62/// `magi doctor` both call [`Reading::running`] rather than each comparing
63/// against their own copy of this number, so a crashed daemon cannot look
64/// alive on one screen and dead on another.
65pub const STALE_SECS: i64 = 30;
66
67/// Default queue poll interval.
68pub const POLL: Duration = Duration::from_secs(5);
69
70/// How old a claim has to be before startup sweeps it. Longer than any run
71/// this graph plausibly takes, so a sweep cannot pull a task out from under a
72/// daemon that is merely slow.
73pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
74
75/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
76/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
77///
78/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
79/// poll, by attempting the task's own claim: a dead pid is proof enough for
80/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
81/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
82/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
83/// age instead, since there is nothing else to check (see
84/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
85/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
86/// task `running` — see
87/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
88/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
89/// conductor well before the mechanical six-hour sweep would, and thirty
90/// minutes is comfortably below `STALE_CLAIM` while still being generous
91/// enough that a task merely late to publish its first [`HEARTBEAT`] is
92/// never mistaken for abandoned.
93pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
94
95/// What the loop is working on, for the status file.
96#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(default)]
98pub struct Current {
99    /// Worker reservation that produced this claim; absent on legacy drivers.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub worker: Option<String>,
102    /// Task id being run.
103    pub task: String,
104    /// Run id the task produced.
105    pub run: String,
106}
107
108/// The daemon's liveness, published to `<home>/daemon.json`.
109///
110/// This is the only interface between the loop and the web UI, which is why it
111/// carries `updated_at` as well as `started_at`: a reader cannot tell a
112/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
113/// can compare the heartbeat against the clock.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Status {
116    /// On-disk format version.
117    pub schema: u32,
118    /// Process id, so a human can find or kill the daemon.
119    pub pid: u32,
120    /// When this process started.
121    pub started_at: Timestamp,
122    /// Last heartbeat.
123    pub updated_at: Timestamp,
124    /// True when the queue has nothing runnable.
125    pub idle: bool,
126    /// Every task and run currently in flight. More than one entry means the
127    /// loop is driving more than one run at once — see
128    /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
129    /// nothing is running, so a reader never has to treat "no field" and "an
130    /// empty list" as two different kinds of idle.
131    pub current: Vec<Current>,
132    /// Tasks that reached a terminal status in this process.
133    pub completed: usize,
134    /// Queue polls since start, so a wedged loop shows up as a frozen count.
135    pub polls: u64,
136    /// Last completed candidate scan that started no tasks; absent otherwise.
137    #[serde(default)]
138    pub dispatch_wait: Option<DispatchWait>,
139    /// Effective startup capabilities of the question recovery loops.
140    #[serde(default)]
141    pub question_recovery: Option<crate::question_delivery::Recovery>,
142    /// Independent-worker control protocol supported by this scheduler.
143    #[serde(default)]
144    pub worker_protocol: Option<u32>,
145}
146
147impl Status {
148    /// A fresh, idle status for this process.
149    #[must_use]
150    pub fn new() -> Self {
151        let now = Timestamp::now();
152        Self {
153            schema: SCHEMA,
154            pid: std::process::id(),
155            started_at: now,
156            updated_at: now,
157            idle: true,
158            current: Vec::new(),
159            completed: 0,
160            polls: 0,
161            dispatch_wait: None,
162            question_recovery: None,
163            worker_protocol: Some(1),
164        }
165    }
166}
167
168impl Default for Status {
169    fn default() -> Self {
170        Self::new()
171    }
172}
173
174/// How the loop should behave.
175#[derive(Debug, Clone, Serialize, Deserialize)]
176#[serde(default)]
177pub struct Opts {
178    /// Repository used by tasks that name none.
179    pub repo: PathBuf,
180    /// Explicit `magi.toml`, instead of the discovered layer stack.
181    pub config: Option<PathBuf>,
182    /// Queue poll interval.
183    pub poll: Duration,
184    /// Attempts a task gets before it is held for a human.
185    pub max_attempts: usize,
186    /// Drain what is runnable now, then return, instead of waiting for more.
187    pub once: bool,
188    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
189    pub merge: Option<String>,
190    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
191    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
192    /// `None` resolves to [`crate::run::default_worktree_root`] - the
193    /// operator's real `~/wt/<repo>` - the same way a run with no
194    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
195    /// that does not own that directory (a test, an embedding that manages
196    /// worktrees itself) must set this, or every idle tick reclaims worktrees
197    /// out from under whoever actually does.
198    pub worktrees_root: Option<PathBuf>,
199}
200
201impl Default for Opts {
202    fn default() -> Self {
203        Self {
204            repo: PathBuf::from("."),
205            config: None,
206            poll: POLL,
207            max_attempts: 2,
208            once: false,
209            merge: None,
210            worktrees_root: None,
211        }
212    }
213}
214
215impl Opts {
216    fn absolute(&self) -> Result<Self> {
217        let mut opts = self.clone();
218        opts.repo = std::path::absolute(&opts.repo)?;
219        opts.config = opts
220            .config
221            .as_deref()
222            .map(std::path::absolute)
223            .transpose()?;
224        opts.worktrees_root = opts
225            .worktrees_root
226            .as_deref()
227            .map(std::path::absolute)
228            .transpose()?;
229        Ok(opts)
230    }
231}
232
233/// How many runs a plain `usize` from config may drive concurrently, floored
234/// at one. A `0` in a config file would otherwise stall the loop entirely -
235/// no runnable task could ever start - which is never what an operator who
236/// wrote `0` meant.
237fn max_concurrent(n: usize) -> usize {
238    n.max(1)
239}
240
241/// Where the status file lives.
242#[must_use]
243pub fn status_path() -> PathBuf {
244    crate::run::home().join("daemon.json")
245}
246
247/// Publish the status file for this process.
248pub fn write_status(status: &Status) -> Result<()> {
249    write_status_to(&status_path(), status)
250}
251
252/// Publish a status to an explicit path.
253///
254/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
255/// on every health poll and must never see a half-written one.
256pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
257    if let Some(parent) = path.parent() {
258        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
259    }
260    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
261    let tmp = path.with_extension("json.tmp");
262    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
263    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
264    Ok(())
265}
266
267/// Delete the status file. Called on the way out so a clean exit reads as
268/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
269pub fn clear_status() {
270    clear_status_at(&status_path());
271}
272
273/// Delete a status file at an explicit path, so the loop's teardown and
274/// [`clear_status`] cannot drift apart: the loop is handed the path it
275/// published to, and a test can watch a temp file disappear.
276fn clear_status_at(path: &Path) {
277    let _ = std::fs::remove_file(path);
278}
279
280/// A cooperative stop, shared with whoever asked the loop to run.
281///
282/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
283/// Ctrl-C listener and the web UI keep others, and every clone points at the
284/// same flag. There is no channel because there is nothing to send — the only
285/// message is "stop", it is idempotent, and a flag cannot be missed by a
286/// receiver that was not listening yet.
287///
288/// A stop ends scheduler dispatch promptly. Its busy snapshot is observational:
289/// detached task workers keep their own lifetimes and ownership after this
290/// handle's scheduler exits.
291#[derive(Debug, Clone, Default)]
292pub struct Stop {
293    /// Set once, never cleared: a stop is not something an operator takes back
294    /// half way through, and a clearable flag would let a start racing a stop
295    /// resurrect a loop that is already unwinding.
296    stopped: Arc<AtomicBool>,
297    /// Live task workers observed by the scheduler's latest dispatch snapshot.
298    busy: Arc<std::sync::atomic::AtomicUsize>,
299    /// Wakes the idle wait. Without this a stop would not be seen until the
300    /// poll interval elapsed, and an operator tapping stop on a phone would
301    /// watch a button do nothing for five seconds.
302    wake: Arc<Notify>,
303    /// Handed to the run in flight, so a stop can also mean "park at the next
304    /// node boundary" instead of "finish the whole competition first".
305    pause: crate::graph::Pause,
306}
307
308impl Stop {
309    /// A stop nobody has asked for yet.
310    #[must_use]
311    pub fn new() -> Self {
312        Self::default()
313    }
314
315    /// Ask the loop to stop. Idempotent, and safe to call before the loop
316    /// starts: the flag is checked before the first poll.
317    pub fn stop(&self) {
318        self.stopped.store(true, Ordering::SeqCst);
319        // `notify_one` rather than `notify_waiters` because the loop may not be
320        // parked yet: this stores a permit, so a wait that registers a moment
321        // later returns at once instead of sleeping out the whole interval.
322        self.wake.notify_one();
323    }
324
325    /// Has a stop been asked for?
326    #[must_use]
327    pub fn stopped(&self) -> bool {
328        self.stopped.load(Ordering::SeqCst)
329    }
330
331    /// Whether a requested scheduler retirement still has an active snapshot.
332    /// Workers continue independently after the scheduler has retired.
333    #[must_use]
334    pub fn finishing(&self) -> bool {
335        self.stopped() && self.busy_now()
336    }
337
338    /// Ask the loop to stop *and* the run in flight to park at its next node
339    /// boundary.
340    ///
341    /// Unlike plain stop, explicit park asks workers to checkpoint at their
342    /// existing safe boundaries. Binary replacement never needs a park.
343    pub fn park(&self, cause: crate::run::ParkCause) {
344        self.pause.park_for(cause);
345        self.stop();
346    }
347
348    /// Has a park been asked for?
349    #[must_use]
350    pub fn parking(&self) -> bool {
351        self.pause.parked()
352    }
353
354    /// The pause handle to give a runner.
355    #[must_use]
356    pub fn pause(&self) -> crate::graph::Pause {
357        self.pause.clone()
358    }
359
360    /// Whether the scheduler's latest snapshot contains active task workers.
361    #[must_use]
362    pub fn busy_now(&self) -> bool {
363        self.busy.load(Ordering::SeqCst) > 0
364    }
365
366    /// Wait out one poll interval, returning early once a stop is asked for.
367    async fn idle(&self, poll: Duration) {
368        tokio::select! {
369            () = tokio::time::sleep(poll) => {}
370            () = self.wake.notified() => {}
371        }
372    }
373}
374
375/// The daemon's published state, read permissively.
376///
377/// This mirrors [`Status`], but is a separate declaration on purpose: every
378/// field defaults, so a status file from an older or newer magi still yields
379/// a usable reading — one this build has never heard of — instead of a parse
380/// error that hides the daemon entirely.
381#[derive(Debug, Clone, Default, Deserialize)]
382#[serde(default)]
383pub struct Reading {
384    /// Format version the daemon claims.
385    pub schema: u32,
386    /// Daemon process id, for an operator who wants to stop it.
387    pub pid: Option<u32>,
388    /// When that process started.
389    pub started_at: Option<Timestamp>,
390    /// Last heartbeat. Absent means the file is unusable, hence not running.
391    pub updated_at: Option<Timestamp>,
392    /// True when the queue had nothing runnable at the last poll.
393    pub idle: bool,
394    /// What the daemon is working on. Empty means idle; more than one entry
395    /// means more than one run is in flight at once.
396    ///
397    /// `deserialize_with` rather than the plain derive: a daemon started
398    /// before this field became a list is still out there writing the old
399    /// shape — a single `{"task":...,"run":...}` object, or its absence —
400    /// on every heartbeat until it is restarted, and a live process reading
401    /// that file during the rollout must still see it as running rather than
402    /// as absent. A bare type change here would fail the whole struct's
403    /// deserialization on a type mismatch, defeating the permissiveness this
404    /// type exists for.
405    #[serde(deserialize_with = "de_current")]
406    pub current: Vec<Current>,
407    /// Tasks this daemon process has finished.
408    pub completed: u64,
409    /// Queue polls this daemon process has made.
410    pub polls: u64,
411    /// Last no-start scan, retaining unknown reason keys from newer writers.
412    pub dispatch_wait: Option<DispatchWait>,
413    /// Effective startup capabilities of the question recovery loops.
414    #[serde(default)]
415    pub question_recovery: Option<crate::question_delivery::Recovery>,
416    /// Independent-worker control protocol, absent on legacy embedded loops.
417    pub worker_protocol: Option<u32>,
418}
419
420/// Accept the old single-`Current`-or-absent shape as well as the current
421/// list, so a reader never has to know which build wrote the file.
422fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
423where
424    D: serde::Deserializer<'de>,
425{
426    #[derive(Deserialize)]
427    #[serde(untagged)]
428    enum Shape {
429        Many(Vec<Current>),
430        One(Current),
431    }
432    Ok(
433        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
434            Shape::Many(v) => v,
435            Shape::One(c) => vec![c],
436        }),
437    )
438}
439
440impl Reading {
441    /// Seconds since the last heartbeat, or `None` when there has never been
442    /// one.
443    #[must_use]
444    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
445        self.updated_at
446            .map(|at| (now.as_second() - at.as_second()).max(0))
447    }
448
449    /// Whether the loop counts as running: a heartbeat no older than
450    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
451    /// progress hours after the daemon that owned it was killed.
452    #[must_use]
453    pub fn running(&self, now: Timestamp) -> bool {
454        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
455    }
456}
457
458/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
459/// usable there.
460///
461/// Missing, half-written and unparseable all collapse to `None`, because the
462/// only question a reader asks is whether a daemon is alive, and a file it
463/// cannot read is not evidence that one is.
464#[must_use]
465pub fn read_status(home: &Path) -> Option<Reading> {
466    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
467    serde_json::from_str(&body).ok()
468}
469
470/// Read-only evidence of runs owned by a live daemon or independent worker.
471///
472/// CLI, sandboxed conversation controls and Web cleanup share this observation.
473/// A stale daemon heartbeat does not invalidate a worker's OS-held lease.
474/// Starting reservations and unknown worker state remain protected; observing
475/// them never creates, reconciles or archives files in the worker store.
476/// Callers interested in one identity use [`is_working_on`] or
477/// [`is_working_on_task`].
478#[must_use]
479pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
480    let mut current = read_status(home)
481        .filter(|reading| reading.running(now))
482        .map(|reading| reading.current)
483        .unwrap_or_default();
484    let workers = crate::worker::observe_active(home).and_then(|jobs| {
485        jobs.into_iter()
486            .filter(|job| job.kind == "task")
487            .map(|job| {
488                let request: TaskWorker = serde_json::from_value(job.payload)?;
489                let run = Queue::at(request.queue)
490                    .get(&request.task)
491                    .ok()
492                    .and_then(|task| task.execution_runs().last().cloned())
493                    .unwrap_or_default();
494                Ok(Current {
495                    worker: Some(job.id),
496                    task: request.task,
497                    run,
498                })
499            })
500            .collect::<Result<Vec<_>>>()
501    });
502    match workers {
503        Ok(workers) => {
504            for worker in workers {
505                if !current.iter().any(|claim| {
506                    claim.task == worker.task
507                        && claim.run == worker.run
508                        && claim.worker == worker.worker
509                }) {
510                    current.push(worker);
511                }
512            }
513        }
514        Err(error) => {
515            // This API gates destructive cleanup. Unknown worker ownership
516            // protects every known task/run instead of pretending it is idle.
517            tracing::error!("cannot determine active workers: {error:#}");
518            current.extend(
519                Queue::at(home.join("queue"))
520                    .list()
521                    .into_iter()
522                    .map(|task| Current {
523                        worker: None,
524                        task: task.id.clone(),
525                        run: task.execution_runs().last().cloned().unwrap_or_default(),
526                    }),
527            );
528            current.extend(
529                crate::run::list_ids_in(&home.join("runs"))
530                    .into_iter()
531                    .map(|run| Current {
532                        worker: None,
533                        task: String::new(),
534                        run,
535                    }),
536            );
537        }
538    }
539    current
540}
541
542/// Whether a live daemon is working on this run at this moment.
543#[must_use]
544pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
545    current_work(home, now).iter().any(|c| c.run == run)
546}
547
548/// Admission may ignore only this process's confirmed worker reservation.
549/// Keep anonymous/legacy daemon claims and every other worker, even for the
550/// same task. The run's execution lease and process identity are checked by
551/// the caller under the owner lock as well.
552pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
553    // A helper or test may inherit an identity from a different run store.
554    // That identity grants no exception here; retain all ownership evidence.
555    let same_home = std::env::var_os("MAGI_WORKER_HOME")
556        .is_some_and(|worker_home| Path::new(&worker_home) == home);
557    let caller = if same_home {
558        crate::worker::current_job(home)?
559    } else {
560        None
561    }
562    .filter(|job| {
563        job.kind == "task"
564            && job.status == crate::worker::Status::Running
565            && job.pid == Some(std::process::id())
566    });
567    Ok(other_claims_run(
568        &current_work(home, now),
569        run,
570        caller.as_ref().map(|job| job.id.as_str()),
571    ))
572}
573
574fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
575    claims
576        .iter()
577        .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
578}
579
580/// Whether a live daemon is working on a run whose short id is this one.
581///
582/// For a worktree that has no run record to compare against at all -
583/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
584/// id is not available to hand to [`is_working_on`]. The short id is: a run's
585/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
586/// and it is exactly the gap between the daemon claiming a task and
587/// `RunState::new` saving the first `run.json` that this exists to protect -
588/// a run genuinely in flight but invisible to a scan of `runs/`.
589#[must_use]
590pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
591    current_work(home, now)
592        .iter()
593        .any(|c| crate::run::short_of(&c.run) == short)
594}
595
596/// Whether a live daemon is working on this task at this moment.
597#[must_use]
598pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
599    current_work(home, now).iter().any(|c| c.task == task)
600}
601
602/// Remove claim files whose owner is provably dead, or that have simply
603/// outlived `older_than`, and return the task ids swept.
604///
605/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
606/// destructor, and the orphaned `.lock` file would make its task permanently
607/// unclaimable — the backlog would stop for good at exactly the task that was
608/// in flight when the machine went down.
609///
610/// The pid recorded in the lock is the authority whenever it can be read at
611/// all; age is only a fallback for when it cannot be.
612///
613/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
614///   full stop — dead sweeps the lock immediately, regardless of age; alive
615///   protects it, regardless of age. This is what lets a lock be reclaimed in
616///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
617///   before this daemon even started, next to a `queued` task, no longer has
618///   to sit for six hours before anything notices its owner is gone.
619/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
620///   falls back to `older_than`, since there is nothing else to check.
621///
622/// Age must never override a *positive* liveness confirmation. `sweep`
623/// polls concurrently with independently running task workers. A worker may
624/// legitimately run longer than `older_than`; its live pid must still protect
625/// its claim. Age alone must never turn that claim into a second task attempt,
626/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
627/// to a second attempt — two `Runner`s writing the same `run.json` and the
628/// same worktree at once. `pid_alive` answering "alive" for anything it
629/// cannot determine (a live process, a pid this build cannot check, one
630/// under another account) is exactly what keeps that path from ever
631/// firing on a guess.
632///
633/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
634/// output unreadable must not be license to guess, and the risk of an
635/// unparseable lock outliving a genuinely dead owner is bounded by an order
636/// of magnitude above any plausible run rather than by a positive check.
637///
638/// Runs on every poll, not only at startup — a daemon up for days must keep
639/// noticing a lock some other, now-dead, daemon left behind just as readily
640/// as one it trips over on the way up.
641pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
642    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
643}
644
645/// [`sweep_stale_claims`] with its process-query boundary supplied by the
646/// caller. This keeps the lock policy testable where process listing is
647/// unavailable, while production still uses the platform query above.
648fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
649where
650    F: Fn(u32) -> bool,
651{
652    let this_process = std::process::id();
653    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
654        .into_iter()
655        .flatten()
656        .flatten()
657        .map(|e| e.path())
658        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
659        .filter(|p| {
660            match std::fs::read_to_string(p)
661                .ok()
662                .and_then(|body| body.trim().parse::<u32>().ok())
663            {
664                // This process wrote it and is asking the question right
665                // now, so it is definitionally still alive - settled without
666                // spawning a helper process at all.
667                Some(pid) if pid == this_process => false,
668                Some(pid) => !pid_alive(pid),
669                None => p
670                    .metadata()
671                    .and_then(|m| m.modified())
672                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
673                    .is_ok_and(|age| age >= older_than),
674            }
675        })
676        .filter(|p| std::fs::remove_file(p).is_ok())
677        .filter_map(|p| {
678            p.file_stem()
679                .and_then(|s| s.to_str())
680                .map(std::borrow::ToOwned::to_owned)
681        })
682        .collect();
683    swept.sort_unstable();
684    swept
685}
686
687/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
688/// no live daemon's heartbeat naming it? Deterministic — no model call, and
689/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
690/// shown.
691fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
692    task.status == TaskStatus::Running
693        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
694        && !is_working_on_task(home, &task.id, now)
695}
696
697/// Every task [`is_stalled`] right now — "止まったタスク" in
698/// `crate::conduct`'s vocabulary.
699fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
700    queue
701        .list()
702        .into_iter()
703        .filter(|t| is_stalled(t, home, now))
704        .collect()
705}
706
707/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
708/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
709/// `Failed`-and-so-also-runnable: a task that already attempted and lost
710/// belongs in [`finished_tasks`], where the question is a recovery, not a
711/// dependency.
712fn queued_tasks(queue: &Queue) -> Vec<Task> {
713    queue
714        .list()
715        .into_iter()
716        .filter(|t| t.status == TaskStatus::Queued)
717        .collect()
718}
719
720/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
721/// タスク" in `crate::conduct`'s vocabulary.
722fn finished_tasks(queue: &Queue) -> Vec<Task> {
723    queue
724        .list()
725        .into_iter()
726        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
727        .collect()
728}
729
730/// Deterministically resolve `Task::blocked_by`: a dependency task that
731/// reached `Done`, or a question that was answered, is removed — no model
732/// involved, on every poll. An answered question's content is copied onto
733/// the task ([`Task::record_answer`]) before its id is dropped, so it
734/// reaches the next `crate::conduct` prompt and the next run's instruction
735/// (see [`instruction_for`]) rather than only clearing the block.
736///
737/// A `blocked_by` id that names neither an existing task nor an existing
738/// question - `magi task rm` (or an operator by hand) deleted it while this
739/// task was still waiting - is caught before any of that: it can never
740/// become `Done` or `Answered`, so the ordinary loop below would otherwise
741/// leave the task `blocked` forever with nothing to notice. Such a task is
742/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
743/// which puts it in front of `crate::triage::run_once`'s own walk the next
744/// time it runs - see that module's doc for why the choice is "ask a human",
745/// never "assume the missing dependency was satisfied and unblock anyway".
746fn resolve_blockers(queue: &Queue, questions: &Questions) {
747    for listed in queue.list() {
748        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
749            continue;
750        }
751        let Ok(_claim) = queue.claim(&listed.id) else {
752            continue;
753        };
754        let Ok(mut task) = queue.get(&listed.id) else {
755            continue;
756        };
757        if task.status != TaskStatus::Blocked {
758            continue;
759        }
760        // A dependency deleted on purpose is released, not held - and before
761        // the missing check, so a pass that races the delete (or a claim that
762        // made `Queue::remove` skip this task) settles it quietly.
763        let deleted = queue.apply_deleted_blockers(&mut task, questions);
764        if !deleted.is_empty() {
765            record(queue, &mut task);
766            for id in &deleted {
767                queue.note_dependency_deleted(&task, id);
768            }
769            if task.status != TaskStatus::Blocked {
770                continue;
771            }
772        }
773        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
774        if !missing.is_empty() {
775            let language = language_of(&task, Path::new("."));
776            let mut cause = missing.clone();
777            cause.sort();
778            cause.dedup();
779            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
780            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
781                &task.blocked_by,
782                &missing,
783                &language,
784            )));
785            record(queue, &mut task);
786            continue;
787        }
788        // A conductor question nobody answered in time is retired by the
789        // waiter, and nothing else would ever move the task it blocks.
790        if let Some(q) = task.blocked_by.iter().find_map(|id| {
791            let crate::queue::Dependency::Question(full) =
792                crate::queue::dependency(queue, questions, id)
793            else {
794                return None;
795            };
796            questions.get_for_effects(&full).ok().filter(|q| {
797                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
798            })
799        }) {
800            let language = language_of(&task, Path::new("."));
801            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
802            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
803            record(queue, &mut task);
804            continue;
805        }
806        let mut changed = false;
807        for id in task.blocked_by.clone() {
808            let resolved = crate::queue::dependency(queue, questions, &id);
809            if let crate::queue::Dependency::Task(full) = &resolved {
810                if queue
811                    .get(full)
812                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
813                {
814                    task.unblock(&id);
815                    changed = true;
816                }
817                continue;
818            }
819            if let crate::queue::Dependency::Question(full) = resolved
820                && let Ok(q) = questions.get_for_effects(&full)
821                && q.status == ask::QuestionStatus::Answered
822            {
823                // The action sweep releases conductor blockers atomically
824                // with their selected operation. A fresh deputy lease must
825                // never leave an answered hold temporarily runnable.
826                if q.node == crate::conduct::NODE
827                    && q.chosen_action().is_some()
828                    && !task.action_applied(&q.id)
829                {
830                    continue;
831                }
832                let answer = match &q.answer {
833                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
834                    None => String::new(),
835                };
836                task.record_answer(q.summary.clone(), answer);
837                task.unblock(&id);
838                changed = true;
839            }
840        }
841        if changed {
842            record(queue, &mut task);
843        }
844    }
845}
846
847/// The `hold_reason` of a task whose conductor question went unanswered.
848fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
849    if crate::lang::is_japanese(language) {
850        format!(
851            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
852            q.short(),
853            q.summary
854        )
855    } else {
856        format!(
857            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
858            q.short(),
859            q.summary
860        )
861    }
862}
863
864/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
865/// for several unrelated reasons, and the waiter must not read them alike.
866#[derive(Debug, Clone, Copy, PartialEq, Eq)]
867pub(crate) enum ActionStanding {
868    /// The answer carries no action: the waiter delivers it as before.
869    NoAction,
870    /// The daemon will apply it (not applied, task idle, current attempt).
871    Pending,
872    /// Already applied (`Task::actions_applied`): the daemon has acted, so
873    /// delivering the word to the old seat would run it beside the new work.
874    Applied,
875    /// The question is about an earlier attempt than the task's latest.
876    Stale,
877    /// The task is running / blocked / done: the daemon defers for now.
878    Busy,
879}
880
881impl ActionStanding {
882    /// The daemon has acted or will act: the waiter must not deliver.
883    pub(crate) fn daemon_owns(self) -> bool {
884        matches!(self, Self::Pending | Self::Applied | Self::Stale)
885    }
886}
887
888/// Classify `q`'s chosen action against `task`. `Stale` is judged before
889/// `Busy`: a question about an earlier attempt must be stopped even while a
890/// newer competition is running.
891pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
892    if task.stale_question(q) {
893        ActionStanding::Stale
894    } else if q.chosen_action().is_none() {
895        ActionStanding::NoAction
896    } else if task.action_applied(&q.id) {
897        ActionStanding::Applied
898    } else if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
899        ActionStanding::Stale
900    } else if matches!(
901        task.status,
902        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
903    ) {
904        ActionStanding::Busy
905    } else {
906        ActionStanding::Pending
907    }
908}
909
910/// What [`decide_action`] concluded about one answered question.
911#[derive(Debug, Clone, PartialEq, Eq)]
912enum ActionDecision {
913    /// Nothing to do now (no action, already applied, or the task is busy).
914    Skip,
915    /// Continue the named run instead of competing again.
916    Resume(String),
917    /// Requeue as a fresh competition.
918    Requeue,
919    /// Hold the task by explicit operator choice.
920    Hold,
921    /// Close the task as done.
922    Done,
923    /// The question is about an earlier attempt than the task's latest; it
924    /// is recorded as handled and changes nothing.
925    Stale,
926    /// The action cannot be carried out; hold the task and say why. Never
927    /// falls back to something else, because the operator chose this one.
928    Refuse(String),
929}
930
931/// Decide what the choice answered on `q` means for `task`. `load` reads a
932/// run's state, as with [`unfinished_run_with`]. `home` must name that same
933/// store for driver leases and question checkpoints.
934///
935/// `Resume` only fires on the task's *latest* run, and only while that run
936/// could actually make progress ([`RunStatus::resumable`], not released, review
937/// budget left); an answer naming anything else is refused rather than
938/// reinterpreted as a fresh competition.
939fn decide_action<F>(
940    home: &Path,
941    task: &Task,
942    q: &ask::Question,
943    p: &Phrases,
944    load: F,
945) -> ActionDecision
946where
947    F: FnOnce(&str) -> Result<RunState>,
948{
949    if task.stale_question(q) {
950        return ActionDecision::Stale;
951    }
952    let Some(action) = q.chosen_action() else {
953        return ActionDecision::Skip;
954    };
955    if task.action_applied(&q.id)
956        || matches!(
957            task.status,
958            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
959        )
960    {
961        return ActionDecision::Skip;
962    }
963    // A question about an earlier attempt must not act on a newer one. A
964    // conductor question is keyed by the task id, not a run, so it is exempt.
965    if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
966        return ActionDecision::Stale;
967    }
968    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
969    let stopping = q.node == land::APPROVAL_NODE
970        && q.resolution()
971            .as_deref()
972            .is_some_and(crate::merge_decision::stops);
973    // An answer is the owner's decision as of when it was given: a manual hold
974    // placed before it (even after the question was asked) was seen and
975    // overruled by it, while a hold or release after it supersedes it.
976    let decision_at = q.answered_at.unwrap_or(q.asked_at);
977    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
978        return if repair || stopping {
979            ActionDecision::Refuse(format!(
980                "{} answer {} was superseded by a later operator decision; the task stays held. Inspect `magi show {}`; if this action is still wanted, explicitly release the existing owner with `magi task release {}`",
981                if repair { "repair" } else { "stop" },
982                q.id,
983                q.run,
984                task.id
985            ))
986        } else {
987            ActionDecision::Stale
988        };
989    }
990    match action {
991        a if a.maintenance() => ActionDecision::Skip,
992        ask::ChoiceAction::RecoverBase { .. }
993        | ask::ChoiceAction::ResumeRun { .. }
994        | ask::ChoiceAction::ReleaseTask { .. }
995        | ask::ChoiceAction::RerunChecks { .. }
996        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
997        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
998        ask::ChoiceAction::Hold => ActionDecision::Hold,
999        ask::ChoiceAction::Done => ActionDecision::Done,
1000        ask::ChoiceAction::Resume { run } => {
1001            if task.execution_runs().last() != Some(run) {
1002                return ActionDecision::Refuse((p.resume_not_latest)(
1003                    q.short(),
1004                    ask::short_id(run),
1005                ));
1006            }
1007            match load(run) {
1008                Ok(s) if stopping => {
1009                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1010                        || !s
1011                            .land_approval
1012                            .as_ref()
1013                            .is_some_and(|binding| binding.question == q.id)
1014                    {
1015                        ActionDecision::Stale
1016                    } else if s.liveness_under(home, false) == Liveness::Live {
1017                        ActionDecision::Skip
1018                    } else if s.status == RunStatus::Landing
1019                        && !s.released()
1020                        && s.retired_to.is_none()
1021                    {
1022                        ActionDecision::Resume(run.clone())
1023                    } else {
1024                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1025                    }
1026                }
1027                Ok(s)
1028                    if q.node == land::APPROVAL_NODE
1029                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1030                {
1031                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1032                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1033                    {
1034                        // A live/manual driver already consumed or superseded
1035                        // this answer. Do not hold its fresh approval wait.
1036                        ActionDecision::Stale
1037                    } else if s.liveness_under(home, false) == Liveness::Live {
1038                        ActionDecision::Skip
1039                    } else if s.status != RunStatus::Landing
1040                        || s.released()
1041                        || s.reviews.is_empty()
1042                        || !implementers_match(task, &s)
1043                        || !s
1044                            .land_approval
1045                            .as_ref()
1046                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1047                    {
1048                        ActionDecision::Refuse(format!(
1049                            "repair question {} no longer names a supported current approval on run {}; inspect `magi show {}` and restore the existing owner's approval before retrying; do not file another task",
1050                            q.id, run, run
1051                        ))
1052                    } else {
1053                        ActionDecision::Resume(run.clone())
1054                    }
1055                }
1056                Ok(s) if s.liveness_under(home, false) == Liveness::Live => {
1057                    ActionDecision::Refuse("run already has a live driver".into())
1058                }
1059                Ok(s) => match crate::handover::resume_refusal_under(&s, Some(home)) {
1060                    None => ActionDecision::Resume(run.clone()),
1061                    Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1062                        q.short(),
1063                        ask::short_id(run),
1064                        &reason.diagnostic(&s),
1065                    )),
1066                },
1067                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1068                    q.short(),
1069                    ask::short_id(run),
1070                    &format!("{e:#}"),
1071                )),
1072            }
1073        }
1074    }
1075}
1076
1077/// The fixed prose the daemon writes into [`Task::last_error`] and
1078/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1079/// `triage::Wording` and `land::Words`: only English and Japanese are
1080/// translated, anything else falls back to English.
1081///
1082/// Rendered when the reason is *generated*, so a reason keeps the language it
1083/// was written in if the setting changes later. The notification frame
1084/// (`Task <id> is held:`) is not here and stays English.
1085///
1086/// Deliberately **not** translated, because other code reads them back by
1087/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1088/// and `gate red`. IDs, node names, paths and external error text are embedded
1089/// as they are.
1090struct Phrases {
1091    /// `{}` = status label, then the detail.
1092    graph_stopped: fn(&str, &str) -> String,
1093    quorum_lost: &'static str,
1094    /// Followed by the seats' names.
1095    quota_took_out: &'static str,
1096    /// Followed by the status label.
1097    run_ended: &'static str,
1098    /// Followed by the question's short id.
1099    waiting_for_answer: &'static str,
1100    recovered_running: &'static str,
1101    no_run_to_recover: &'static str,
1102    could_not_start: &'static str,
1103    resume_not_latest: fn(&str, &str) -> String,
1104    resume_cannot_progress: fn(&str, &str, &str) -> String,
1105    resume_unreadable: fn(&str, &str, &str) -> String,
1106    /// A takeover refusal: the operator-facing text. English is the error's own
1107    /// `Display`; a translation keeps the machine detail apart in parentheses.
1108    handover_refused: fn(&crate::handover::Refused) -> String,
1109    /// Appended to a refused handover's hold reason (leading space included).
1110    handover_hint: &'static str,
1111    /// (seats that never answered, review rounds) for the review loop's
1112    /// "refusing to call it clean" stop.
1113    reviewers_never_answered: fn(usize, usize) -> String,
1114}
1115
1116const PHRASES_EN: Phrases = Phrases {
1117    graph_stopped: |status, detail| {
1118        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1119    },
1120    quorum_lost: "the judging panel lost its quorum",
1121    quota_took_out: "; quota took out ",
1122    run_ended: "run ended ",
1123    waiting_for_answer: " - waiting for operator answer to question ",
1124    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1125    no_run_to_recover: "task was `running` with no live daemon and no readable \
1126                        run to recover; held for a human to check what happened",
1127    could_not_start: "could not start the run: ",
1128    resume_not_latest: |q, run| {
1129        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1130    },
1131    resume_cannot_progress: |q, run, reason| {
1132        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1133    },
1134    resume_unreadable: |q, run, e| {
1135        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1136    },
1137    handover_refused: |r| r.to_string(),
1138    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1139    reviewers_never_answered: |missing, rounds| {
1140        format!(
1141            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1142             refusing to call it clean"
1143        )
1144    },
1145};
1146
1147const PHRASES_JA: Phrases = Phrases {
1148    graph_stopped: |status, detail| {
1149        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1150    },
1151    quorum_lost: "審査パネルが定足数を失いました",
1152    quota_took_out: "。クォータで脱落: ",
1153    run_ended: "run 終了: ",
1154    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1155    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1156    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1157                        何が起きたか人が確認するため保留にしました",
1158    could_not_start: "run を開始できませんでした: ",
1159    resume_not_latest: |q, run| {
1160        format!(
1161            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1162        )
1163    },
1164    resume_cannot_progress: |q, run, reason| {
1165        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1166    },
1167    resume_unreadable: |q, run, e| {
1168        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1169    },
1170    handover_refused: |r| {
1171        use crate::handover::Refused;
1172        match r {
1173            Refused::Foreign { branch, path, why } => format!(
1174                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1175                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1176                 から、やり直してください(詳細: {why})"
1177            ),
1178            Refused::Unsafe { branch, path, why } => format!(
1179                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1180                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1181                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1182            ),
1183            Refused::ReleaseFailed { branch, path, run } => format!(
1184                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1185                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1186                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1187            ),
1188        }
1189    },
1190    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1191    reviewers_never_answered: |missing, rounds| {
1192        format!(
1193            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1194             クリーンとは認めません"
1195        )
1196    },
1197};
1198
1199fn phrases(language: &str) -> &'static Phrases {
1200    if crate::lang::is_japanese(language) {
1201        &PHRASES_JA
1202    } else {
1203        &PHRASES_EN
1204    }
1205}
1206
1207/// The language of the repository a task belongs to, read best-effort for the
1208/// paths that have no run (and so no config of their own) to ask. An unreadable
1209/// config is English, not an error: a hold reason must still get written.
1210fn language_of(task: &Task, fallback: &Path) -> String {
1211    crate::lang::of_repo(&repo_for(task, fallback))
1212}
1213
1214/// The task an answered question speaks for: the one whose runs include the
1215/// question's run, or - for a conductor question, filed under the task's own
1216/// id - the task with that id.
1217pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1218    if q.node == crate::conduct::NODE {
1219        return tasks.iter().find(|t| t.id == q.run);
1220    }
1221    tasks.iter().find(|t| t.runs.contains(&q.run))
1222}
1223
1224/// Legacy conductor prose never becomes a maintenance command by inference.
1225/// Replace unsupported open labels under the question lock before dispatch.
1226fn repair_choice_offers(questions: &Questions) {
1227    let ownership = crate::task_chat::InquiryOwnership::default();
1228    for q in questions
1229        .list_for_effects_in(&ownership)
1230        .into_iter()
1231        .filter(|q| {
1232            q.status.open()
1233                && q.node == crate::conduct::NODE
1234                && q.choices
1235                    .iter()
1236                    .any(|c| crate::choice_effect::describe(q, c).is_none())
1237        })
1238    {
1239        let _ = questions.update_in(&q.id, &ownership, |current| {
1240            if current.status.open() {
1241                crate::choice_effect::executable_conductor(current);
1242                if let Some(deputy) = &mut current.deputy {
1243                    deputy.brief = crate::deputy::brief(
1244                        &current.run,
1245                        &current.detail,
1246                        &current.choices,
1247                        &current.actions,
1248                    );
1249                }
1250            }
1251            Ok(())
1252        });
1253    }
1254}
1255
1256/// Apply answered typed choices. Only the daemon calls this in production;
1257/// deputies settle the question and never execute its actions.
1258pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1259    apply_maintenance_choices(queue, questions, home).await;
1260    apply_task_choice_actions(queue, questions, home);
1261}
1262
1263/// Apply bounded maintenance effects independently of question ownership: a
1264/// release watcher need not have a queue task, and a predecessor is another run.
1265async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1266    let ownership = crate::task_chat::InquiryOwnership::default();
1267    for q in questions.list_for_effects_in(&ownership) {
1268        // Read again under the same fence used by explicit settlement.
1269        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1270            continue;
1271        };
1272        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1273            continue;
1274        };
1275        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1276            continue;
1277        };
1278        // Receipt paths use question IDs, whose format is independent of run
1279        // IDs. Apply the question store's filename safety rule to both eras.
1280        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1281            continue;
1282        }
1283        if queue.list().iter().any(|task| {
1284            (task.id == q.run
1285                || task.runs.contains(&q.run)
1286                || q.routed_task.as_deref() == Some(&task.id))
1287                && task.stale_question(&q)
1288        }) {
1289            continue;
1290        }
1291        if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1292            let tasks = queue.list();
1293            let owner = crate::task_chat::task_of(&q, &tasks);
1294            if let Some(owner) = owner
1295                && q.routed_task
1296                    .as_deref()
1297                    .is_none_or(|routed| routed == owner)
1298            {
1299                let result = crate::base_recovery_control::recover(
1300                    queue,
1301                    home,
1302                    crate::base_recovery_control::Request {
1303                        run: run.clone(),
1304                        head: stop.head.clone(),
1305                        actor: "decisions".into(),
1306                        request: q.id.clone(),
1307                        decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1308                        expected_stop: Some((stop.clone(), *episode)),
1309                    },
1310                )
1311                .await;
1312                if let Err(error) = result {
1313                    tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1314                    notices::raise_in(home, Notice::warn(
1315                        &format!("base-recovery:{}", q.id),
1316                        format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1317                    ).link(Link::Run { id: run.clone() }));
1318                }
1319            }
1320            continue;
1321        }
1322        let dir = home.join("choice-actions");
1323        if std::fs::create_dir_all(&dir).is_err() {
1324            continue;
1325        }
1326        let Ok(lock) = std::fs::OpenOptions::new()
1327            .create(true)
1328            .truncate(false)
1329            .write(true)
1330            .open(dir.join(format!("{}.lock", q.id)))
1331        else {
1332            continue;
1333        };
1334        if crate::pr_head::try_lock_file(&lock).is_err() {
1335            continue;
1336        }
1337        let fresh = !home
1338            .join("choice-actions")
1339            .join(format!("{}.json", q.id))
1340            .exists();
1341        let result = async {
1342            let receipt = dir.join(format!("{}.json", q.id));
1343            if receipt.exists() {
1344                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1345                anyhow::ensure!(
1346                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1347                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1348                );
1349                return Ok::<_, anyhow::Error>(());
1350            }
1351            // Never retry an uncertain external effect. The receipt is written
1352            // before calling gh, exactly like release_watch's rerun record.
1353            let record = |status: &str| -> anyhow::Result<()> {
1354                let tmp = receipt.with_extension("tmp");
1355                std::fs::write(
1356                    &tmp,
1357                    serde_json::to_vec(&serde_json::json!({
1358                        "action": action, "status": status,
1359                    }))?,
1360                )?;
1361                std::fs::rename(tmp, &receipt)?;
1362                Ok(())
1363            };
1364            let applied = async {
1365                match action {
1366                    ask::ChoiceAction::ResumeRun { run } => {
1367                        crate::resume::validate(home, run)?;
1368                        record("started")?;
1369                        let decided = q.answered_at.unwrap_or(q.asked_at);
1370                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1371                            crate::resume::validate_unqueued(home, run)?;
1372                            crate::resume::start(home, run.clone()).await?;
1373                        }
1374                    }
1375                    ask::ChoiceAction::ReleaseTask {
1376                        task,
1377                        held_at,
1378                        reason,
1379                    } => {
1380                        anyhow::ensure!(
1381                            queue.resolve_id(task)? == *task,
1382                            "task action requires an exact task ID"
1383                        );
1384                        let _claim = queue.claim(task)?;
1385                        let mut task = queue.get(task)?;
1386                        if task.action_applied(&q.id) {
1387                            return Ok(());
1388                        }
1389                        // Filing this conductor question temporarily wraps the
1390                        // original hold in a Blocked state. Restore only that
1391                        // exact blocker on the local copy before checking the
1392                        // hold binding; unrelated waits never authorize release.
1393                        if q.node == crate::conduct::NODE
1394                            && q.run == task.id
1395                            && task.status == TaskStatus::Blocked
1396                            && task.blocked_from == Some(TaskStatus::Held)
1397                            && task.blocked_by.as_slice() == [q.id.as_str()]
1398                        {
1399                            task.unblock(&q.id);
1400                        }
1401                        anyhow::ensure!(
1402                            task.status == TaskStatus::Held
1403                                && task.held_at == Some(*held_at)
1404                                && task.hold_reason.as_deref() == reason.as_deref()
1405                                && task
1406                                    .operator_decided_at
1407                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1408                            "task no longer has the hold this question names"
1409                        );
1410                        task.release_operator("choice", Some(&q.id));
1411                        task.mark_action_applied(&q.id);
1412                        queue.put(&mut task)?;
1413                    }
1414                    ask::ChoiceAction::AbandonRun { run } => {
1415                        record("started")?;
1416                        crate::driver::abandon_proven_dead(home, run)?;
1417                    }
1418                    ask::ChoiceAction::RerunChecks {
1419                        repo,
1420                        pr,
1421                        head,
1422                        runs,
1423                    } => {
1424                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1425                            .await?;
1426                    }
1427                    _ => unreachable!(),
1428                }
1429                Ok::<_, anyhow::Error>(())
1430            }
1431            .await;
1432            match applied {
1433                Ok(()) => record("applied"),
1434                Err(e) => {
1435                    record(&format!("refused or failed: {e:#}"))?;
1436                    Err(e)
1437                }
1438            }
1439        }
1440        .await;
1441        // Retire the originating blocker as well as the target operation.
1442        // A foreign resume leaves its issuer held instead of competing beside
1443        // the execution just started. Other successful maintenance lets the
1444        // original task retry its normal, guarded path.
1445        if home
1446            .join("choice-actions")
1447            .join(format!("{}.json", q.id))
1448            .exists()
1449            && let Some(listed) = task_of_question(&queue.list(), &q)
1450            && !listed.action_applied(&q.id)
1451            && let Ok(_claim) = queue.claim(&listed.id)
1452            && let Ok(mut origin) = queue.get(&listed.id)
1453        {
1454            if !origin.operator_held()
1455                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1456                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1457            {
1458                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1459                    origin.hold_machine(Some(format!(
1460                        "Maintenance choice {} settled; inspect its target before releasing this task",
1461                        q.id
1462                    )));
1463                } else {
1464                    origin.unblock(&q.id);
1465                }
1466            }
1467            origin.mark_action_applied(&q.id);
1468            let _ = queue.put(&mut origin);
1469        }
1470        if let Err(e) = result
1471            && fresh
1472        {
1473            notices::raise_in(
1474                home,
1475                Notice::warn(
1476                    &format!("action:{}", q.id),
1477                    format!("Choice action {} was not completed: {e:#}", q.id),
1478                )
1479                .link(if q.run_names_task() {
1480                    Link::Task { id: q.run.clone() }
1481                } else {
1482                    Link::Run { id: q.run.clone() }
1483                }),
1484            );
1485        }
1486    }
1487}
1488
1489/// Rerun the named failed workflow runs of a pull request, each at most once
1490/// per `request` (a question id, or a chat operation identity). The head,
1491/// lifecycle and failed state are re-read from the forge first; `started` is
1492/// called once those checks pass and before the first external call, and the
1493/// ledger entry is written before every `gh` call, so an uncertain result is
1494/// never repeated automatically.
1495pub(crate) async fn rerun_checks_once(
1496    home: &Path,
1497    request: &str,
1498    repo: &Path,
1499    pr: &str,
1500    head: &str,
1501    runs: &[String],
1502    started: impl FnOnce() -> anyhow::Result<()>,
1503) -> anyhow::Result<()> {
1504    use crate::release_watch::{GhForge, ReleaseForge};
1505    anyhow::ensure!(
1506        !runs.is_empty()
1507            && runs.len() <= 20
1508            && runs
1509                .iter()
1510                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1511            && !pr.starts_with('-'),
1512        "invalid rerun targets"
1513    );
1514    let snap = GhForge.snapshot(repo, pr).await?;
1515    anyhow::ensure!(
1516        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1517        "pull request head or lifecycle changed"
1518    );
1519    anyhow::ensure!(
1520        runs.iter().all(|r| snap
1521            .checks
1522            .iter()
1523            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1524        "named workflow is no longer failed on this pull request"
1525    );
1526    started()?;
1527    let dir = home.join("choice-actions");
1528    std::fs::create_dir_all(&dir)?;
1529    let rerun_lock = std::fs::OpenOptions::new()
1530        .create(true)
1531        .truncate(false)
1532        .write(true)
1533        .open(dir.join("reruns.lock"))?;
1534    crate::pr_head::try_lock_file(&rerun_lock)?;
1535    let ledger = dir.join("reruns.json");
1536    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1537        serde_json::from_slice(&std::fs::read(&ledger)?)?
1538    } else {
1539        Default::default()
1540    };
1541    for run in runs {
1542        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1543        if !recorded.insert(key) {
1544            continue;
1545        }
1546        let tmp = ledger.with_extension("tmp");
1547        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1548        std::fs::rename(tmp, &ledger)?;
1549        GhForge.rerun(repo, run).await?;
1550    }
1551    Ok(())
1552}
1553
1554/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1555///
1556/// Runs on every poll before the conductor looks at the queue. The task is
1557/// re-read under its claim, so a task somebody completed or held by hand in
1558/// the meantime is judged on what it is now. `Resume` releases the task and
1559/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1560/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1561/// ordinary `unfinished_run` logic resumes that same run.
1562pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1563    let tasks = queue.list();
1564    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1565    for q in questions.list_for_effects_in(&ownership) {
1566        // Read again under the same fence used by explicit settlement.
1567        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1568            continue;
1569        };
1570        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1571            continue;
1572        };
1573        // Dismissal is committed by the question writer, never a resume.
1574        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1575            continue;
1576        }
1577        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1578            continue;
1579        }
1580        let Some(listed) = task_of_question(&tasks, &q) else {
1581            if q.node == land::APPROVAL_NODE
1582                && q.resolution().as_deref().is_some_and(|choice| {
1583                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1584                })
1585            {
1586                notices::raise_in(
1587                    home,
1588                    Notice::warn(
1589                        &format!("repair-owner:{}", q.id),
1590                        format!(
1591                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1592                            q.run, q.run
1593                        ),
1594                    ).link(Link::Run { id: q.run.clone() }),
1595                );
1596            }
1597            continue;
1598        };
1599        if listed.action_applied(&q.id) {
1600            continue;
1601        }
1602        let Ok(_claim) = queue.claim(&listed.id) else {
1603            continue;
1604        };
1605        let Ok(mut task) = queue.get(&listed.id) else {
1606            continue;
1607        };
1608        // Work only on this local copy until the action can be committed.
1609        // In particular, a fresh lease below leaves the persisted task blocked.
1610        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1611            let blockers: Vec<_> = task
1612                .blocked_by
1613                .iter()
1614                .filter(|id| {
1615                    crate::queue::dependency(queue, questions, id)
1616                        == crate::queue::Dependency::Question(q.id.clone())
1617                })
1618                .cloned()
1619                .collect();
1620            if !blockers.is_empty() {
1621                for id in blockers {
1622                    task.unblock(&id);
1623                }
1624                let answer = match &q.answer {
1625                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1626                    None => String::new(),
1627                };
1628                task.record_answer(q.summary.clone(), answer);
1629            }
1630        }
1631        let language = language_of(&task, Path::new("."));
1632        let mut decision = decide_action(home, &task, &q, phrases(&language), |id| {
1633            RunState::load_under(id, home)
1634        });
1635        let completion = if matches!(decision, ActionDecision::Done) {
1636            match crate::task_completion::prepare_close(
1637                &task,
1638                home,
1639                CompletionActor::DaemonSettle,
1640                Some(format!(
1641                    "Question {}: {} — {}",
1642                    q.id,
1643                    q.summary,
1644                    q.resolution().unwrap_or_default()
1645                )),
1646                false,
1647            ) {
1648                Ok(context) => Some(context),
1649                Err(error) => {
1650                    decision = ActionDecision::Refuse(error.to_string());
1651                    None
1652                }
1653            }
1654        } else {
1655            None
1656        };
1657        let ran = matches!(
1658            decision,
1659            ActionDecision::Resume(_)
1660                | ActionDecision::Requeue
1661                | ActionDecision::Hold
1662                | ActionDecision::Done
1663        );
1664        if ran && asker_may_still_read(questions, &q, home) {
1665            // The asking process or its seat can still take the word; act
1666            // once it has gone quiet. Bound on the remaining window: the
1667            // check is not atomic with the write below, so an asker that
1668            // takes the word in between (at most one poll, never more than
1669            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1670            // and `Task::actions_applied` under the claim keeps the action to
1671            // one application. The waiter does not deliver an answer that
1672            // carries an action (`waiter::decide_owned`), so it cannot race.
1673            continue;
1674        }
1675        let done = matches!(decision, ActionDecision::Done);
1676        // Resume owes an execution pass; only these task-local effects finish
1677        // in this write. Stale/refused actions never acquire an effect receipt.
1678        let completed = matches!(
1679            decision,
1680            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1681        );
1682        match decision {
1683            ActionDecision::Skip => continue,
1684            ActionDecision::Resume(run) => {
1685                task.release_operator("choice", Some(&q.id));
1686                task.resume_override = Some(crate::queue::OperatorResume {
1687                    question_id: q.id.clone(),
1688                    at: Timestamp::now(),
1689                    conductor_rehold: None,
1690                    forced: true,
1691                    pinned_run: Some(run),
1692                });
1693            }
1694            ActionDecision::Stale => {}
1695            ActionDecision::Requeue => {
1696                task.release_operator("choice-requeue", Some(&q.id));
1697                task.requeue();
1698            }
1699            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1700            ActionDecision::Done => {
1701                task.succeed(completion.expect("done passed completion admission"));
1702            }
1703            ActionDecision::Refuse(why) => {
1704                let _ =
1705                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1706                if task.operator_held() {
1707                    // A rejected answer does not release the operator's hold
1708                    // or reclassify it as recoverable by the conductor.
1709                    task.hold_reason = Some(match task.hold_reason.take() {
1710                        Some(reason) => format!("{reason}\n\n{why}"),
1711                        None => why,
1712                    });
1713                } else {
1714                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1715                    task.hold_machine(Some(why));
1716                }
1717                notices::raise(
1718                    Notice::warn(
1719                        &format!("action:{}", q.id),
1720                        "An answered task action could not be applied; the task stays held.",
1721                    )
1722                    .link(Link::Task {
1723                        id: task.id.clone(),
1724                    }),
1725                );
1726            }
1727        }
1728        task.mark_action_applied(&q.id);
1729        if completed {
1730            task.decision_effects.insert(
1731                q.id.clone(),
1732                format!("decision: {}", q.resolution().expect("answered action")),
1733            );
1734        }
1735        // The applied id travels with the transition, so a failed save loses
1736        // neither and the answer is acted on at the next poll.
1737        record(queue, &mut task);
1738        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1739            supersede_prior_runs(&task, home);
1740        }
1741        // Delivery is only a note of who has read the answer; the task's own
1742        // mark above is the authority. Best effort.
1743        let _ = questions.update_in(&q.id, &ownership, |r| {
1744            r.answer_delivered = true;
1745            Ok(())
1746        });
1747    }
1748}
1749
1750/// Whether something may still read the answer to `q`: a fresh lease, or the
1751/// asking seat still listed as active in its run (its CLI can outlive the
1752/// `magi ask` that was killed).
1753fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1754    let now = Timestamp::now();
1755    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1756        return true;
1757    }
1758    q.node != crate::conduct::NODE
1759        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1760            s.seats_active()
1761                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1762        })
1763}
1764
1765/// Retire an unanswered conductor question after its task no longer refers to
1766/// it. Conductor questions use the task id in `Question::run`, so run-based
1767/// cleanup cannot observe a manual release or completion.
1768///
1769/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1770/// own question also carries a `run`, and a run id that happens to collide
1771/// with some task's id is not this loop's business — only a conductor
1772/// question actually uses the task id that way. One `Questions::list()` scan
1773/// is taken up front and matched against the in-memory task set, rather than
1774/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1775fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1776    let tasks = queue.list();
1777    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1778    let by_id: std::collections::BTreeMap<&str, &Task> =
1779        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1780    let referenced: Vec<&str> = tasks
1781        .iter()
1782        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1783        .collect();
1784
1785    for mut question in questions.list_for_effects_in(&ownership) {
1786        if !question.status.open()
1787            || question.node != crate::conduct::NODE
1788            || questions.held_reply_in(&question.id, &ownership)
1789        {
1790            continue;
1791        }
1792        // Keep questions a task still names, including when the reference
1793        // moved to a dependent task.
1794        // Preserve even ambiguous references: retiring a possibly referenced
1795        // question is unsafe until the operator disambiguates it.
1796        if referenced
1797            .iter()
1798            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1799        {
1800            continue;
1801        }
1802        let Some(task) = by_id.get(question.run.as_str()) else {
1803            continue;
1804        };
1805        question.abandon(format!(
1806            "task {} no longer waits for this answer",
1807            task.short()
1808        ));
1809        if let Err(e) = questions.put_in(&mut question, &ownership) {
1810            tracing::warn!(
1811                "could not retire question {} for task {}: {e:#}",
1812                question.short(),
1813                task.short()
1814            );
1815        }
1816    }
1817}
1818
1819/// What a finished run tells the queue about the task it came from.
1820///
1821/// A struct rather than a fourth and fifth boolean argument: the two flags
1822/// answer different questions about the same run, and a call site passing
1823/// `(…, true, false)` is one transposition away from refunding attempts
1824/// forever.
1825#[derive(Debug, Clone, Copy)]
1826pub struct Verdict {
1827    /// Where the graph stopped.
1828    pub status: RunStatus,
1829    /// The run opened a pull request.
1830    pub left_pr: bool,
1831    /// At least one seat was lost to a rate limit.
1832    pub quota_hit: bool,
1833    /// The run parked at a node boundary because it was asked to.
1834    pub parked: bool,
1835    /// The run never produced a single candidate a judge could look at.
1836    ///
1837    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1838    /// still have another candidate worth judging, in which case the loss was
1839    /// not the reason nothing came of the run. This is `true` only when the
1840    /// implement wave ended with nothing viable at all.
1841    pub no_viable_candidates: bool,
1842}
1843
1844/// Record a finished run against the task it came from.
1845///
1846/// Kept pure and separate from the loop because this mapping *is* the retry
1847/// policy, and a policy that can only be exercised by spawning a graph is a
1848/// policy nobody checks. The table:
1849///
1850/// | run status                           | task becomes        | attempt spent |
1851/// |---------------------------------------|---------------------|---------------|
1852/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1853/// | `Merged`, `Ready`                      | `Done`               | yes          |
1854/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1855/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1856/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1857/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1858/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1859/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1860/// | `Blocked` with a PR                    | `Held`               | yes          |
1861/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1862/// | `VerifiedNoop`                          | `Held`               | yes          |
1863/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1864///
1865/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1866/// deliberately: every candidate agreeing there is nothing to write is not a
1867/// machine fact about a rate limit, it is an unverified claim about the
1868/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1869/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1870/// claim could be wrong (a misread instruction, a stale check), and closing
1871/// the task automatically on an implementer's say-so would be the exact
1872/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1873/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1874/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1875/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1876/// claim regardless of whether the one already-spent attempt is refunded, and
1877/// [`Task::release`] resets the count to zero anyway the moment a human looks
1878/// at the evidence and lets it run again.
1879///
1880/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1881/// twice, together. A quorum lost to rate limits is a property of the machine
1882/// and not of the task, so the attempt is refunded and a reset quota picks
1883/// the work up where it stopped — and that is just as true when every
1884/// implement seat lost the same race and `after_implement` bails with nothing
1885/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1886/// machine fact. The `no_viable_candidates` guard is what keeps that row
1887/// narrow: a `Failed` run that produced a real candidate which then lost for
1888/// some other reason still spends the attempt, exactly like the quorum lost
1889/// to judges that answered with the wrong shape is ordinary flakiness, and
1890/// refunding *that* takes the bound off the retry loop entirely: run e633
1891/// stalled with `quota: []` after two judges wrote unusable JSON, was
1892/// refunded, and the next attempt paid for a fresh hour-long implement wave
1893/// before it could fail the same way. `max_attempts` exists precisely so
1894/// that cannot repeat forever.
1895///
1896/// A non-terminal status means `execute` returned while the graph was still
1897/// mid-flight, which is a bug rather than a verdict; it is treated as a
1898/// failure so that a task cannot loop on it either.
1899///
1900/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1901/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1902pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1903    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN, None)
1904}
1905
1906/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1907fn settle_in(
1908    task: &mut Task,
1909    verdict: Verdict,
1910    detail: &str,
1911    max_attempts: usize,
1912    p: &Phrases,
1913    state: Option<&RunState>,
1914) {
1915    // A parked run is the operator's own doing, and its work is intact on
1916    // disk. The task goes back in line with its attempt refunded so the next
1917    // loop resumes the same run - which `one_task` prefers over competing
1918    // again - and so that swapping the binary a few times cannot exhaust a
1919    // budget meant for agents that actually misbehaved.
1920    if verdict.parked {
1921        task.park(detail);
1922        return;
1923    }
1924    let completion = |task: &Task| match state {
1925        Some(state) => CompletionContext::from_run(
1926            CompletionActor::DaemonSettle,
1927            Some(detail.to_owned()),
1928            task,
1929            state,
1930        ),
1931        None => CompletionContext::new(
1932            CompletionActor::DaemonSettle,
1933            Some(detail.to_owned()),
1934            &crate::run::home(),
1935            task,
1936        ),
1937    };
1938    match verdict.status {
1939        RunStatus::Merged | RunStatus::Ready
1940            if task.pr_recovery.as_ref().is_some_and(|s| {
1941                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1942            }) =>
1943        {
1944            task.hold_manual(Some("Public delivery is not confirmed. Inspect the selected PR and run, then use recover-pr --disposition land with the intended source and validation configuration.".into()));
1945        }
1946        RunStatus::Merged | RunStatus::Ready => task.succeed(completion(task)),
1947        RunStatus::AlreadyInBase => task.already_landed(detail, completion(task)),
1948        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1949        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1950            task.stall(detail)
1951        }
1952        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1953        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1954        RunStatus::Blocked => task.fail(detail, max_attempts),
1955        RunStatus::VerifiedNoop => task.handed_off(detail),
1956        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1957    }
1958}
1959
1960/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1961/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1962/// itself has actually finished *and* its own last attempt is provably why:
1963/// this loads that run and requires `Merged`/`Ready` before touching
1964/// anything earlier in `runs`, since `Task::succeed` can also be called
1965/// directly on a task whose last attempt never landed at all.
1966///
1967/// Called right after whatever call set `task.status` to
1968/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1969/// `reclaim`'s, but also every other place a task can be closed by hand
1970/// without the loop ever settling it itself: `magi task done`
1971/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1972/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1973/// GitHub merge, say, exactly the workflow this repository's own
1974/// "Landing a run's winner by hand" documents — is just as much "this task's
1975/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1976/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1977/// forever, which is the exact backlog this status exists to clear. `pub`
1978/// for those two out-of-module callers; everything else about this stays
1979/// internal bookkeeping.
1980///
1981/// A run something is still actually driving is left alone: a
1982/// task cannot be `Done` while one of its *own* attempts is still in flight,
1983/// so a live one at this point can only be an unrelated process — a manual
1984/// `--resume` of this old, now-moot run — and rewriting under it would just
1985/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1986/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1987/// pair `run_report`/`run_detail` use for the same question elsewhere:
1988/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1989/// --resume` invoked by hand outside it, which `liveness` also checks via
1990/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1991/// (already terminal in some other way, or itself mid-run) is left untouched
1992/// too.
1993///
1994/// Best-effort, like the rest of this module's bookkeeping: a load or save
1995/// failure here is a `tracing::warn`, not a failed settle, and the next time
1996/// this same task's completion is recorded — or a daemon restart replays
1997/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1998/// separate reconciliation pass; if that gap ever matters in practice, one
1999/// can be added then.
2000///
2001/// `home` is a parameter, not the process-global [`crate::run::home`], for
2002/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
2003/// calls this with `ui.home`, which is `crate::run::home()` in a real
2004/// process but a fixture's own directory under test — falling through to
2005/// the global there would read and write through whichever home some other
2006/// test in the same binary happened to pin into that `OnceLock` first, not
2007/// the run this call actually means.
2008pub fn supersede_prior_runs(task: &Task, home: &Path) {
2009    if task
2010        .completion_history
2011        .last()
2012        .is_some_and(|event| event.discard)
2013    {
2014        return;
2015    }
2016    let now = Timestamp::now();
2017    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
2018    // right behind a `Merged`/`Ready` verdict) from one set directly by
2019    // `magi task done`/its web equivalent/the conductor on a task whose last
2020    // recorded attempt never actually landed - that requires reading the
2021    // run itself, which is exactly what this does before trusting anything
2022    // in `runs` is safe to relabel.
2023    let last_run_succeeded = task
2024        .runs
2025        .last()
2026        .and_then(|id| RunState::load_under(id, home).ok())
2027        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
2028    for id in task.superseded_attempts(last_run_succeeded) {
2029        let mut state = match RunState::load_under(id, home) {
2030            Ok(s) => s,
2031            Err(e) => {
2032                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
2033                continue;
2034            }
2035        };
2036        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
2037            continue;
2038        }
2039        let daemon_claims = is_working_on(home, id, now);
2040        if state.liveness(daemon_claims) == Liveness::Live {
2041            continue;
2042        }
2043        state.status = RunStatus::Superseded;
2044        if let Err(e) = state.save_under(home) {
2045            tracing::warn!("could not mark run {id} superseded: {e:#}");
2046        }
2047    }
2048}
2049
2050/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
2051/// finish the moment it was called, because one of its earlier attempts was
2052/// still live then - a `magi run --resume` invoked by hand on an old run,
2053/// most likely.
2054///
2055/// That skip is correct at the time (rewriting under a run something is
2056/// still actively saving would just be undone), but recording a completion
2057/// does not schedule another settlement, so without this nothing would look at it
2058/// again: if that manual process later ends anywhere other than
2059/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
2060/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
2061/// backlog this status exists to clear. Called on the same idle-only
2062/// cadence as [`janitor`], next to it rather than folded into it: this
2063/// walks `queue` and `janitor` never otherwise needs one.
2064///
2065/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
2066/// more than one attempt, every pass: each call is a handful of local file
2067/// reads bounded by that task's own attempt count, the same order of cost
2068/// [`clean::fold_due`] already pays scanning every run on disk on the same
2069/// cadence, and a task already fully resolved costs one failed liveness
2070/// check turned no-op the moment its lingering attempt is no longer live.
2071fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2072    for task in queue.list() {
2073        if task.status != TaskStatus::Done || task.runs.len() < 2 {
2074            continue;
2075        }
2076        supersede_prior_runs(&task, home);
2077    }
2078}
2079
2080/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
2081/// task ends up held.
2082///
2083/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
2084/// dead daemon never got back to) share this, so the two cannot drift into
2085/// disagreeing about which held tasks get a diagnostic.
2086fn settle_and_diagnose(
2087    task: &mut Task,
2088    verdict: Verdict,
2089    detail: &str,
2090    max_attempts: usize,
2091    state: &RunState,
2092) {
2093    let p = phrases(&state.config.graph.language);
2094    // Shared by normal completion and crash recovery, under the task claim.
2095    // No new attempt can own the task until the old driver has exited.
2096    if let Some(d) = &state.merge_decision {
2097        use crate::merge_decision as md;
2098        if task
2099            .execution_runs()
2100            .last()
2101            .is_some_and(|id| id != &state.id)
2102        {
2103            return;
2104        }
2105        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2106            task.succeed(CompletionContext::from_run(
2107                CompletionActor::DaemonSettle,
2108                Some(format!("Owner merge decision {}: {}", d.question, d.choice)),
2109                task,
2110                state,
2111            ));
2112        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2113            if state.liveness(false) != Liveness::Dead {
2114                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2115                return;
2116            }
2117            let replacement = md::Replacement {
2118                question: d.question.clone(),
2119                run: state.id.clone(),
2120                pr: d.target.pr.clone(),
2121                agent: agent.to_owned(),
2122                context: format!(
2123                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2124                    d.target.pr,
2125                    state.id,
2126                    serde_json::to_string(&state.reviews).unwrap_or_default()
2127                ),
2128            };
2129            task.requeue();
2130            task.pr_recovery = None;
2131            task.review_of = None;
2132            task.replacement = Some(replacement);
2133        } else {
2134            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2135                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2136            } 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())) }));
2137        }
2138        task.mark_action_applied(&d.question);
2139        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2140            task.decision_effects
2141                .insert(d.question.clone(), format!("decision: {}", d.choice));
2142        }
2143        if let Some(pass) = state.passes.last() {
2144            task.record_pass_at(
2145                &state.id,
2146                pass.index,
2147                Some(pass.started_at),
2148                task.attempts,
2149                None,
2150            );
2151        }
2152        return;
2153    }
2154    if let Some(replacement) = &task.replacement
2155        && !state.parked
2156        && state.resource_block.is_none()
2157        && (state.viable().is_empty()
2158            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2159    {
2160        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)));
2161        return;
2162    }
2163    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2164        let mut agents: Vec<_> = state
2165            .quota
2166            .iter()
2167            .filter(|q| {
2168                q.cause == crate::agent::QuotaCause::Authentication
2169                    && state
2170                        .passes
2171                        .last()
2172                        .is_none_or(|pass| q.at >= pass.started_at)
2173            })
2174            .map(|q| q.agent.as_str())
2175            .collect();
2176        agents.sort_unstable();
2177        agents.dedup();
2178        if !agents.is_empty() {
2179            task.stall(detail);
2180            task.notice_cause("agent-authentication", None, None);
2181            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2182            return;
2183        }
2184    }
2185    let attempts_before = task.attempts;
2186    // A run that stopped because a shared resource stayed busy was never a
2187    // failure of the task or of an agent. Earlier nodes may have run; only
2188    // the blocked operation lacks a result. The attempt is
2189    // refunded and the task is held by the machine, under a reason `triage`
2190    // can re-check, so the same run resumes with the same agents once the
2191    // resource is free. A park request still wins (it is the operator's).
2192    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2193        let disk_checked_at = task.disk_checked_at;
2194        task.notice_cause(
2195            &format!("resource:{}:{}", block.kind, block.node),
2196            None,
2197            None,
2198        );
2199        task.last_error = Some(detail.to_owned());
2200        task.diagnostic = None;
2201        task.attempts = task.attempts.saturating_sub(1);
2202        if block.kind == "agent authentication" {
2203            task.hold_machine(Some(format!(
2204                "[authentication] {}; no attempt was spent",
2205                block.detail
2206            )));
2207        } else if block.kind == "agent usage limit" {
2208            // Usage limits keep the existing cooldown-and-resume policy.
2209            if let Some(agent) = &state.config.graph.selected_implementer {
2210                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.")));
2211            } else {
2212                task.status = TaskStatus::Failed;
2213                task.last_error = Some(block.detail.clone());
2214            }
2215        } else if block.kind == "disk pressure" {
2216            task.hold_machine(Some(format!(
2217                "{}{}",
2218                crate::disk::RUNNING_PRESSURE,
2219                block.detail
2220            )));
2221        } else {
2222            task.hold_machine(Some(format!(
2223                "{}{}; no attempt was spent; resume to retry the affected operation",
2224                crate::cache::RESOURCE_HOLD,
2225                block.description()
2226            )));
2227        }
2228        if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2229            && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2230        {
2231            task.mark_disk_capacity();
2232            task.disk_checked_at = disk_checked_at;
2233        }
2234        if let Some(pass) = state.passes.last() {
2235            task.record_pass_at(
2236                &state.id,
2237                pass.index,
2238                Some(pass.started_at),
2239                attempts_before,
2240                None,
2241            );
2242        }
2243        return;
2244    }
2245    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2246        state.parked
2247            && state.status == RunStatus::Landing
2248            && state
2249                .pr_pushed_head
2250                .as_ref()
2251                .is_none_or(|h| h == &hold.head)
2252            && task.execution_runs().last() == Some(&state.id)
2253    }) {
2254        // Settlement and crash recovery share this idempotency key. A later
2255        // explicit resume is a new pass and may refund its own attempt once.
2256        let pass = state.passes.last().map_or(0, |p| p.index);
2257        if !task
2258            .passes
2259            .iter()
2260            .any(|p| p.run == state.id && p.pass_index == pass)
2261        {
2262            task.attempts = task.attempts.saturating_sub(1);
2263        }
2264        task.hold_machine(Some(format!(
2265            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2266            hold.question
2267        )));
2268        task.last_error = Some(detail.to_owned());
2269        task.diagnostic = None;
2270        task.record_pass_at(
2271            &state.id,
2272            pass,
2273            state.passes.last().map(|p| p.started_at),
2274            attempts_before,
2275            Some(crate::run::ParkCause::Question),
2276        );
2277        return;
2278    }
2279    let unresolved = task.hold_notice_cause.clone();
2280    if state.base_sync_blocked() {
2281        // No automatic retry may turn a retained sync stop into a new competition.
2282        task.hold_machine(Some(detail.to_owned()));
2283        task.last_error = Some(detail.to_owned());
2284    } else if !verdict.parked
2285        && task
2286            .pr_recovery
2287            .as_ref()
2288            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2289        && matches!(
2290            verdict.status,
2291            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2292        )
2293    {
2294        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2295            task.succeed(CompletionContext::from_run(
2296                CompletionActor::DaemonSettle,
2297                Some(detail.to_owned()),
2298                task,
2299                state,
2300            ));
2301        } else {
2302            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()));
2303        }
2304    } else if !verdict.parked
2305        && task.pr_recovery.is_some()
2306        && matches!(
2307            verdict.status,
2308            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2309        )
2310        && !verdict.quota_hit
2311    {
2312        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.")));
2313    } else {
2314        settle_in(task, verdict, detail, max_attempts, p, Some(state));
2315    }
2316    if !verdict.parked
2317        && !verdict.quota_hit
2318        && matches!(
2319            verdict.status,
2320            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2321        )
2322    {
2323        task.recovery_failed(state);
2324    }
2325    if state.prep_failure.is_some() {
2326        // Minting a run whose candidates could not be prepared is not work
2327        // on a newly approved attempt. Keep the unresolved outcome anchor.
2328        task.hold_notice_cause = unresolved;
2329        task.startup_notice_cause("startup-candidates");
2330    }
2331    // Written here, where the refund (or not) is decided, so the history is a
2332    // fact and not a later guess from the run's status.
2333    if let Some(pass) = state.passes.last() {
2334        let parked = match &pass.end {
2335            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2336            _ => None,
2337        };
2338        task.record_pass_at(
2339            &state.id,
2340            pass.index,
2341            Some(pass.started_at),
2342            attempts_before,
2343            parked,
2344        );
2345    }
2346    if task.status == TaskStatus::Held {
2347        if state.base_sync_blocked() {
2348            task.base_sync_notice(state);
2349        } else if state.prep_failure.is_none() {
2350            task.notice_cause(
2351                label(verdict.status),
2352                Some(&state.id),
2353                state.passes.last().map(|p| p.index),
2354            );
2355        }
2356        task.diagnostic = diagnostic(state);
2357        note_open_question(task, &state.id, p);
2358    }
2359}
2360
2361/// If `task` is held with a `magi ask` question still open on `run`, name the
2362/// question in [`Task::hold_reason`] rather than leaving the hold reading
2363/// only [`describe`]'s run summary.
2364///
2365/// This is the shape task 20260928-191407-05fd left underspecified: an
2366/// implementer settled a verified no-op and filed a question for the
2367/// operator, and the hold that followed said nothing about the question
2368/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2369/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2370/// marker) and must keep seeing it unchanged.
2371///
2372/// Best-effort: an unreadable question store must not stop a run from
2373/// settling, so this is a no-op rather than a propagated error when
2374/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2375fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2376    let Some(home) = crate::run::try_home() else {
2377        return;
2378    };
2379    let open = Questions::at(home.join("questions")).open_for(run);
2380    let Some(q) = open.first() else {
2381        return;
2382    };
2383    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2384    decisions.sort_unstable();
2385    task.notice_cause(
2386        &format!("questions:{}", decisions.join(",")),
2387        Some(run),
2388        None,
2389    );
2390    let base = task.hold_reason.clone().unwrap_or_default();
2391    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2392}
2393
2394/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2395/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2396/// by some other means entirely, like a manual `magi run` resume that
2397/// finishes the graph outside the queue's bookkeeping.
2398///
2399/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2400/// `settle` is separate from `attempt`: a task recovered this way must land
2401/// exactly where a live daemon would have put it — the same policy table,
2402/// not a second one that quietly drifts from it — and that is only checkable
2403/// without spawning a real run.
2404fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2405    if let Some(request) = task.sync_only.clone() {
2406        crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2407        return;
2408    }
2409    match last_run {
2410        Some(state) => {
2411            let verdict = Verdict {
2412                status: state.status,
2413                left_pr: state.pr.is_some(),
2414                quota_hit: state.quota.iter().any(|loss| {
2415                    state
2416                        .passes
2417                        .last()
2418                        .is_none_or(|pass| loss.at >= pass.started_at)
2419                }),
2420                parked: state.parked,
2421                no_viable_candidates: state.viable().is_empty(),
2422            };
2423            let detail = format!(
2424                "{}{}",
2425                phrases(&state.config.graph.language).recovered_running,
2426                describe(&state)
2427            );
2428            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2429        }
2430        None => {
2431            // No run, so no config of its own: `language` is the task's
2432            // repository's setting, read by the caller.
2433            let why = phrases(language).no_run_to_recover;
2434            task.last_error = Some(why.to_owned());
2435            // The phone shows `hold_reason`, so a task held by the machine
2436            // says why there too and not only in `last_error`.
2437            task.notice_cause("missing-run", None, None);
2438            task.hold_machine(Some(why.to_owned()));
2439        }
2440    }
2441}
2442
2443/// Find every task left at `running` that no live process is actually
2444/// driving, and settle each one against whatever its last run became.
2445///
2446/// # Why a claim is proof, not a guess
2447///
2448/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2449/// `running`, and the guard is held for the task's whole time in that status:
2450/// `attempt` does not return, and the loop does not move past the scope
2451/// holding the claim, until the run has settled. So a `running` task whose
2452/// lock is gone cannot have a live owner — this process or any other —
2453/// without needing a staleness threshold or a pid check the way
2454/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2455/// task that never got as far as `running` at all. Taking the claim here is
2456/// the whole test: it either fails, because something really does hold it
2457/// and the task is left alone, or it succeeds, which is the proof — and it is
2458/// kept for the rest of the decision so nothing else can start a competing
2459/// run while this one is being written.
2460///
2461/// Called on every poll, not only at startup, for the reason
2462/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2463/// keep noticing this, not only on the one morning it happened to restart.
2464fn reclaim_orphaned_running(
2465    queue: &Queue,
2466    max_attempts: usize,
2467    live_workers: &std::collections::BTreeSet<String>,
2468) -> Vec<String> {
2469    let mut reclaimed = Vec::new();
2470    for listed in queue.list() {
2471        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2472            continue;
2473        }
2474        let Ok(_claim) = queue.claim(&listed.id) else {
2475            continue;
2476        };
2477        // Re-read under the claim: a release or an edit landed by a human
2478        // between the listing above and the claim just taken must not be
2479        // clobbered by a decision based on the stale copy.
2480        let Ok(mut task) = queue.get(&listed.id) else {
2481            continue;
2482        };
2483        if task.status != TaskStatus::Running {
2484            continue;
2485        }
2486        let last_run = task
2487            .execution_runs()
2488            .last()
2489            .and_then(|id| RunState::load(id).ok());
2490        // `execute` normally abandons a run's own open questions the moment
2491        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2492        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2493        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2494        // with the question still `open`, because the process died before
2495        // reaching that call. `reclaim` itself stays pure on purpose (see its
2496        // own doc), so the same cleanup runs here instead, against the run
2497        // this reclaim is already reading. `settle_run` costs nothing when
2498        // `execute` already got there first.
2499        if let Some(state) = &last_run
2500            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2501        {
2502            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2503        }
2504        let language = if last_run.is_none() {
2505            language_of(&task, Path::new("."))
2506        } else {
2507            String::new()
2508        };
2509        reclaim(&mut task, last_run, max_attempts, &language);
2510        if task.status == TaskStatus::Done {
2511            supersede_prior_runs(&task, &crate::run::home());
2512        }
2513        record(queue, &mut task);
2514        reclaimed.push(task.id.clone());
2515    }
2516    reclaimed
2517}
2518
2519/// Find every run whose `run.json` is provably dead — every seat it still
2520/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2521/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2522/// not merely "no daemon claims it" — and fail it, clearing the leftover
2523/// active seats so the run stops reading as `implementing` (or whichever
2524/// node) forever.
2525///
2526/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2527/// `running`, using whatever `run.json` already says — but nothing in that
2528/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2529/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2530/// never got back to sits exactly where it was left: `active` full of seats
2531/// nobody will ever answer for, `status` stuck on whatever node was in
2532/// flight. `magi show` already tells an operator this in prose (`no live
2533/// daemon claims this run right now`); this is what makes that fact durable
2534/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2535/// stay stuck once nothing is driving it.
2536///
2537/// Runs on every poll, not only at startup, for the reason
2538/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2539/// daemon up for days must keep noticing a run some other, now-dead, daemon
2540/// left behind just as readily as one it trips over on the way up.
2541///
2542/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2543/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2544/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2545/// `runs` directory instead: `home` here is a parameter precisely so a test
2546/// can point it away from the operator's real history (see [`drive`]'s own
2547/// doc), and a scan that fell through to the global home anyway would walk
2548/// whichever directory some *other* process or test pinned into that
2549/// `OnceLock` first — mutating runs this call was never handed.
2550fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2551    reclaim_abandoned_runs_with(
2552        home,
2553        now,
2554        crate::proc::pid_status,
2555        crate::proc::process_started_at,
2556    )
2557}
2558
2559/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2560/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2561/// for the identical reason: this sweep's real damage (wiping a run's active
2562/// seats and failing it) has to be provable against an injected answer in a
2563/// test, not just the real process table.
2564fn reclaim_abandoned_runs_with<F, G>(
2565    home: &Path,
2566    now: Timestamp,
2567    query: F,
2568    identity: G,
2569) -> Vec<String>
2570where
2571    F: Fn(u32) -> Option<bool>,
2572    G: Fn(u32) -> Option<String>,
2573{
2574    let mut abandoned = Vec::new();
2575    for entry in std::fs::read_dir(home.join("runs"))
2576        .into_iter()
2577        .flatten()
2578        .flatten()
2579    {
2580        let id = entry.file_name().to_string_lossy().into_owned();
2581        if !crate::run::is_run_id(&id) {
2582            continue;
2583        }
2584        // Serialize the proof and save with claims and takeover: a new
2585        // execution must not be overwritten after the liveness observation.
2586        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2587            continue;
2588        };
2589        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2590        // that module's docs for why a run this cannot parse is left alone
2591        // rather than guessed at. A different schema number is not that: this
2592        // touches only `status` and `active`, never a field whose meaning a
2593        // schema bump changed, so an old record's values serve this exactly
2594        // as well as a current one's (see `clean::read_state`'s own doc for
2595        // the same reasoning applied to folding).
2596        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2597            continue;
2598        };
2599        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2600            continue;
2601        };
2602        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2603            continue;
2604        }
2605        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2606        // it", which is also the normal, healthy shape of a manual `magi
2607        // run` / `magi review` sharing this same home — this scan walks
2608        // every run on disk, not only ones this daemon itself started. Such
2609        // a run's active seats can legitimately sit past their own timeout
2610        // for a little while (the CLI finishing up, its result still being
2611        // collected) without the process driving it having died. `liveness`
2612        // is what actually tells the two apart, by corroborating
2613        // `driver_pid` against the process it names — see its own doc. Only
2614        // its strongest, provable answer licenses wiping this run's active
2615        // seats and failing it out from under whatever is still running it.
2616        let daemon_claims = is_working_on(home, &id, now);
2617        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2618            != crate::run::Liveness::Dead
2619        {
2620            continue;
2621        }
2622        state.abandon("daemon");
2623        if let Err(e) = state.save_under(home) {
2624            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2625            continue;
2626        }
2627        // This run never passes through `Runner::execute` again, so its end
2628        // is announced here.
2629        if let Some(notice) = notices::run_ended(&state) {
2630            notices::raise_in(home, notice);
2631        }
2632        // The seat that asked is gone for good now, exactly like any other
2633        // door `graph::Runner::settle_questions` closes the moment `status`
2634        // lands somewhere non-resumable - see that method's own doc. Nothing
2635        // else reaches this one before the next `janitor()` startup pass
2636        // (`clean::abandon_settled_questions`), and a daemon that stays up
2637        // for days must not leave an open question badging the operator
2638        // until it happens to restart.
2639        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2640            tracing::warn!("abandon questions for {id}: {e:#}");
2641        }
2642        abandoned.push(id);
2643    }
2644    abandoned
2645}
2646
2647#[derive(Debug, Clone, Serialize, Deserialize)]
2648struct TaskWorker {
2649    opts: Opts,
2650    queue: PathBuf,
2651    task: String,
2652    #[serde(default)]
2653    lane: PermitKind,
2654    #[serde(default)]
2655    standalone: bool,
2656}
2657
2658fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2659    Ok(crate::worker::active(home)?
2660        .into_iter()
2661        .filter(|job| job.kind == "task")
2662        .collect())
2663}
2664
2665fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2666    task_jobs(home)?
2667        .into_iter()
2668        .filter_map(
2669            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2670                Ok(request) if !request.standalone => Some(Ok(job)),
2671                Ok(_) => None,
2672                Err(error) => Some(Err(error.into())),
2673            },
2674        )
2675        .collect()
2676}
2677
2678/// Whether an independent scheduler can be controlled without its web parent.
2679#[must_use]
2680pub fn managed(home: &Path) -> bool {
2681    match crate::worker::active(home) {
2682        Err(error) => {
2683            tracing::error!("cannot determine scheduler ownership: {error:#}");
2684            true
2685        }
2686        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2687        Ok(_) => {
2688            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2689                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2690        }
2691    }
2692}
2693
2694/// Start a detached, singleton scheduler using this executable generation.
2695pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2696    anyhow::ensure!(
2697        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2698        "the scheduler is stopping; wait for retirement before starting it again"
2699    );
2700    crate::worker::spawn(
2701        home,
2702        "scheduler",
2703        "scheduler",
2704        serde_json::to_value(opts.absolute()?)?,
2705    )
2706    .await
2707}
2708
2709fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2710    home.join("worker-parks").join(format!("{}.json", job.id))
2711}
2712
2713fn request_task_park(
2714    home: &Path,
2715    job: &crate::worker::Job,
2716    cause: crate::run::ParkCause,
2717) -> Result<()> {
2718    let path = park_request_path(home, job);
2719    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2720    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2721    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2722}
2723
2724/// Stop dispatch immediately; only an explicit park reaches existing workers.
2725pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2726    if control == crate::worker::Control::Park {
2727        for job in owned_task_jobs(home)? {
2728            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2729        }
2730    }
2731    crate::worker::request(home, "scheduler", control)
2732}
2733
2734/// Resolve what a restart would replace without signalling the scheduler.
2735pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
2736    if let Some(job) = crate::worker::active(home)?
2737        .into_iter()
2738        .find(|job| job.kind == "scheduler")
2739    {
2740        return serde_json::from_value(job.payload)
2741            .context("read detached scheduler options")
2742            .map(Some);
2743    }
2744    if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2745        && crate::worker::try_lease(home, "scheduler")?.is_none()
2746    {
2747        let path = home.join("scheduler-options.json");
2748        let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2749        return serde_json::from_slice(&body)
2750            .context("decode detached scheduler options")
2751            .map(Some);
2752    }
2753    Ok(None)
2754}
2755
2756/// Replace the scheduler, leaving all active task and conversation jobs alone.
2757pub async fn restart_detached(home: &Path) -> Result<()> {
2758    let Some(opts) = scheduler_restart_options(home)? else {
2759        return Ok(());
2760    };
2761    request_control(home, crate::worker::Control::Stop)?;
2762    loop {
2763        let reserved = crate::worker::active(home)?
2764            .iter()
2765            .any(|job| job.kind == "scheduler");
2766        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2767            break;
2768        }
2769        tokio::time::sleep(Duration::from_millis(100)).await;
2770    }
2771    spawn_detached(home, &opts).await?;
2772    Ok(())
2773}
2774
2775/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2776pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2777    let opts: Opts = serde_json::from_value(payload)?;
2778    let _ = home;
2779    serve_until(opts, Stop::new()).await
2780}
2781
2782/// Execute and settle one task with the queue claim owned by this process.
2783pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2784    let request: TaskWorker = serde_json::from_value(payload)?;
2785    let queue = Queue::at(request.queue);
2786    let key = format!("task:{}", request.task);
2787    let job = task_jobs(home)?
2788        .into_iter()
2789        .find(|job| job.key == key)
2790        .context("task worker reservation is missing")?;
2791    let park_path = park_request_path(home, &job);
2792    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2793    // our durable reservation. Never execute before that ownership hand-off.
2794    let _claim = loop {
2795        match queue.claim(&request.task) {
2796            Ok(claim) => break claim,
2797            // Only contention (the claim file exists) is worth waiting out; an
2798            // I/O failure must end this worker instead of pinning its lane.
2799            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2800                return Err(e.context("claim the task for its worker"));
2801            }
2802            Err(_) => {
2803                sweep_stale_claims(&queue, STALE_CLAIM);
2804                tokio::time::sleep(Duration::from_millis(50)).await;
2805            }
2806        }
2807    };
2808    let mut task = queue.get(&request.task)?;
2809    if !task.status.runnable()
2810        || (!request.standalone
2811            && request.lane
2812                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2813    {
2814        return Ok(());
2815    }
2816    let stop = Stop::new();
2817    let watcher = {
2818        let home = home.to_path_buf();
2819        let stop = stop.clone();
2820        let park_path = park_path.clone();
2821        tokio::spawn(async move {
2822            loop {
2823                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2824                    let cause = std::fs::read(&park_path)
2825                        .ok()
2826                        .and_then(|body| serde_json::from_slice(&body).ok())
2827                        .unwrap_or(crate::run::ParkCause::Operator);
2828                    stop.park(cause);
2829                    return;
2830                }
2831                tokio::time::sleep(Duration::from_millis(200)).await;
2832            }
2833        })
2834    };
2835    let quota = if request.standalone {
2836        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2837    } else {
2838        let status = Arc::new(Mutex::new(Status::new()));
2839        Box::pin(attempt(
2840            &request.opts,
2841            &queue,
2842            &status,
2843            &stop,
2844            crate::graph::Pause::new(),
2845            &mut task,
2846        ))
2847        .await
2848    };
2849    watcher.abort();
2850    let _ = std::fs::remove_file(park_path);
2851    persist_cooldown(home, &quota).await?;
2852    Ok(())
2853}
2854
2855/// Launch the standalone task worker with a claim-to-reservation handoff.
2856/// Returns only after the worker owns a durable execution reservation.
2857pub async fn spawn_claimed(
2858    home: &Path,
2859    opts: &Opts,
2860    queue: &Queue,
2861    task: &Task,
2862    claim: crate::queue::Claim,
2863) -> Result<crate::worker::Job> {
2864    let request = TaskWorker {
2865        opts: opts.absolute()?,
2866        queue: std::path::absolute(queue.root())?,
2867        task: task.id.clone(),
2868        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2869        standalone: true,
2870    };
2871    let job = crate::worker::spawn(
2872        home,
2873        "task",
2874        &format!("task:{}", task.id),
2875        serde_json::to_value(request)?,
2876    )
2877    .await?;
2878    drop(claim);
2879    Ok(job)
2880}
2881
2882/// Transfer a standalone caller's claim only after the detached worker is live,
2883/// then follow that worker to its final (non-automatically-retrying) outcome.
2884pub async fn run_detached_claimed(
2885    opts: &Opts,
2886    queue: &Queue,
2887    task: &mut Task,
2888    claim: crate::queue::Claim,
2889) -> Result<()> {
2890    let home = crate::run::home();
2891    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2892    loop {
2893        // Reconcile execution leases even without a scheduler. A dead worker
2894        // must become a reported failure, never an infinite persisted wait.
2895        crate::worker::active(&home)?;
2896        let current = crate::worker::get(&home, &job.id)?;
2897        if matches!(
2898            current.status,
2899            crate::worker::Status::Finished | crate::worker::Status::Failed
2900        ) {
2901            *task = queue.get(&task.id)?;
2902            anyhow::ensure!(
2903                current.status != crate::worker::Status::Failed,
2904                "task worker failed: {}",
2905                current.result.as_deref().unwrap_or("unknown failure")
2906            );
2907            return Ok(());
2908        }
2909        tokio::time::sleep(Duration::from_millis(200)).await;
2910    }
2911}
2912
2913async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2914    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2915        let _lease = loop {
2916            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2917                break lease;
2918            }
2919            tokio::time::sleep(Duration::from_millis(10)).await;
2920        };
2921        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2922            let path = home.join("task-quota-cooldown.json");
2923            let temporary = path.with_extension("json.tmp");
2924            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2925            std::fs::rename(temporary, path)?;
2926        }
2927    }
2928    Ok(())
2929}
2930
2931fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2932    match std::fs::read(home.join("task-quota-cooldown.json")) {
2933        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2934        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2935        Err(error) => Err(error.into()),
2936    }
2937}
2938
2939/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2940///
2941/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2942/// sets, so there is one loop body rather than two that drift apart the first
2943/// time the retry policy changes on only one of them.
2944pub async fn serve(opts: Opts) -> Result<()> {
2945    tracing::info!(
2946        "automatic update and restart requires magi web; standalone serve does not restart"
2947    );
2948    serve_until(opts, Stop::new()).await
2949}
2950
2951/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2952///
2953/// A stop retires dispatch promptly, including while a worker launch is being
2954/// acknowledged. Already reserved workers own their attempts independently and
2955/// finish with their started executable. Explicit park additionally forwards
2956/// durable park requests; neither scheduler retirement nor update does so.
2957///
2958/// While the queue is empty the stop is honoured within one wakeup rather than
2959/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2960/// caller that taps stop does not sit through the remainder of a sleep.
2961pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2962    let opts = opts.absolute()?;
2963    let home = crate::run::home();
2964    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2965        .context("another scheduler already owns this home")?;
2966    if let Some(reading) = read_status(&home)
2967        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2968    {
2969        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2970    }
2971    if !crate::worker::active(&home)?
2972        .iter()
2973        .any(|job| job.kind == "scheduler")
2974    {
2975        crate::worker::clear_control(&home, "scheduler")?;
2976    }
2977    std::fs::write(
2978        home.join("scheduler-options.json"),
2979        serde_json::to_vec(&opts)?,
2980    )?;
2981    let control = {
2982        let home = home.clone();
2983        let stop = stop.clone();
2984        tokio::spawn(async move {
2985            loop {
2986                match crate::worker::control(&home, "scheduler").ok().flatten() {
2987                    Some(crate::worker::Control::Park) => {
2988                        let _ = request_control(&home, crate::worker::Control::Park);
2989                        stop.park(crate::run::ParkCause::Operator);
2990                        break;
2991                    }
2992                    Some(crate::worker::Control::Stop) => {
2993                        stop.stop();
2994                        break;
2995                    }
2996                    None => {}
2997                }
2998                tokio::time::sleep(Duration::from_millis(100)).await;
2999            }
3000        })
3001    };
3002    let signal = {
3003        let stop = stop.clone();
3004        tokio::spawn(async move {
3005            if tokio::signal::ctrl_c().await.is_ok() {
3006                stop.stop();
3007                tracing::info!("scheduler shutdown requested; independent workers continue");
3008            }
3009        })
3010    };
3011
3012    let worktrees_root = opts
3013        .worktrees_root
3014        .clone()
3015        .unwrap_or_else(crate::run::default_worktree_root);
3016    let outcome = drive(
3017        &opts,
3018        &Queue::open(),
3019        &status_path(),
3020        &crate::run::home(),
3021        &worktrees_root,
3022        &stop,
3023    )
3024    .await;
3025
3026    signal.abort();
3027    control.abort();
3028    outcome
3029}
3030
3031/// The loop proper: setup, poll, teardown, with the queue and the status file
3032/// supplied rather than discovered.
3033///
3034/// All three of `home`, `worktrees_root` and the queue/status paths are
3035/// parameters rather than resolved here, for the same reason:
3036/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
3037/// so a unit test that pinned it would fight every other test in the binary,
3038/// and a loop that resolved its own worktree bay could only be exercised
3039/// against the operator's real `~/wt/<repo>` - publishing over a live
3040/// daemon's status file, claiming tasks out of a live backlog, and, since
3041/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
3042/// whatever the operator actually has on disk.
3043async fn drive(
3044    opts: &Opts,
3045    queue: &Queue,
3046    status_file: &Path,
3047    home: &Path,
3048    worktrees_root: &Path,
3049    stop: &Stop,
3050) -> Result<()> {
3051    // The status file is a *snapshot*, not a stream of events: a reader only
3052    // ever wants the latest values, and every tick rewrites the whole file
3053    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
3054    // while an mpsc channel would force the loop to re-send unchanged fields on
3055    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
3056    // for no gain. The lock is only ever held across a field assignment, never
3057    // across an await.
3058    let recovery_cfg = prepare(&opts.repo, opts).ok();
3059    let daemon_cfg = recovery_cfg
3060        .as_ref()
3061        .map(|c| c.daemon.clone())
3062        .unwrap_or_default();
3063    let reconciled = crate::driver::reconcile(home);
3064    if !reconciled.is_empty() {
3065        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3066    }
3067    let mut initial_status = Status::new();
3068    let owned = owned_task_jobs(home)?;
3069    initial_status.current = current_work(home, Timestamp::now())
3070        .into_iter()
3071        .filter(|current| {
3072            owned
3073                .iter()
3074                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3075        })
3076        .collect();
3077    initial_status.idle = initial_status.current.is_empty();
3078    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3079        recovery_cfg.as_ref(),
3080        daemon_cfg.max_deputies,
3081    ));
3082    let status = Arc::new(Mutex::new(initial_status));
3083    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3084    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3085
3086    // Read once at startup, not per task: how many runs this loop drives at
3087    // once is a property of the machine running it, not of whichever
3088    // repository a given task happens to name - see
3089    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
3090    // fact in the same sense the agent roster is.
3091    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3092
3093    tracing::info!(
3094        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3095        queue.root().display(),
3096        opts.poll.as_secs(),
3097        opts.max_attempts,
3098        concurrency,
3099        if daemon_cfg.pause_for_interrupts {
3100            ", interrupts enabled"
3101        } else {
3102            ""
3103        }
3104    );
3105
3106    let outcome = tokio::select! {
3107        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3108            max_concurrent: concurrency,
3109            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3110            recovery_cfg,
3111        }) => outcome,
3112        () = async {
3113            while !stop.stopped() {
3114                tokio::time::sleep(Duration::from_millis(25)).await;
3115            }
3116        } => {
3117            if stop.parking() {
3118                request_control(home, crate::worker::Control::Park)?;
3119            }
3120            Ok(())
3121        }
3122    };
3123
3124    stop.busy.store(0, Ordering::SeqCst);
3125    beat.abort();
3126    clear_status_at(status_file);
3127    outcome
3128}
3129
3130/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3131/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3132pub(crate) fn release_watch_settings_from_config(
3133    home: &Path,
3134    repo: &Path,
3135    cfg: &Config,
3136) -> (Vec<PathBuf>, u64) {
3137    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3138        .into_iter()
3139        .map(|r| r.path)
3140        .collect();
3141    // Repositories the daemon has worked in, wherever they live: a task may
3142    // name one outside `[repos] roots`, and its release PR must be watched too.
3143    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3144        .list()
3145        .into_iter()
3146        .map(|t| t.repo)
3147        .collect();
3148    let runs = home.join("runs");
3149    for id in crate::run::list_ids_in(&runs) {
3150        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3151            .ok()
3152            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3153            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3154        known.extend(repo);
3155    }
3156    for k in known {
3157        let k = k.canonicalize().unwrap_or(k);
3158        if k.join(".git").exists() && !paths.contains(&k) {
3159            paths.push(k);
3160        }
3161    }
3162    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3163    if !paths.contains(&own) {
3164        paths.push(own);
3165    }
3166    (paths, cfg.daemon.release_stall_minutes)
3167}
3168
3169/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3170const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3171
3172/// Refresh the status file on a fixed tick.
3173///
3174/// Separate from the loop because a run takes tens of minutes: a status file
3175/// written only between tasks would look stale for the whole of every run, and
3176/// a reader would report the daemon dead exactly while it was busiest.
3177async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3178    loop {
3179        tokio::time::sleep(HEARTBEAT).await;
3180        let snapshot = {
3181            let mut guard = lock(&status);
3182            guard.updated_at = Timestamp::now();
3183            guard.clone()
3184        };
3185        if let Err(e) = write_status_to(&path, &snapshot) {
3186            // A failed heartbeat must not take the daemon down: the loop is the
3187            // product, the status file is only the window onto it.
3188            tracing::warn!("could not refresh the daemon status file: {e:#}");
3189        }
3190    }
3191}
3192
3193/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3194/// if so, whether that wait is over.
3195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3196enum LandResume {
3197    /// The task's last run is not parked on a land approval; schedule it
3198    /// like any other candidate.
3199    NotLanding,
3200    /// Parked in `land`, waiting on a question nobody has answered yet.
3201    /// Left alone: attempting it now would only re-observe the same pull
3202    /// request and park again, spending a `gh` call on a decision that has
3203    /// not changed since the last time this was checked.
3204    StillWaiting,
3205    /// Parked in `land`, and the question is settled - answered or
3206    /// abandoned. Resuming this is the one kind of candidate that must not
3207    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3208    Ready,
3209}
3210
3211/// Classify a runnable candidate by whether it is parked on a land-merge
3212/// approval. Read-only - no claim taken, nothing written - so it is cheap
3213/// enough to call on every candidate, every poll.
3214fn land_resume_state(task: &Task) -> LandResume {
3215    if task.sync_only.is_some() {
3216        return LandResume::NotLanding;
3217    }
3218    let Some(run_id) = task.execution_runs().last() else {
3219        return LandResume::NotLanding;
3220    };
3221    let Ok(state) = RunState::load(run_id) else {
3222        return LandResume::NotLanding;
3223    };
3224    if !state.parked {
3225        return LandResume::NotLanding;
3226    }
3227    if state.status == RunStatus::Landing
3228        && state.land_approval.as_ref().is_some_and(|binding| {
3229            ask::Questions::open()
3230                .get_for_effects(&binding.question)
3231                .is_ok_and(|q| {
3232                    q.run == state.id
3233                        && q.resolution()
3234                            .as_deref()
3235                            .is_some_and(crate::merge_decision::stops)
3236                })
3237        })
3238    {
3239        return LandResume::Ready;
3240    }
3241    if !implementers_match(task, &state) {
3242        return LandResume::NotLanding;
3243    }
3244    // Parked in `land` on the merge approval, or at `merge` on the owner's
3245    // word about a title/body the posting gate withheld. Told apart by the
3246    // run's own record, not by a status both can share.
3247    let node = if state.status == RunStatus::Landing {
3248        land::APPROVAL_NODE
3249    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3250        crate::github_text::ASK_NODE
3251    } else {
3252        return LandResume::NotLanding;
3253    };
3254    let store = ask::Questions::open();
3255    let waiting = store
3256        .list_for_effects()
3257        .into_iter()
3258        .filter(|q| &q.run == run_id && q.node == node)
3259        .max_by(|a, b| a.id.cmp(&b.id));
3260    let Some(mut q) = waiting else {
3261        return LandResume::Ready;
3262    };
3263    if !q.status.open() {
3264        // Repair spends agent resources and must obey concurrency and quota
3265        // waits; only a merge/hold decision may use the decision-only lane.
3266        if q.resolution().as_deref() == Some(land::REPAIR) {
3267            return if state.liveness(false) == Liveness::Live {
3268                LandResume::StillWaiting
3269            } else {
3270                LandResume::NotLanding
3271            };
3272        }
3273        return LandResume::Ready;
3274    }
3275    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3276    // nobody ever answered; land's approval bypasses that wait entirely (see
3277    // `land::approval_gate`), so the same deadline has to be enforced here
3278    // instead, or `graph.answer_timeout` silently stops meaning anything for
3279    // a land approval and a run can sit `StillWaiting` forever with nobody
3280    // told to look at it.
3281    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3282    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3283    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3284        q.abandon(format!(
3285            "no answer within {}s of asking",
3286            timeout.as_secs().max(1)
3287        ));
3288        // If this can't be persisted, do not treat the wait as settled on a
3289        // guess: fall through and try again next poll.
3290        if store.put(&mut q).is_ok() {
3291            return LandResume::Ready;
3292        }
3293    }
3294    LandResume::StillWaiting
3295}
3296
3297/// How often the loop rechecks for new work while something it already
3298/// started is still running, rather than sleeping out the whole
3299/// [`Opts::poll`] interval.
3300///
3301/// Short on purpose: this is what lets a land-merge approval that comes back
3302/// while another task is mid-competition be noticed and resumed within a
3303/// fraction of a second, not within the next multi-second poll.
3304const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3305
3306/// How often [`poll`] rechecks the shared build cache against its cap at a
3307/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3308/// waiting for the queue to run dry.
3309///
3310/// A queue that never empties means the `janitor` call at the bottom of this
3311/// loop's fully-idle branch can go unreached for as long as the backlog
3312/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3313/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3314/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3315/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3316/// backlog of short tasks does not pay for that walk on every poll.
3317const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3318
3319/// State of [`poll`]'s own interrupt-scheduling sequence - see
3320/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3321/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3322/// both kept free of `Task`'s non-identity fields on purpose: every decision
3323/// here turns only on task ids and which ones are in flight, so the "never
3324/// more than one run at once" and "exactly one resume" invariants can be
3325/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3326/// queue - which is exactly the coverage this feature's first two attempts
3327/// were missing.
3328///
3329/// Persisted after every transition, so scheduler replacement preserves the
3330/// interrupt's exclusive turn and the interrupted task's priority resume.
3331#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3332enum Interrupt {
3333    /// No interrupt sequence in progress. Ordinary dispatch applies.
3334    Idle,
3335    /// `interrupt_task` is runnable and exactly one other run is in flight;
3336    /// `parked` names that one task's id. Dispatch is withheld from
3337    /// everyone, including `interrupt_task` itself, until it has left
3338    /// flight - only then is `interrupt_task` let through.
3339    ///
3340    /// `parked` is a `Vec` rather than a bare id for symmetry with
3341    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3342    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3343    /// when exactly one run is in flight, so it is guaranteed to hold
3344    /// exactly one entry in practice - see that branch's own doc for why
3345    /// more than one is deliberately never attempted.
3346    Parking {
3347        parked: Vec<String>,
3348        interrupt_task: String,
3349    },
3350    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3351    /// withheld from everyone until it leaves flight - merged, failed, held,
3352    /// it makes no difference - at which point the sequence moves to
3353    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3354    /// going straight to `Idle` would hand `parked` back to ordinary
3355    /// priority-order dispatch, where a higher-priority task filed in the
3356    /// meantime could start ahead of it.
3357    Running {
3358        parked: Vec<String>,
3359        interrupt_task: String,
3360    },
3361    /// `interrupt_task` left flight; `parked` still names the one run this
3362    /// sequence owes a resume. Dispatch is withheld from everyone except
3363    /// that task - see [`interrupt_gate`] - so the resume this feature
3364    /// promises is never raced by, or run alongside, an unrelated candidate.
3365    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3366    /// own doc on abandonment - the moment it is no longer runnable at all.
3367    Resuming { parked: Vec<String> },
3368}
3369
3370/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3371/// and `runnable` are read-only snapshots of this tick's reality, and the
3372/// only side effect the caller still owes the world is asking whichever
3373/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3374/// site.
3375///
3376/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3377/// accepted rather than a narrower type because that is what [`poll`] already
3378/// has on hand from [`runnable`], and building a second, smaller list on
3379/// every tick just to satisfy this signature would cost more than it proves.
3380///
3381/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3382/// back to a task they are waiting on no longer being [`runnable`] - held,
3383/// blocked, deleted, or finished by some other means entirely, all of which
3384/// an operator can do to a task sitting in the queue with no claim on it at
3385/// all, at any moment, interrupt sequence or not. Without this check the
3386/// sequence would wait forever for a dispatch that can never come, and
3387/// `interrupt_gate` would withhold every other task in the queue right along
3388/// with it - a single `magi task hold` on the wrong id turning into a
3389/// daemon that never dispatches anything again.
3390fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3391    match state {
3392        Interrupt::Idle => {
3393            // Not just "something to interrupt": exactly one thing. More
3394            // than one run in flight only happens above the default
3395            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3396            // one resume, never run alongside anything else" only because
3397            // it is only ever seeded with exactly one id - see
3398            // `Interrupt::Resuming`'s own doc on why releasing more than one
3399            // parked id back to ordinary dispatch cannot be made safe
3400            // against that same setting's own extra concurrency slots.
3401            // Waiting here for the herd to settle to one is the
3402            // simplification this feature's own constraints ask for rather
3403            // than a second concurrency model to reconcile with the first.
3404            if in_flight.len() != 1 {
3405                return Interrupt::Idle;
3406            }
3407            match runnable.iter().find(|t| t.interrupt) {
3408                Some(t) => Interrupt::Parking {
3409                    parked: in_flight.to_vec(),
3410                    interrupt_task: t.id.clone(),
3411                },
3412                None => Interrupt::Idle,
3413            }
3414        }
3415        Interrupt::Parking {
3416            parked,
3417            interrupt_task,
3418        } => {
3419            if in_flight.iter().any(|id| parked.contains(id)) {
3420                // Still waiting for what was in flight to actually stop.
3421                Interrupt::Parking {
3422                    parked,
3423                    interrupt_task,
3424                }
3425            } else if in_flight.contains(&interrupt_task) {
3426                Interrupt::Running {
3427                    parked,
3428                    interrupt_task,
3429                }
3430            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3431                // The parked run(s) are gone, but the interrupt task has not
3432                // been dispatched yet on this tick - `interrupt_gate` is
3433                // what lets it through next.
3434                Interrupt::Parking {
3435                    parked,
3436                    interrupt_task,
3437                }
3438            } else {
3439                // The interrupt task itself is no longer runnable - see this
3440                // function's own doc on abandonment. The parked run(s) still
3441                // get their guaranteed resume; there is simply no interrupt
3442                // to run ahead of them any longer.
3443                Interrupt::Resuming { parked }
3444            }
3445        }
3446        Interrupt::Running {
3447            parked,
3448            interrupt_task,
3449        } => {
3450            if in_flight.contains(&interrupt_task) {
3451                Interrupt::Running {
3452                    parked,
3453                    interrupt_task,
3454                }
3455            } else {
3456                // The interrupt task's own run reached a terminal status,
3457                // whichever one - this is the *only* trigger that moves the
3458                // sequence on, driven straight off the same in-flight
3459                // bookkeeping `poll` already reaps every tick, not a second,
3460                // independent poll of anything.
3461                Interrupt::Resuming { parked }
3462            }
3463        }
3464        Interrupt::Resuming { parked } => {
3465            if in_flight.iter().any(|id| parked.contains(id)) {
3466                // One of the parked runs has been dispatched - the resume
3467                // this sequence owed is fulfilled. Whatever else is left in
3468                // `parked` (ordinarily nothing, at the default concurrency
3469                // of one) rejoins ordinary priority-order dispatch, same as
3470                // any other runnable task.
3471                Interrupt::Idle
3472            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3473                Interrupt::Resuming { parked }
3474            } else {
3475                // Abandonment (see this function's own doc): nothing left in
3476                // `parked` is even runnable any longer.
3477                Interrupt::Idle
3478            }
3479        }
3480    }
3481}
3482
3483/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3484/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3485/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3486/// indistinguishable from any other runnable task - exactly the "off does
3487/// nothing" this feature promises.
3488fn advance_interrupt_tick(
3489    enabled: bool,
3490    state: Interrupt,
3491    in_flight: &[String],
3492    runnable: &[Task],
3493) -> Interrupt {
3494    if !enabled {
3495        return Interrupt::Idle;
3496    }
3497    advance_interrupt(state, in_flight, runnable)
3498}
3499
3500/// Which of this tick's runnable candidates the interrupt sequence actually
3501/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3502/// each half is assertable on its own: this is the half that keeps a
3503/// competition and an interrupt from ever running at the same moment.
3504fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3505    match state {
3506        Interrupt::Idle => candidates,
3507        Interrupt::Parking {
3508            parked,
3509            interrupt_task,
3510        } => {
3511            if in_flight.iter().any(|id| parked.contains(id)) {
3512                Vec::new()
3513            } else {
3514                candidates
3515                    .into_iter()
3516                    .filter(|t| &t.id == interrupt_task)
3517                    .collect()
3518            }
3519        }
3520        Interrupt::Running { .. } => Vec::new(),
3521        // At most one: even if `parked` names more than one id (more than
3522        // one run was in flight when the sequence began, only possible
3523        // above the default `max_concurrent_runs = 1`), only the first match
3524        // is offered. Capping this to a single candidate - not merely to
3525        // `parked`'s own ids - is what makes "exactly one resume, never two
3526        // dispatched together" true regardless of how many ordinary slots
3527        // happen to be free this tick.
3528        Interrupt::Resuming { parked } => candidates
3529            .into_iter()
3530            .find(|t| parked.contains(&t.id))
3531            .into_iter()
3532            .collect(),
3533    }
3534}
3535
3536/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3537/// bundled into one parameter so `poll`'s own signature stays readable -
3538/// see [`drive`]'s call site for where these are actually read.
3539struct DispatchLimits {
3540    /// How many *ordinary* candidates run at once. See
3541    /// [`crate::config::Daemon::max_concurrent_runs`].
3542    max_concurrent: usize,
3543    /// See [`crate::config::Daemon::pause_for_interrupts`].
3544    pause_for_interrupts: bool,
3545    recovery_cfg: Option<Config>,
3546}
3547
3548/// Which semaphore, if any, dispatching a candidate should draw its permit
3549/// from.
3550///
3551/// Pure and separate from [`poll`]'s loop body for the same reason
3552/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3553/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3554/// exactly the policy this feature adds, and a policy only exercisable by
3555/// running the whole loop is a policy nobody checks.
3556#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3557enum PermitKind {
3558    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3559    /// Checked first - a task can be both a land resume and marked
3560    /// [`Task::urgent`], and the resume's own "must not queue behind
3561    /// anything" guarantee takes precedence.
3562    None,
3563    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3564    /// (never in addition to trying) the ordinary pool. This is what lets
3565    /// an urgent task dispatch while every ordinary slot is already checked
3566    /// out, and what stops a second urgent task from opening a third run: it
3567    /// waits on this same one-slot semaphore rather than falling through to
3568    /// the ordinary one.
3569    Urgent,
3570    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3571    /// above.
3572    #[default]
3573    Ordinary,
3574}
3575
3576/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3577/// own boolean, already computed by the caller from [`land_resume_state`].
3578fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3579    if priority {
3580        PermitKind::None
3581    } else if urgent {
3582        PermitKind::Urgent
3583    } else {
3584        PermitKind::Ordinary
3585    }
3586}
3587
3588fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3589    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3590        (0usize, 0usize),
3591        |(ordinary, urgent), request| match request.lane {
3592            PermitKind::Ordinary => (ordinary + 1, urgent),
3593            PermitKind::Urgent => (ordinary, urgent + 1),
3594            PermitKind::None => (ordinary, urgent),
3595        },
3596    );
3597    (
3598        limit.saturating_sub(ordinary),
3599        1usize.saturating_sub(urgent),
3600    )
3601}
3602
3603/// Why a runnable candidate was not dispatched. This does not alter policy.
3604#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3605enum SkipReason {
3606    ClaimUnavailable,
3607    RereadFailed,
3608    NoLongerRunnable,
3609    WaitingOnLanding,
3610    CoolingDown,
3611    OrdinaryCapacity,
3612    UrgentCapacity,
3613    InterruptGate,
3614}
3615
3616impl SkipReason {
3617    fn key(self) -> &'static str {
3618        match self {
3619            Self::ClaimUnavailable => "claim_unavailable",
3620            Self::RereadFailed => "reread_failed",
3621            Self::NoLongerRunnable => "no_longer_runnable",
3622            Self::WaitingOnLanding => "waiting_on_landing",
3623            Self::CoolingDown => "cooling_down",
3624            Self::OrdinaryCapacity => "ordinary_capacity",
3625            Self::UrgentCapacity => "urgent_capacity",
3626            Self::InterruptGate => "interrupt_gate",
3627        }
3628    }
3629
3630    fn describe(self) -> &'static str {
3631        match self {
3632            Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3633            Self::RereadFailed => "could not re-read it",
3634            Self::NoLongerRunnable => "no longer runnable",
3635            Self::WaitingOnLanding => "waiting on landing",
3636            Self::CoolingDown => "quota cooldown",
3637            Self::OrdinaryCapacity => "no free ordinary slot",
3638            Self::UrgentCapacity => "urgent slot busy",
3639            Self::InterruptGate => "withheld by the interrupt sequence",
3640        }
3641    }
3642}
3643
3644/// A reason count from a completed dispatch scan.
3645#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3646pub struct DispatchReasonCount {
3647    /// Stable string key, so readers can preserve future reasons.
3648    pub reason: String,
3649    /// Candidates skipped for this reason.
3650    pub count: usize,
3651}
3652
3653/// Observations from a completed scan, not a fresh queue estimate.
3654#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3655pub struct DispatchWait {
3656    /// Runnable candidates before the interrupt gate.
3657    pub runnable: usize,
3658    /// Counts in descending order, with stable reason order for ties.
3659    pub reasons: Vec<DispatchReasonCount>,
3660}
3661
3662type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3663
3664fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3665    if runnable == 0 {
3666        return None;
3667    }
3668    let mut counts = std::collections::BTreeMap::new();
3669    for (_, reason) in skips {
3670        *counts.entry(*reason).or_insert(0usize) += 1;
3671    }
3672    let mut counts: Vec<_> = counts.into_iter().collect();
3673    counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3674    Some(DispatchWait {
3675        runnable,
3676        reasons: counts
3677            .into_iter()
3678            .map(|(reason, count)| DispatchReasonCount {
3679                reason: reason.key().to_owned(),
3680                count,
3681            })
3682            .collect(),
3683    })
3684}
3685
3686fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3687    before
3688        .iter()
3689        .filter(|id| !after.iter().any(|task| &task.id == *id))
3690        .map(|id| (id.clone(), SkipReason::InterruptGate))
3691        .collect()
3692}
3693
3694fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3695    if *previous == current {
3696        return false;
3697    }
3698    *previous = current;
3699    true
3700}
3701
3702struct DispatchClaim {
3703    task: Task,
3704    claim: crate::queue::Claim,
3705    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3706}
3707
3708/// Claim and re-read before choosing a lane: a queue listing may predate an
3709/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3710fn claim_dispatch(
3711    queue: &Queue,
3712    candidate: &Task,
3713    cooling_down: bool,
3714    ordinary: &Arc<tokio::sync::Semaphore>,
3715    urgent: &Arc<tokio::sync::Semaphore>,
3716) -> std::result::Result<DispatchClaim, SkipReason> {
3717    let claim = queue
3718        .claim(&candidate.id)
3719        .map_err(|_| SkipReason::ClaimUnavailable)?;
3720    let task = match queue.get(&candidate.id) {
3721        Ok(t) if t.status.runnable() => t,
3722        Ok(_) => return Err(SkipReason::NoLongerRunnable),
3723        Err(e) => {
3724            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3725            return Err(SkipReason::RereadFailed);
3726        }
3727    };
3728    let resume = land_resume_state(&task);
3729    if resume == LandResume::StillWaiting {
3730        return Err(SkipReason::WaitingOnLanding);
3731    }
3732    let priority = resume == LandResume::Ready;
3733    if !priority && cooling_down {
3734        return Err(SkipReason::CoolingDown);
3735    }
3736    // Never borrow an ordinary slot when the single urgent slot is busy.
3737    // Keep scanning other candidates when either pool has no free slot.
3738    let permit = match permit_kind(priority, task.urgent) {
3739        PermitKind::None => None,
3740        PermitKind::Urgent => Some(
3741            Arc::clone(urgent)
3742                .try_acquire_owned()
3743                .map_err(|_| SkipReason::UrgentCapacity)?,
3744        ),
3745        PermitKind::Ordinary => Some(
3746            Arc::clone(ordinary)
3747                .try_acquire_owned()
3748                .map_err(|_| SkipReason::OrdinaryCapacity)?,
3749        ),
3750    };
3751    // Persist the dispatch order under the claim, before config discovery or
3752    // coordination waits can reorder concurrent starts.
3753    let stamp = Timestamp::now();
3754    let mut task = task;
3755    task.dispatched_at = Some(stamp);
3756    if let Err(e) = queue.modify(&task.id, |t| {
3757        t.dispatched_at = Some(stamp);
3758        true
3759    }) {
3760        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3761    }
3762    Ok(DispatchClaim {
3763        task,
3764        claim,
3765        permit,
3766    })
3767}
3768
3769/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3770/// teardown and cannot skip the teardown on an early return.
3771///
3772/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3773/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3774/// land approval that has since been answered is dispatched outside that
3775/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3776/// the whole point of parking there is that it must not queue behind
3777/// whatever else the loop happens to be running, even at the default of one.
3778/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3779/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3780/// these exemptions is still subject to the interrupt gate below, urgent
3781/// included: a land-resume or urgent candidate is exactly as much "something
3782/// else running" as an ordinary one from the interrupt sequence's point of
3783/// view, and letting either slip through while a run is being parked, or
3784/// while the interrupt task itself has the floor, is precisely the second
3785/// run 75dd's own "at most one run, ever, at once" guarantee must never
3786/// allow - see [`Interrupt`]'s own doc.
3787#[derive(Serialize, Deserialize)]
3788struct ServiceWorker {
3789    opts: Opts,
3790    queue: PathBuf,
3791    worktrees_root: PathBuf,
3792    operation: String,
3793}
3794
3795fn load_conductor(home: &Path) -> Result<Conductor> {
3796    match std::fs::read(home.join("conductor-state.json")) {
3797        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3798        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3799        Err(error) => Err(error.into()),
3800    }
3801}
3802
3803fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3804    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3805        .into_iter()
3806        .map(|c| c.task)
3807        .collect();
3808    let stalled = stalled_tasks(queue, home, Timestamp::now());
3809    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3810    let finished = finished_tasks(queue)
3811        .into_iter()
3812        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3813        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3814        .collect();
3815    let queued = queued_tasks(queue)
3816        .into_iter()
3817        .filter(|t| !live.contains(&t.id))
3818        .collect();
3819    (queued, stalled, finished)
3820}
3821
3822// Separate latest dispatch and worker receipts expose version handoff and skips
3823// without erasing the last completed scan or treating observations as authority.
3824fn retention_service_receipt(
3825    home: &Path,
3826    operation: &str,
3827    phase: &str,
3828    outcome: &str,
3829    detail: &str,
3830    cfg: Option<&Config>,
3831) {
3832    if !matches!(operation, "housekeeping" | "disk-pressure") {
3833        return;
3834    }
3835    let receipt = serde_json::json!({"checked_at": Timestamp::now(),
3836        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
3837        "operation": operation, "outcome": outcome, "detail": detail,
3838        "auto_fold": cfg.map(|c| c.disk.auto_fold),
3839        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
3840    if let Err(error) = crate::fold_evidence::atomic_write(
3841        &home.join(format!("source-eviction-{operation}-{phase}.json")),
3842        &serde_json::to_vec(&receipt).expect("service receipt"),
3843    ) {
3844        tracing::warn!("retention service receipt failed: {error:#}");
3845    }
3846}
3847
3848async fn start_service(
3849    home: &Path,
3850    opts: &Opts,
3851    queue: &Queue,
3852    worktrees_root: &Path,
3853    operation: &str,
3854    cfg: Option<&Config>,
3855    busy: bool,
3856) -> Result<()> {
3857    // Fetch policy is live configuration, unlike question recovery capacity.
3858    // Reload before both cadence and eligibility, including disabled -> enabled.
3859    let fetch_cfg = if operation == "fetch" {
3860        match prepare(&opts.repo, opts) {
3861            Ok(cfg) => Some(cfg),
3862            Err(error) => {
3863                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3864                return Ok(());
3865            }
3866        }
3867    } else {
3868        None
3869    };
3870    let cfg = fetch_cfg.as_ref().or(cfg);
3871    let ticks = home.join("service-ticks");
3872    std::fs::create_dir_all(&ticks)?;
3873    let receipt = ticks.join(format!("daemon-{operation}"));
3874    let last = std::fs::read(&receipt)
3875        .ok()
3876        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3877    let interval = match operation {
3878        "disk-pressure" => 30,
3879        "chat-goals" => 60,
3880        "cache" => CACHE_CHECK_INTERVAL_SECS,
3881        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3882        _ => opts.poll.as_secs().max(1),
3883    };
3884    let now = Timestamp::now();
3885    if !cache_check_due(last, now, interval) {
3886        retention_service_receipt(
3887            home,
3888            operation,
3889            "dispatch",
3890            "skipped",
3891            "cadence not due",
3892            cfg,
3893        );
3894        return Ok(());
3895    }
3896    let key = format!("service:daemon-{operation}");
3897    if crate::worker::active(home)?
3898        .iter()
3899        .any(|job| job.key == key)
3900    {
3901        retention_service_receipt(
3902            home,
3903            operation,
3904            "dispatch",
3905            "skipped",
3906            "service worker already active",
3907            cfg,
3908        );
3909        return Ok(());
3910    }
3911    let eligible = match operation {
3912        "conductor" => {
3913            let (queued, stalled, finished) = conductor_work(queue, home);
3914            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3915                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3916        }
3917        "maintenance" => {
3918            queue.list().iter().any(|task| {
3919                crate::triage::disk_wait_eligible(task)
3920                    && task
3921                        .disk_checked_at
3922                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
3923            }) || Questions::at(home.join("questions"))
3924                .list_for_effects()
3925                .iter()
3926                .any(|q| {
3927                    q.chosen_action().is_some_and(|action| action.maintenance())
3928                        && !home
3929                            .join("choice-actions")
3930                            .join(format!("{}.json", q.id))
3931                            .exists()
3932                })
3933        }
3934        "housekeeping" => !busy && runnable(queue).is_empty(),
3935        "cache" => {
3936            !busy
3937                && !runnable(queue).is_empty()
3938                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3939        }
3940        "disk-pressure" => busy,
3941        "fetch" => {
3942            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3943        }
3944        "chat-goals" => crate::talk::Talks::at(home.join("talks"))
3945            .list()
3946            .iter()
3947            .any(|talk| {
3948                talk.status.open()
3949                    && talk.pending.is_empty()
3950                    && talk.pending_attachments.is_empty()
3951                    && talk.goals.iter().any(|goal| goal.active())
3952            }),
3953        _ => false,
3954    };
3955    if !eligible {
3956        retention_service_receipt(
3957            home,
3958            operation,
3959            "dispatch",
3960            "skipped",
3961            if operation == "housekeeping" {
3962                "active work or runnable task queue"
3963            } else {
3964                "no active work; idle housekeeping owns scan"
3965            },
3966            cfg,
3967        );
3968        return Ok(());
3969    }
3970    retention_service_receipt(
3971        home,
3972        operation,
3973        "dispatch",
3974        "launching",
3975        "eligible and cadence due",
3976        cfg,
3977    );
3978    let request = ServiceWorker {
3979        opts: opts.absolute()?,
3980        queue: std::path::absolute(queue.root())?,
3981        worktrees_root: std::path::absolute(worktrees_root)?,
3982        operation: operation.to_owned(),
3983    };
3984    if let Err(error) =
3985        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3986    {
3987        retention_service_receipt(
3988            home,
3989            operation,
3990            "dispatch",
3991            "error",
3992            &format!("worker launch: {error:#}"),
3993            cfg,
3994        );
3995        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3996    }
3997    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3998    Ok(())
3999}
4000
4001/// Finite maintenance jobs survive scheduler replacement without duplicating
4002/// agent calls or cancelling an operation between its effect and receipt.
4003pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
4004    let request: ServiceWorker = serde_json::from_value(payload)?;
4005    let opts = &request.opts;
4006    let queue = Queue::at(request.queue);
4007    let questions = Questions::at(home.join("questions"));
4008    match request.operation.as_str() {
4009        "chat-goals" => {
4010            let talks = crate::talk::Talks::at(home.join("talks"));
4011            crate::chat_goal_runtime::sweep(&talks, false).await;
4012        }
4013        "maintenance" => {
4014            apply_maintenance_choices(&queue, &questions, home).await;
4015            triage::monitor_disk_waits(
4016                &queue,
4017                &questions,
4018                opts.config.as_deref(),
4019                Timestamp::now(),
4020            );
4021        }
4022        "conductor" => {
4023            let path = home.join("conductor-state.json");
4024            let mut conductor = load_conductor(home)?;
4025            let (queued, stalled, finished) = conductor_work(&queue, home);
4026            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4027                && conductor.worth_a_look(&queue, &stalled, &finished)
4028            {
4029                let cfg = prepare(&opts.repo, opts)?;
4030                conductor
4031                    .maybe_run(
4032                        &cfg,
4033                        &opts.repo,
4034                        &queue,
4035                        &questions,
4036                        home,
4037                        &queued,
4038                        &stalled,
4039                        &finished,
4040                        opts.max_attempts,
4041                    )
4042                    .await;
4043                let temporary = path.with_extension("json.tmp");
4044                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
4045                std::fs::rename(temporary, path)?;
4046            }
4047        }
4048        "fetch" => {
4049            let cfg = prepare(&opts.repo, opts)?;
4050            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
4051                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
4052                tracing::debug!("fetch origins: {outcome:?}");
4053            }
4054        }
4055        "cache" => {
4056            if task_jobs(home)?.is_empty() {
4057                let mut checked = None;
4058                maybe_prune_cache_between_runs(
4059                    &opts.repo,
4060                    opts,
4061                    home,
4062                    &Stop::new(),
4063                    &mut checked,
4064                    Timestamp::now(),
4065                )
4066                .await;
4067            }
4068        }
4069        "disk-pressure" => {
4070            if let Ok(cfg) = prepare(&opts.repo, opts) {
4071                retention_service_receipt(
4072                    home,
4073                    "disk-pressure",
4074                    "worker",
4075                    "running",
4076                    "retention sweep",
4077                    Some(&cfg),
4078                );
4079                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4080                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
4081                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
4082                }
4083                if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
4084                    tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
4085                }
4086                for current in current_work(home, Timestamp::now()) {
4087                    if let Ok(state) = RunState::load_under(&current.run, home)
4088                        && let Some(reason) = disk_gate(&state.repo, &state.config)
4089                    {
4090                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
4091                            job.key.strip_prefix("task:") == Some(current.task.as_str())
4092                        }) {
4093                            request_task_park(
4094                                home,
4095                                &job,
4096                                crate::run::ParkCause::Interrupt {
4097                                    reason: reason.clone(),
4098                                },
4099                            )?;
4100                        }
4101                        notices::raise_in(
4102                            home,
4103                            Notice::warn(
4104                                "disk:pressure",
4105                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
4106                            ),
4107                        );
4108                    }
4109                }
4110            } else {
4111                retention_service_receipt(
4112                    home,
4113                    "disk-pressure",
4114                    "worker",
4115                    "error",
4116                    "configuration could not be loaded",
4117                    None,
4118                );
4119            }
4120        }
4121        "housekeeping" => {
4122            if task_jobs(home)?.is_empty() {
4123                match prepare(&opts.repo, opts) {
4124                    Ok(cfg) => {
4125                        retention_service_receipt(
4126                            home,
4127                            "housekeeping",
4128                            "worker",
4129                            "running",
4130                            "retention sweep",
4131                            Some(&cfg),
4132                        );
4133                        crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4134                    }
4135                    Err(error) => retention_service_receipt(
4136                        home,
4137                        "housekeeping",
4138                        "worker",
4139                        "error",
4140                        &format!("configuration: {error:#}"),
4141                        None,
4142                    ),
4143                }
4144                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
4145                resweep_superseded_attempts(&queue, home);
4146                triage_held(&queue, home, opts).await;
4147            } else {
4148                retention_service_receipt(
4149                    home,
4150                    "housekeeping",
4151                    "worker",
4152                    "skipped",
4153                    "task worker became active",
4154                    None,
4155                );
4156            }
4157        }
4158        operation => bail!("unknown daemon service {operation}"),
4159    }
4160    Ok(())
4161}
4162
4163/// Only a different request under the same key is a dispatch handoff race.
4164/// Our own unacknowledged reservation is a startup failure, not competing work:
4165/// stop dispatch without fencing it, so an already detached child may still run.
4166fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
4167    let key = format!("task:{}", request.task);
4168    let payload = serde_json::to_value(request)?;
4169    if crate::worker::active(home)?
4170        .iter()
4171        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
4172    {
4173        tracing::warn!(
4174            "task {} acquired a competing worker reservation: {error:#}",
4175            crate::run::short_of(&request.task)
4176        );
4177        return Ok(());
4178    }
4179    tracing::error!("task worker startup stopped dispatch: {error:#}");
4180    notices::raise_in(
4181        home,
4182        Notice::error(
4183            "loop:worker-startup",
4184            // Startup diagnostics may contain private child-process details;
4185            // keep them in the local error/log rather than the chat or notifier.
4186            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),
4187        ).link(Link::Task { id: request.task.clone() }),
4188    );
4189    Err(error).with_context(|| {
4190        format!(
4191            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
4192            crate::run::short_of(&request.task)
4193        )
4194    })
4195}
4196
4197async fn poll(
4198    opts: &Opts,
4199    queue: &Queue,
4200    status: &Arc<Mutex<Status>>,
4201    home: &Path,
4202    worktrees_root: &Path,
4203    stop: &Stop,
4204    limits: DispatchLimits,
4205) -> Result<()> {
4206    let mut attempted = Vec::new();
4207    let mut settling_once_services = false;
4208    let interrupt_path = home.join("scheduler-interrupt.json");
4209    let mut interrupt = match std::fs::read(&interrupt_path) {
4210        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
4211        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
4212        Err(error) => return Err(error.into()),
4213    };
4214    let mut previous = std::collections::BTreeSet::<String>::new();
4215    let mut previous_skips = DispatchSkips::new();
4216    while !stop.stopped() {
4217        let jobs: Vec<_> = crate::worker::active(home)?
4218            .into_iter()
4219            .filter(|job| job.kind == "task")
4220            .collect();
4221        let requests: Vec<_> = jobs
4222            .iter()
4223            .map(|job| {
4224                serde_json::from_value::<TaskWorker>(job.payload.clone())
4225                    .with_context(|| format!("read live task worker {}", job.id))
4226            })
4227            .collect::<Result<_>>()?;
4228        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4229        let owned: std::collections::BTreeSet<_> = requests
4230            .iter()
4231            .filter(|r| !r.standalone)
4232            .map(|r| r.task.clone())
4233            .collect();
4234        let current: Vec<_> = requests
4235            .iter()
4236            .zip(&jobs)
4237            .filter(|(request, _)| !request.standalone)
4238            .map(|(request, job)| Current {
4239                worker: Some(job.id.clone()),
4240                task: request.task.clone(),
4241                run: queue
4242                    .get(&request.task)
4243                    .ok()
4244                    .and_then(|task| task.execution_runs().last().cloned())
4245                    .unwrap_or_default(),
4246            })
4247            .collect();
4248        {
4249            let mut snapshot = lock(status);
4250            snapshot.polls += 1;
4251            snapshot.completed += previous.difference(&owned).count();
4252            snapshot.current = current;
4253            snapshot.idle = owned.is_empty();
4254            snapshot.dispatch_wait = None;
4255        }
4256        previous = owned.clone();
4257        stop.busy.store(owned.len(), Ordering::SeqCst);
4258
4259        // Slots are reconstructed from durable reservations and OS-held worker
4260        // leases, not this scheduler's lifetime or mutable task urgency.
4261        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4262        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4263        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4264        let mut permits = Vec::new();
4265        sweep_stale_claims(queue, STALE_CLAIM);
4266        reclaim_orphaned_running(queue, opts.max_attempts, &live);
4267        reclaim_abandoned_runs(home, Timestamp::now());
4268        let questions = Questions::at(home.join("questions"));
4269
4270        // Deterministic: no model, run before the conductor sees anything so
4271        // its input reflects the queue's current, already-resolved state.
4272        crate::task_chat::sweep(
4273            queue,
4274            &crate::talk::Talks::at(home.join("talks")),
4275            &questions,
4276            home,
4277        );
4278        if let Err(error) = crate::task_inquiry::Outbox::at(home)
4279            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4280        {
4281            tracing::warn!("task inquiry delivery remains pending: {error:#}");
4282        }
4283        repair_choice_offers(&questions);
4284        resolve_blockers(queue, &questions);
4285        apply_task_choice_actions(queue, &questions, home);
4286        triage::apply_answers(queue, &questions);
4287        reconcile_task_questions(queue, &questions);
4288        let talks = crate::talk::Talks::at(home.join("talks"));
4289        crate::chat_notify::sweep(queue, &talks, home);
4290        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4291        crate::chat_watch::sweep(home, &talks);
4292        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4293            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4294        }
4295        let mut turns = tokio::task::JoinSet::new();
4296        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4297        // start_turns dispatches detached turns; no paid work lives in this set.
4298        while turns.join_next().await.is_some() {}
4299
4300        crate::consult::start_services(
4301            home,
4302            &opts.repo,
4303            limits.recovery_cfg.as_ref(),
4304            opts.config.as_deref(),
4305        )
4306        .await?;
4307        for operation in [
4308            "conductor",
4309            "maintenance",
4310            "housekeeping",
4311            "disk-pressure",
4312            "cache",
4313            "fetch",
4314            "chat-goals",
4315        ] {
4316            // Once an idle --once drain starts settling services, subsequent
4317            // scans only consume their effects. An expired cadence receipt
4318            // must not start another service and keep the drain alive.
4319            if settling_once_services {
4320                break;
4321            }
4322            if operation == "chat-goals" && stop.parking() {
4323                continue;
4324            }
4325            start_service(
4326                home,
4327                opts,
4328                queue,
4329                worktrees_root,
4330                operation,
4331                limits.recovery_cfg.as_ref(),
4332                !live.is_empty(),
4333            )
4334            .await?;
4335        }
4336        let latest = crate::worker::active(home)?;
4337        if latest.iter().any(|job| job.key == "service:daemon-cache")
4338            || latest
4339                .iter()
4340                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4341        {
4342            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4343            continue;
4344        }
4345        let candidates: Vec<Task> = runnable(queue)
4346            .into_iter()
4347            .filter(|task| !live.contains(&task.id))
4348            .filter(|task| !opts.once || !attempted.contains(&task.id))
4349            .collect();
4350        let in_flight: Vec<_> = owned.iter().cloned().collect();
4351        let prior_interrupt = std::mem::discriminant(&interrupt);
4352        interrupt = advance_interrupt_tick(
4353            limits.pause_for_interrupts,
4354            interrupt,
4355            &in_flight,
4356            &candidates,
4357        );
4358        // Same-variant transitions preserve their identities. Only an actual
4359        // transition needs a durable write, atomically before sending controls.
4360        if prior_interrupt != std::mem::discriminant(&interrupt) {
4361            let temporary = interrupt_path.with_extension("json.tmp");
4362            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4363            std::fs::rename(temporary, &interrupt_path)?;
4364        }
4365        if let Interrupt::Parking {
4366            parked,
4367            interrupt_task,
4368        } = &interrupt
4369        {
4370            for job in jobs.iter().filter(|job| {
4371                parked
4372                    .iter()
4373                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4374            }) {
4375                if crate::worker::control(home, &job.key)?.is_none() {
4376                    request_task_park(
4377                        home,
4378                        job,
4379                        crate::run::ParkCause::Interrupt {
4380                            reason: format!(
4381                                "task {} asked to run first",
4382                                crate::run::short_of(interrupt_task)
4383                            ),
4384                        },
4385                    )?;
4386                }
4387            }
4388        }
4389        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
4390        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4391        let mut skips = interrupt_skips(&candidate_ids, &candidates);
4392        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4393        let mut started = false;
4394        let mut resync = false;
4395        for candidate in candidates {
4396            if stop.stopped() {
4397                break;
4398            }
4399            let DispatchClaim {
4400                task,
4401                claim,
4402                permit,
4403            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
4404                Ok(claim) => claim,
4405                Err(reason) => {
4406                    skips.insert((candidate.id, reason));
4407                    continue;
4408                }
4409            };
4410            if crate::worker::active(home)?
4411                .iter()
4412                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4413            {
4414                drop(claim);
4415                resync = true;
4416                break;
4417            }
4418            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4419            let request = TaskWorker {
4420                opts: opts.absolute()?,
4421                queue: std::path::absolute(queue.root())?,
4422                task: task.id.clone(),
4423                lane,
4424                standalone: false,
4425            };
4426            // Keep the claim until spawn acknowledges the worker's durable
4427            // reservation. The worker then claims and re-reads before attempt.
4428            if let Err(error) = crate::worker::spawn(
4429                home,
4430                "task",
4431                &format!("task:{}", task.id),
4432                serde_json::to_value(&request)?,
4433            )
4434            .await
4435            {
4436                task_worker_spawn_error(home, &request, error)?;
4437                drop(claim);
4438                resync = true;
4439                break;
4440            }
4441            drop(claim);
4442            permits.extend(permit);
4443            attempted.push(task.id);
4444            started = true;
4445        }
4446        if !resync && !stop.stopped() {
4447            if !started {
4448                lock(status).dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
4449            }
4450            if changed_dispatch_skips(&mut previous_skips, skips) {
4451                if previous_skips.is_empty() {
4452                    tracing::info!("dispatch skips cleared");
4453                }
4454                for (task, reason) in &previous_skips {
4455                    tracing::info!(
4456                        task,
4457                        reason = reason.key(),
4458                        "task {} skipped: {}",
4459                        crate::run::short_of(task),
4460                        reason.describe()
4461                    );
4462                }
4463            }
4464        }
4465        if started || resync {
4466            continue;
4467        }
4468        if owned.is_empty() && opts.once {
4469            settling_once_services = true;
4470            // These finite services can own queue claims or publish answers.
4471            // A skipped claim is not an idle queue until they have finished;
4472            // scan again afterwards so their changes are actually scheduled.
4473            if crate::worker::active(home)?.iter().any(|job| {
4474                job.kind == "daemon-service"
4475                    && matches!(
4476                        job.key.as_str(),
4477                        "service:daemon-housekeeping"
4478                            | "service:daemon-conductor"
4479                            | "service:daemon-maintenance"
4480                    )
4481            }) {
4482                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4483                continue;
4484            }
4485            break;
4486        }
4487        stop.idle(if live.is_empty() {
4488            opts.poll
4489        } else {
4490            RECHECK_WHILE_BUSY.min(opts.poll)
4491        })
4492        .await;
4493    }
4494    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4495    // every queue claim and Runner driver lease through outcome settlement.
4496    stop.busy.store(0, Ordering::SeqCst);
4497    lock(status).dispatch_wait = None;
4498    Ok(())
4499}
4500
4501/// A maintenance pass may briefly own the same record while a worker starts.
4502/// Wait without blocking the executor or charging an agent attempt, then read
4503/// ownership again under the acquired lock. Other I/O failures still fail closed.
4504async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4505    let busy = |error: &anyhow::Error| {
4506        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4507            error.kind() == std::io::ErrorKind::WouldBlock
4508                || cfg!(windows) && error.raw_os_error() == Some(33)
4509        })
4510    };
4511    match crate::pr_head::owner_lock(home, id) {
4512        Ok(lock) => return Ok(lock),
4513        Err(error) if busy(&error) => {}
4514        Err(error) => return Err(error),
4515    }
4516    let wait = RunState::load_under(id, home)?
4517        .config
4518        .graph
4519        .timeout_resource_wait;
4520    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4521}
4522
4523/// Historical successors do not revoke a still-resumable public owner. Scan
4524/// under the same lock as publication/driver claims, and fail closed on unknown
4525/// history before spending another attempt.
4526async fn public_resume_owner(
4527    home: &Path,
4528    runs: &[String],
4529    repo: &Path,
4530) -> Result<Option<RunState>> {
4531    let mut owner = None;
4532    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4533        let _lock = resume_owner_lock(home, id).await?;
4534        let state = RunState::load_under(id, home)?;
4535        if state.released()
4536            || state.retired_to.is_some()
4537            || state.pr_taken_over_by.is_some()
4538            || !crate::handover::landing_checkpoint(&state)
4539        {
4540            continue;
4541        }
4542        anyhow::ensure!(
4543            crate::git::toplevel(&state.repo).await?.canonicalize()?
4544                == crate::git::toplevel(repo).await?.canonicalize()?,
4545            "public owner repository differs; inspect run lineage"
4546        );
4547        anyhow::ensure!(
4548            owner.is_none(),
4549            "multiple retained public owners; inspect run lineage"
4550        );
4551        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4552            anyhow::bail!(reason.diagnostic(&state));
4553        }
4554        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4555        anyhow::ensure!(
4556            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4557            "public owner's driver is live or unknown; wait before retrying"
4558        );
4559        owner = Some(state);
4560    }
4561    Ok(owner)
4562}
4563
4564/// Run one claimed task to a terminal status and record the outcome.
4565///
4566/// Every transition is flushed to the queue as it happens, so the state on disk
4567/// is what actually occurred rather than what this process still intends to
4568/// write.
4569async fn attempt(
4570    opts: &Opts,
4571    queue: &Queue,
4572    status: &Arc<Mutex<Status>>,
4573    stop: &Stop,
4574    interrupt_pause: crate::graph::Pause,
4575    task: &mut Task,
4576) -> Vec<QuotaLoss> {
4577    if let Some(request) = task.sync_only.clone() {
4578        Box::pin(attempt_sync_only(
4579            queue,
4580            status,
4581            stop,
4582            interrupt_pause,
4583            task,
4584            request,
4585        ))
4586        .await;
4587        return Vec::new();
4588    }
4589    let repo = repo_for(task, &opts.repo);
4590    tracing::info!(
4591        "task {} — {} (repo {})",
4592        task.short(),
4593        task.title,
4594        repo.display()
4595    );
4596
4597    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4598        Ok(owner) => owner,
4599        Err(e) => {
4600            task.hold_machine(Some(format!(
4601                "Cannot verify existing public owner: {e:#}; no attempt started."
4602            )));
4603            record(queue, task);
4604            return Vec::new();
4605        }
4606    };
4607    let resume_runs = public_owner
4608        .as_ref()
4609        .map(|s| vec![s.id.clone()])
4610        .unwrap_or_else(|| task.execution_runs().to_vec());
4611
4612    // A stop spends no agent resources and uses the saved landing owner.
4613    // Current roster edits, missing attachments or a failed config fetch must
4614    // never turn it into a new implementation, or prevent a PR from closing.
4615    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4616        && previous
4617            .merge_decision
4618            .as_ref()
4619            .is_some_and(|decision| !decision.closed)
4620        && previous.status != RunStatus::Landing
4621        && !crate::merge_decision::resumable_hold(&previous)
4622    {
4623        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)));
4624        record(queue, task);
4625        return Vec::new();
4626    }
4627    let stop_owner = resume_runs
4628        .last()
4629        .and_then(|id| RunState::load(id).ok())
4630        .filter(|state| {
4631            crate::merge_decision::resumable_hold(state)
4632                || state.status == RunStatus::Landing
4633                    && state.land_approval.as_ref().is_some_and(|binding| {
4634                        Questions::open()
4635                            .get_for_effects(&binding.question)
4636                            .is_ok_and(|q| {
4637                                q.run == state.id
4638                                    && q.resolution()
4639                                        .as_deref()
4640                                        .is_some_and(crate::merge_decision::stops)
4641                            })
4642                    })
4643        });
4644    if let Some(owner) = stop_owner {
4645        let mut runner = match Runner::resume(&owner.id) {
4646            Ok(runner) => runner,
4647            Err(e) => {
4648                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4649                record(queue, task);
4650                return Vec::new();
4651            }
4652        };
4653        runner.on_pause(stop.pause());
4654        runner.watch_interrupt(interrupt_pause);
4655        let quota_before = runner.state.quota.clone();
4656        let before_start = task.clone();
4657        task.start(owner.id.clone());
4658        if let Err(error) = queue.put(task) {
4659            *task = before_start;
4660            let error = runner.fail_startup("task-start", error);
4661            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4662                task.record_startup_failure(failure.clone());
4663            }
4664            task.hold_manual(Some(format!(
4665                "Could not persist task start; no agents dispatched: {error:#}"
4666            )));
4667            record(queue, task);
4668            return Vec::new();
4669        }
4670        lock(status).current.push(Current {
4671            worker: None,
4672            task: task.id.clone(),
4673            run: owner.id,
4674        });
4675        runner.state.carry_dispatched_resumes(task);
4676        runner.state.next_pass_task_entry = true;
4677        let result = runner.execute().await;
4678        return finish_attempt(
4679            opts.max_attempts,
4680            queue,
4681            task,
4682            &runner.state,
4683            &quota_before,
4684            result,
4685        );
4686    }
4687
4688    if let Some(owner) = &public_owner
4689        && (task.fresh_start || !may_resume_run(owner, task))
4690    {
4691        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)));
4692        record(queue, task);
4693        return Vec::new();
4694    }
4695
4696    if let Some(state) = task
4697        .execution_runs()
4698        .last()
4699        .and_then(|id| RunState::load(id).ok())
4700        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4701    {
4702        task.hold_machine(Some(reason));
4703        record(queue, task);
4704        return Vec::new();
4705    }
4706
4707    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4708        && !task.fresh_start
4709        && task.pr_recovery.is_none()
4710    {
4711        // Authorization still takes the owner lock and execution lease and
4712        // rechecks liveness, retained HEAD and ownership before saving.
4713        let authorized = if crate::repair_budget::conflict_pending(task, &held) {
4714            true
4715        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4716            let home = queue.root().parent().expect("queue has a home");
4717            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4718                Ok(()) => true,
4719                Err(error) => {
4720                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4721                    false
4722                }
4723            }
4724        } else {
4725            false
4726        };
4727        if !authorized {
4728            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())));
4729            // Retain the existing stop identity when an old release reached the queue.
4730            task.base_sync_notice(&held);
4731            task.resume_override = None;
4732            record(queue, task);
4733            return Vec::new();
4734        }
4735    }
4736    let unfinished = (!task.fresh_start)
4737        .then(|| unfinished_run(&resume_runs, task.short()))
4738        .flatten()
4739        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4740    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4741    if task.repair_grants.last().is_some_and(|receipt| {
4742        task.execution_runs().last() == Some(&receipt.request.run)
4743            && task.operator_decided_at == receipt.decision
4744            && previous
4745                .as_ref()
4746                .is_none_or(|run| run.id != receipt.request.run)
4747    }) {
4748        task.hold_unrequested_retry(Some(
4749            "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(),
4750        ));
4751        record(queue, task);
4752        return Vec::new();
4753    }
4754    if let Some(id) = &task.disk_resume_run
4755        && unfinished.as_ref() != Some(id)
4756    {
4757        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()));
4758        record(queue, task);
4759        return Vec::new();
4760    }
4761
4762    if !task.fresh_start
4763        && task.pr_recovery.is_none()
4764        && task.review_branch.is_none()
4765        && task.resume_override.is_none()
4766        && previous
4767            .as_ref()
4768            .is_some_and(|run| run.retired_to.is_some())
4769        && unfinished.is_none()
4770    {
4771        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()));
4772        record(queue, task);
4773        return Vec::new();
4774    }
4775
4776    let saved_recovery = previous.as_ref().filter(|run| {
4777        task.replacement.is_none()
4778            && task.pr_recovery.as_ref().is_some_and(|selected| {
4779                selected
4780                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4781                    .is_ok()
4782                    && selected_starter(selected, Some(run), unfinished.as_deref())
4783                        == Starter::Resume(run.id.clone())
4784            })
4785    });
4786
4787    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4788    // failure here is the network's or the operator's, not the task's: hold
4789    // without spending an attempt, never fall back to a possibly stale copy.
4790    let explicit = match &task.overrides {
4791        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4792        Some(_) => opts.config.as_deref(),
4793        None => opts.config.as_deref(),
4794    };
4795    let (mut config, layers) = if let Some(run) = saved_recovery {
4796        // A matching resume owns its resolved configuration and evidence;
4797        // current layers and inherited overrides only configure new work.
4798        let mut saved = run.clone();
4799        if let Err(e) = saved.configure_recovery_resume() {
4800            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4801            record(queue, task);
4802            return Vec::new();
4803        }
4804        (saved.config, Vec::new())
4805    } else {
4806        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4807            Ok(loaded) => loaded,
4808            Err(e) => {
4809                let reason = format!("[config] {e:#}");
4810                record_config_failure(task, &e);
4811                task.last_error = Some(reason.clone());
4812                task.hold_machine(Some(reason));
4813                record(queue, task);
4814                return Vec::new();
4815            }
4816        };
4817        if let Err(e) = apply_options(&mut config, opts, task) {
4818            task.hold_manual(Some(format!(
4819                "[config] {e:#}; correct the merge override before releasing the task"
4820            )));
4821            record(queue, task);
4822            return Vec::new();
4823        }
4824        if let Some(selected) = &task.pr_recovery
4825            && let Err(e) = selected.configure(&mut config)
4826        {
4827            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4828            record(queue, task);
4829            return Vec::new();
4830        }
4831        (config, layers)
4832    };
4833    let config_evidence = crate::pr_recovery::ConfigEvidence {
4834        layers,
4835        overrides: task.overrides.clone(),
4836        daemon_merge: task
4837            .overrides
4838            .as_ref()
4839            .is_none_or(|o| o.inherit_daemon_options)
4840            .then(|| opts.merge.clone())
4841            .flatten(),
4842    };
4843    apply_task_implementers(&mut config, task);
4844    if let Some(replacement) = &task.replacement {
4845        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4846            old.liveness(false) == Liveness::Dead
4847                && old.merge_decision.as_ref().is_some_and(|d| {
4848                    d.closed
4849                        && d.question == replacement.question
4850                        && d.replacement_run.as_ref().is_none_or(|run| {
4851                            task.execution_runs().last() == Some(run)
4852                                && RunState::load(run).is_ok_and(|current| {
4853                                    current.replaces.as_ref().is_some_and(|pin| {
4854                                        pin.question == replacement.question
4855                                            && pin.agent == replacement.agent
4856                                    })
4857                                })
4858                        })
4859                })
4860        });
4861        if !safe {
4862            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()));
4863            record(queue, task);
4864            return Vec::new();
4865        }
4866        match config.agent(&replacement.agent) {
4867            Ok(agent) if crate::agent::installed(agent) => {}
4868            _ => {
4869                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)));
4870                record(queue, task);
4871                return Vec::new();
4872            }
4873        }
4874        config.graph.implementers = 1;
4875        config.graph.land_approval = true;
4876        config.merge.mode = MergeMode::Pr;
4877        config.graph.selected_implementer = Some(replacement.agent.clone());
4878    }
4879    let p = phrases(&config.graph.language);
4880    let start_failed = p.could_not_start;
4881    // Resolve once for both admission and settlement. The inputs are the
4882    // task's explicit sources (never prose), plus an explicit review source's
4883    // current head; review-only runs may rebase later, and neither fact can
4884    // refund a failed automatic generation.
4885    if let Ok(base) =
4886        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4887            .await
4888        && let Ok(head) =
4889            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4890    {
4891        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4892        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4893            let source = crate::git::rev_parse(&repo, branch)
4894                .await
4895                .unwrap_or_default();
4896            inputs.push_str(&format!(";review:{branch}:{source}"));
4897        }
4898        if let Some(reason) = task
4899            .recovery_exhausted(
4900                &head,
4901                &inputs,
4902                task.attempt_limit
4903                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4904            )
4905            .filter(|_| {
4906                !task.repair_grants.last().is_some_and(|receipt| {
4907                    RunState::load(&receipt.request.run)
4908                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4909                })
4910            })
4911        {
4912            task.hold_recovery_budget(
4913                reason,
4914                crate::queue::RecoveryAdmission { base: head, inputs },
4915            );
4916            record(queue, task);
4917            return Vec::new();
4918        }
4919        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4920    }
4921
4922    // A resumable run of this task is carried on, never re-competed. The
4923    // candidates are built and paid for, and a fresh competition races a
4924    // second implementation against them.
4925    //
4926    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4927    // started 3cbf on the same task a moment later, duplicating two and a
4928    // half hours of agent work. Then b25f stalled on a judge that timed out
4929    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4930    // was to blame for - and 4043 started **one second** later, buying three
4931    // fresh implementations to reach the same panel. `RunStatus::resumable`
4932    // rather than `!done()` is what catches the second case: a stall is
4933    // terminal, and its cheap recovery re-asks only the absent seats.
4934    //
4935    // A load failure is warned about rather than silently read as "not
4936    // resumable": the alternative is exactly what let a schema mismatch on
4937    // run `eba2` fall through to a full re-competition with nobody told why.
4938    // `crate::conduct` is what actually offers a better answer than
4939    // `Runner::start` here (see `Recovery::Review`), once this task's next
4940    // failure shows it up as `held`/`failed` with the run state unreadable.
4941    // Keep a retained review selection intact until disk admission succeeds.
4942    let consume_review = !previous
4943        .as_ref()
4944        .is_some_and(|state| crate::repair_budget::pending(task, state));
4945    let review_branch = consume_review
4946        .then(|| review_branch_for(task, previous.as_ref()))
4947        .flatten();
4948    let branch_exists = match review_branch {
4949        Some(branch) => crate::git::branch_exists(&repo, branch)
4950            .await
4951            .unwrap_or(false),
4952        None => false,
4953    };
4954    // An explicit `magi review <branch>` is reviewed whatever happens to the
4955    // branch unless an explicit implementer change requires fresh work. An
4956    // unfinished run of the same task still wins, so a retry resumes.
4957    let proposed = review_retry_starter(
4958        task,
4959        previous.as_ref(),
4960        review_branch,
4961        branch_exists,
4962        unfinished.as_deref(),
4963    );
4964    let retry_selected = task.replacement.is_some()
4965        && task.resumption.is_some()
4966        && !task.fresh_start
4967        && previous.as_ref().is_some_and(|run| {
4968            run.replaces.is_some()
4969                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4970                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4971        });
4972    let stop_pin = task
4973        .resume_override
4974        .as_ref()
4975        .filter(|pin| {
4976            Questions::open()
4977                .get_for_effects(&pin.question_id)
4978                .is_ok_and(|q| {
4979                    q.node == land::APPROVAL_NODE
4980                        && q.resolution()
4981                            .as_deref()
4982                            .is_some_and(crate::merge_decision::stops)
4983                })
4984        })
4985        .and_then(|pin| pin.pinned_run.clone());
4986    let granted_run = task.repair_grants.last().and_then(|receipt| {
4987        let state = RunState::load(&receipt.request.run).ok()?;
4988        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
4989    });
4990    let starter = if let Some(run) = granted_run {
4991        Starter::Resume(run)
4992    } else if let Some(owner) = &public_owner {
4993        Starter::Resume(owner.id.clone())
4994    } else if let Some(run) = stop_pin {
4995        // Stop actions resume their exact owner even after seat-count edits;
4996        // they must never fall through to implementation or a takeover.
4997        Starter::Resume(run)
4998    } else if retry_selected {
4999        Starter::Resume(previous.as_ref().unwrap().id.clone())
5000    } else if let Some(selected) = &task.pr_recovery {
5001        if selected
5002            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5003            .is_ok()
5004        {
5005            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
5006        } else {
5007            Starter::Review(selected.branch.clone())
5008        }
5009    } else {
5010        starter_with_implementers(task, previous.as_ref(), proposed)
5011    };
5012    // A retained execution still writes to its saved output volume. A newer
5013    // repository policy only selects the volume for a fresh run.
5014    let disk_reason = match &starter {
5015        Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
5016            || {
5017                RunState::load(id)
5018                    .ok()
5019                    .and_then(|run| disk_gate(&run.repo, &run.config))
5020            },
5021            |run| disk_gate(&run.repo, &run.config),
5022        ),
5023        _ => disk_gate(&repo, &config),
5024    };
5025    if let Some(reason) = disk_reason {
5026        task.notice_cause("disk-space", None, None);
5027        task.last_error = Some(reason.clone());
5028        let disk_checked_at = task.disk_checked_at;
5029        task.hold_machine(Some(reason.clone()));
5030        if matches!(starter, Starter::Resume(_)) {
5031            task.mark_disk_capacity();
5032        } else {
5033            task.mark_startup_disk_capacity();
5034        }
5035        task.disk_checked_at = disk_checked_at;
5036        record(queue, task);
5037        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
5038        notices::raise(
5039            Notice::warn(
5040                &format!("disk:{}", repo.display()),
5041                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
5042            )
5043            .link(Link::Task {
5044                id: task.id.clone(),
5045            }),
5046        );
5047        return Vec::new();
5048    }
5049    let review_branch = if consume_review {
5050        let valid = review_branch.is_some();
5051        task.review_instruction = None;
5052        task.review_branch.take().filter(|_| valid)
5053    } else {
5054        None
5055    };
5056    // An explicit resume pin must never degrade into a new competition or
5057    // takeover, including when its run stops being eligible after the answer.
5058    if let Some(pin) = &task.resume_override
5059        && let Some(run) = &pin.pinned_run
5060        && starter != Starter::Resume(run.clone())
5061    {
5062        let run = run.clone();
5063        task.notice_cause("resume-owner", Some(&run), None);
5064        task.hold_machine(Some(format!(
5065            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
5066            task.id
5067        )));
5068        record(queue, task);
5069        return Vec::new();
5070    }
5071    // Automatic disk recovery resumes its retained run or stops: a changed
5072    // seat count or review branch must not turn it into a new competition.
5073    // No attempt is spent here.
5074    if let Some(run) = &task.disk_resume_run
5075        && starter != Starter::Resume(run.clone())
5076    {
5077        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()));
5078        record(queue, task);
5079        return Vec::new();
5080    }
5081    if task.replacement.is_some()
5082        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
5083        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
5084    {
5085        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()));
5086        record(queue, task);
5087        return Vec::new();
5088    }
5089    if let Some(reason) = retained_attempt_hold(
5090        task,
5091        &starter,
5092        config.disk.retained_attempt_limit,
5093        RunState::load,
5094    ) {
5095        // The review choice was consumed above. Preserve it across this hold
5096        // so a later release cannot silently become a fresh implementation.
5097        if let Starter::Review(branch) = &starter {
5098            task.review_branch = Some(branch.clone());
5099        }
5100        task.hold_unrequested_retry(Some(reason));
5101        record(queue, task);
5102        return Vec::new();
5103    }
5104    // Absolute paths of the files the task was filed with, re-read from the
5105    // task now so a file attached while it was held reaches a resumed run
5106    // too. A stored name whose file has gone is an error before any agent is
5107    // paid for, never a silent omission the implementer cannot notice.
5108    let attachments = match task_attachments(queue, task) {
5109        Ok(a) => a,
5110        Err(e) => {
5111            task.attempts += 1;
5112            task.fail_startup_target(
5113                "startup-attachments",
5114                e.name.clone(),
5115                format!("{start_failed}{e:#}"),
5116                opts.max_attempts,
5117            );
5118            record(queue, task);
5119            return Vec::new();
5120        }
5121    };
5122    let startup_pause = stop.pause();
5123    let startup_interrupt = interrupt_pause.clone();
5124    let wait = crate::repo_lock::WaitPolicy::new(
5125        Duration::from_secs(config.graph.timeout_resource_wait),
5126        move || startup_pause.parked() || startup_interrupt.parked(),
5127    );
5128    // Startup includes review takeover and recovery. Do not embed its large
5129    // future in both the wait scope and the surrounding attempt stack frame.
5130    let started = wait.scope(Box::pin(async { match &starter {
5131        Starter::Review(_) if task.pr_recovery.is_some() => {
5132            let selected = task.pr_recovery.clone().expect("selected recovery");
5133            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
5134                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
5135                    .await
5136                    .map(|mut r| {
5137                        r.state.attachments = attachments.clone();
5138                        r
5139                    }),
5140                Err(e) => Err(e),
5141            }
5142        }
5143        Starter::Review(branch) => {
5144            tracing::info!(
5145                "task {} reopens `{branch}` as a review-only pass",
5146                task.short()
5147            );
5148            // Every earlier attempt is superseded by the one being minted
5149            // now, so a branch one of them still holds may be taken over.
5150            let takeover = crate::handover::Takeover {
5151                earlier: task.earlier_attempts().to_vec(),
5152                home: crate::run::home(),
5153                choice: take_divergence_answer(branch, &config.merge.remote, task),
5154                task_instruction: Some(instruction_for(task)),
5155            };
5156            Runner::review_taking_over(
5157                &repo,
5158                branch,
5159                config,
5160                Some(takeover),
5161                crate::run::Origin::queue(&task.id),
5162            )
5163            .await
5164        }
5165        Starter::Resume(id) => {
5166            tracing::info!("resuming run {id} rather than competing again");
5167            Runner::resume(id).and_then(|mut r| {
5168                if retry_selected {
5169                    // The explicit queue release retries this same pinned
5170                    // implementation, preserving the attempt and worktrees.
5171                    for candidate in &mut r.state.candidates {
5172                        candidate.failed = None;
5173                        candidate.empty = false;
5174                        candidate.commits = 0;
5175                    }
5176                    r.state.status = RunStatus::Implementing;
5177                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
5178                }
5179                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
5180                    r.state.sources = task.sources.clone();
5181                }
5182                if r.state.prep_failure.is_some() {
5183                    let approval = task
5184                        .resumption
5185                        .as_ref()
5186                        .context("preparation retry requires an explicit task release")?;
5187                    r.retry_preparation(approval.at)?;
5188                }
5189                if let Some(instruction) =
5190                    prepare_instruction(&starter, Some(&r.state.instruction), task)
5191                {
5192                    r.state.instruction = instruction;
5193                }
5194                r.state.attachments = attachments.clone();
5195                if task.replacement.is_some() {
5196                    r.state.config.merge.mode = MergeMode::Pr;
5197                    r.state.config.graph.land_approval = true;
5198                }
5199                // Replacements publish a new PR and ask again. Selected PR
5200                // recoveries keep their saved disposition; ordinary runs can
5201                // retain the task's merge override.
5202                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
5203                    .overrides
5204                    .as_ref()
5205                    .and_then(|o| o.merge.as_deref())
5206                    .and_then(|m| merge_mode(m).ok())
5207                {
5208                    r.state.config.merge.mode = mode;
5209                }
5210                Ok(r)
5211            })
5212        }
5213        Starter::Start => {
5214            if let Some(branch) = &review_branch {
5215                tracing::warn!(
5216                    "conductor chose review for task {} but branch `{branch}` no longer \
5217                     exists; requeuing as a fresh competition instead",
5218                    task.short()
5219                );
5220            }
5221            let instruction = prepare_instruction(&starter, None, task)
5222                .unwrap_or_else(|| task.instruction.clone());
5223            Runner::start_naming(
5224                &repo,
5225                instruction,
5226                &task.title,
5227                config,
5228                crate::run::Origin::queue(&task.id),
5229            )
5230            .await
5231            .map(|mut r| {
5232                r.state.attachments = attachments.clone();
5233                r.state.sources = task.sources.clone();
5234                r
5235            })
5236        }
5237    }})).await;
5238    if let Err(error) = &started
5239        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
5240    {
5241        task.record_startup_failure(failure.clone());
5242    }
5243    let mut runner = match started {
5244        Ok(r) => r,
5245        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
5246            let detail = format!("{e:#}");
5247            task.last_error = Some(detail.clone());
5248            if e.is::<crate::build_target::AdmissionDiskWait>()
5249                && let Starter::Review(branch) = &starter
5250                && review_branch.is_some()
5251            {
5252                task.review_branch = Some(branch.clone());
5253                task.review_instruction = Some(task.instruction.clone());
5254            }
5255            if stop.parking() || interrupt_pause.parked() {
5256                let attempts = task.attempts;
5257                task.park(e.to_string());
5258                // Startup has not spent an attempt to refund.
5259                task.attempts = attempts;
5260            } else if e.is::<crate::build_target::AdmissionDiskWait>() {
5261                let disk_checked_at = task.disk_checked_at;
5262                task.hold_machine(Some(detail));
5263                task.mark_startup_disk_capacity();
5264                task.disk_checked_at = disk_checked_at;
5265            } else {
5266                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
5267            }
5268            record(queue, task);
5269            return Vec::new();
5270        }
5271        // A branch an earlier attempt still holds and magi will not release
5272        // by itself is the operator's call, not a failed attempt: hold the
5273        // task with the reason, spend nothing, and say so on the bell.
5274        Err(e) if task.pr_recovery.is_some() => {
5275            task.startup_notice_cause("startup-public-head");
5276            task.attempts += 1;
5277            task.last_error = Some(format!("{start_failed}{e:#}"));
5278            task.hold_unrequested_retry(Some(format!(
5279                "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."
5280            )));
5281            record(queue, task);
5282            return Vec::new();
5283        }
5284        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
5285            let detail = match e.downcast_ref::<crate::handover::Refused>() {
5286                Some(r) => (p.handover_refused)(r),
5287                None => format!("{e:#}"),
5288            };
5289            task.startup_notice_cause("startup-handover");
5290            let reason = format!("{start_failed}{detail}");
5291            task.last_error = Some(reason.clone());
5292            // Consumed above by `take`; keep it so the released task retries
5293            // as a review of this same branch.
5294            let branch = match &starter {
5295                Starter::Review(branch) => Some(branch.clone()),
5296                _ => None,
5297            };
5298            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
5299            // one page; the guidance rides in the reason, fixed per state so a
5300            // re-put never changes the wording and relights it.
5301            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5302            record(queue, task);
5303            tracing::warn!(
5304                "holding {} for a branch it cannot take over: {e:#}",
5305                task.short()
5306            );
5307            return Vec::new();
5308        }
5309        // A branch that differs between here and the remote in ways magi
5310        // cannot prove are the same change is a decision for the owner, not a
5311        // failed attempt: ask with both sides laid out, spend no attempt, and
5312        // let the answer requeue the task.
5313        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5314            let d = e
5315                .downcast_ref::<crate::reconcile::Diverged>()
5316                .expect("checked by the guard");
5317            let mut q = ask::Question::new(
5318                task.id.clone(),
5319                crate::reconcile::NODE.to_owned(),
5320                crate::reconcile::SEAT.to_owned(),
5321                d.summary(),
5322                d.detail(),
5323                d.choices(),
5324            );
5325            match Questions::open().put(&mut q) {
5326                Ok(()) => {
5327                    task.last_error = Some(format!("{e:#}"));
5328                    // Consumed above by `take`; the answer has to reach a review
5329                    // of this same branch, so keep pointing the task at it.
5330                    task.review_branch = Some(d.branch.clone());
5331                    task.review_instruction = Some(task.instruction.clone());
5332                    task.block(vec![q.id.clone()], Some(d.summary()));
5333                }
5334                Err(put) => {
5335                    tracing::warn!("could not file the divergence question: {put:#}");
5336                    task.attempts += 1;
5337                    task.fail_startup(
5338                        "startup-question-store",
5339                        format!("{start_failed}{e:#}"),
5340                        opts.max_attempts,
5341                    );
5342                }
5343            }
5344            record(queue, task);
5345            return Vec::new();
5346        }
5347        Err(e) => {
5348            // The answer was stale and nothing was applied: keep pointing at
5349            // the branch so the next attempt asks again against its new tips.
5350            // Nothing went wrong with the task, so no attempt is spent: a
5351            // budget one short of its limit must not hold it instead of
5352            // letting the question be asked again.
5353            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5354                && let Starter::Review(branch) = &starter
5355            {
5356                task.review_branch = Some(branch.clone());
5357                task.review_instruction = Some(task.instruction.clone());
5358                task.last_error = Some(format!("{start_failed}{e:#}"));
5359                task.status = crate::queue::TaskStatus::Failed;
5360                record(queue, task);
5361                return Vec::new();
5362            }
5363            task.attempts += 1;
5364            task.last_error = Some(format!("{start_failed}{e:#}"));
5365            task.startup_notice_cause("startup-source");
5366            task.hold_unrequested_retry(Some(format!(
5367                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5368            )));
5369            record(queue, task);
5370            return Vec::new();
5371        }
5372    };
5373    if !matches!(starter, Starter::Resume(_))
5374        && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
5375    {
5376        runner
5377            .state
5378            .event("build-cache", format!("{mode} selected by {source}"));
5379    }
5380    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5381        runner.state.recovery_config = Some(config_evidence);
5382    }
5383    if let Some(replacement) = &task.replacement {
5384        if matches!(starter, Starter::Start) {
5385            runner.state.instruction.push_str(&format!(
5386                "\n\n# Replacement review context\n{}",
5387                replacement.context
5388            ));
5389        }
5390        runner.state.replaces = Some(replacement.clone());
5391        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5392        if let Ok(mut old) = RunState::load(&replacement.run)
5393            && let Some(d) = &mut old.merge_decision
5394        {
5395            d.replacement_run = Some(runner.state.id.clone());
5396            old.event(
5397                "replacement",
5398                format!(
5399                    "replacement run {} owns the next attempt; old PR remains closed",
5400                    runner.state.id
5401                ),
5402            );
5403            if let Err(e) = old.save() {
5404                let error = runner.fail_startup("replacement-history", e);
5405                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5406                    task.record_startup_failure(failure.clone());
5407                }
5408                task.hold_manual(Some(format!(
5409                    "Could not link replacement history: {error:#}; no agents dispatched"
5410                )));
5411                record(queue, task);
5412                return Vec::new();
5413            }
5414        }
5415    }
5416    runner.state.task_instruction = Some(task.instruction.clone());
5417    // The follow-up depth is fixed now, while the task certainly exists:
5418    // deleting it later must not reset the cap (`crate::followup`).
5419    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5420    if runner.state.origin_chat.is_none() {
5421        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5422    }
5423    // A stop that means "park" reaches the graph through this handle.
5424    runner.on_pause(stop.pause());
5425    // `poll`'s interrupt scheduler reaches this one run - and no other -
5426    // through this handle. See `Pause`'s own doc for why these are never
5427    // the same one.
5428    runner.watch_interrupt(interrupt_pause);
5429
5430    // `start` has minted the run, so the task can now point at it. Persisting
5431    // `Running` before `execute` is what makes a crash mid-run legible.
5432    let run = runner.state.id.clone();
5433    let before_start = task.clone();
5434    task.start(run.clone());
5435    if let Err(error) = queue.put(task) {
5436        *task = before_start;
5437        let error = runner.fail_startup("task-start", error);
5438        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5439            task.record_startup_failure(failure.clone());
5440        }
5441        task.hold_manual(Some(format!(
5442            "Could not persist task start; no agents dispatched: {error:#}"
5443        )));
5444        record(queue, task);
5445        return Vec::new();
5446    }
5447    if task.status != TaskStatus::Running {
5448        // Queue::put kept a newer hold or continuation instead of this start.
5449        return Vec::new();
5450    }
5451    lock(status).current.push(Current {
5452        worker: None,
5453        task: task.id.clone(),
5454        run,
5455    });
5456
5457    // `RunState::quota` is the run's whole history across every resume, so
5458    // only what this execution added may arm the cooldown or earn a refund.
5459    let quota_before = runner.state.quota.clone();
5460    runner.state.carry_dispatched_resumes(task);
5461    runner.state.next_pass_task_entry = true;
5462    let result = runner.execute().await;
5463    finish_attempt(
5464        opts.max_attempts,
5465        queue,
5466        task,
5467        &runner.state,
5468        &quota_before,
5469        result,
5470    )
5471}
5472
5473async fn attempt_sync_only(
5474    queue: &Queue,
5475    status: &Arc<Mutex<Status>>,
5476    stop: &Stop,
5477    interrupt: crate::graph::Pause,
5478    task: &mut Task,
5479    request: crate::base_sync_only::Request,
5480) {
5481    let result = async {
5482        anyhow::ensure!(
5483            task.status == TaskStatus::Queued
5484                && task.execution_runs().last() == Some(&request.run)
5485                && task.resume_override.as_ref().is_some_and(
5486                    |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
5487                ),
5488            "sync-base-only request no longer owns the exact queued run"
5489        );
5490        let mut runner = Runner::resume(&request.run)?;
5491        anyhow::ensure!(
5492            public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
5493                .await?
5494                .is_none(),
5495            "the task still has a public execution owner"
5496        );
5497        anyhow::ensure!(
5498            !stop.parking() && !interrupt.parked(),
5499            "paused before base synchronization"
5500        );
5501        let original = task.clone();
5502        task.start(request.run.clone());
5503        task.attempts = original.attempts;
5504        if let Err(error) = queue.put(task) {
5505            *task = original;
5506            return Err(error);
5507        }
5508        if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
5509            return Ok(());
5510        }
5511        lock(status).current.push(Current {
5512            worker: None,
5513            task: task.id.clone(),
5514            run: request.run.clone(),
5515        });
5516        runner.on_pause(stop.pause());
5517        runner.watch_interrupt(interrupt);
5518        runner.execute_sync_only(request.clone()).await
5519    }
5520    .await;
5521    if task.sync_only.as_ref() == Some(&request) {
5522        let saved = RunState::load(&request.run).ok();
5523        let detail = result.err().map(|error| {
5524            format!("Base synchronization only: {error:#}; verification was not allowed")
5525        });
5526        crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
5527        record(queue, task);
5528    }
5529}
5530
5531/// Settle `task` after its run executed: the verdict, the diagnosis, the
5532/// supersession of earlier attempts and the save. Shared by the loop and by
5533/// `magi run --resume`, so an attempt is counted one way wherever it ran.
5534/// Returns the quota losses this execution added to the run.
5535pub fn finish_attempt(
5536    max_attempts: usize,
5537    queue: &Queue,
5538    task: &mut Task,
5539    state: &RunState,
5540    quota_before: &[QuotaLoss],
5541    result: Result<()>,
5542) -> Vec<QuotaLoss> {
5543    let detail = match result {
5544        Ok(()) => describe(state),
5545        Err(e) => format!("{e:#}"),
5546    };
5547    let fresh = losses_this_attempt(quota_before, &state.quota);
5548    let verdict = Verdict {
5549        status: state.status,
5550        // A run that opened a pull request handed its work over, whatever the
5551        // gate then decided about merging it.
5552        left_pr: state.pr.is_some(),
5553        // Only a rate limit earns the task its attempt back - and only one
5554        // suffered now: a refund justified by a previous session's loss is
5555        // the same mistake as re-arming the cooldown from it. A stalled run
5556        // resumed without hitting quota again therefore spends its attempt,
5557        // like any other failure of the task's own.
5558        quota_hit: !fresh.is_empty(),
5559        // A run that parked was asked to stop; that is not a failure and must
5560        // not spend an attempt, or replacing the binary a few times would
5561        // exhaust a task's budget without an agent ever misbehaving.
5562        parked: state.parked,
5563        // A quota loss that left nothing viable is the same machine fact as a
5564        // `Stalled` quota loss; see `settle`'s doc table.
5565        no_viable_candidates: state.viable().is_empty(),
5566    };
5567    if let Some(replacement) = &state.replaces
5568        && let Some(pr) = &state.pr
5569        && let Ok(mut old) = RunState::load(&replacement.run)
5570        && let Some(d) = &mut old.merge_decision
5571    {
5572        d.replacement_pr = Some(pr.url.clone());
5573        let _ = old.save();
5574    }
5575    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5576    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5577        task.hold_unrequested_retry(Some(format!(
5578            "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.",
5579            task.short()
5580        )));
5581    }
5582    if task.status == TaskStatus::Done {
5583        supersede_prior_runs(task, &crate::run::home());
5584    }
5585    record(queue, task);
5586    tracing::info!(
5587        "task {} is {} after run {} ({})",
5588        task.short(),
5589        task.status.as_str(),
5590        state.short(),
5591        label(state.status)
5592    );
5593    fresh
5594}
5595
5596/// A task a hand-started run leaves runnable (failed with attempts to spare,
5597/// or requeued) is **held**: nobody asked for a retry, and a loop starting
5598/// later must not spend agent calls on it. `magi task release` retries.
5599pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5600    // Parked work (including legacy Failed records with a parked run) is a
5601    // checkpoint or owner handoff, not an unrequested retry.
5602    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5603        && !awaiting_resume_with(task, RunState::load)
5604        // A run parked on the owner's word about a withheld PR title/body
5605        // resumes via `land_resume_state`, including review-only tasks that
5606        // `awaiting_resume_with` does not consider.
5607        && withheld_text_wait(task).is_none()
5608        && !(task.fresh_start && task.replacement.is_some())
5609    {
5610        let why = task.last_error.clone().map_or_else(
5611            || "the run did not finish".to_owned(),
5612            |e| format!("the run did not finish: {e}"),
5613        );
5614        task.hold_unrequested_retry(Some(format!(
5615            "{why}. It was started by hand, so it is not retried \
5616             automatically; `magi task release` retries it."
5617        )));
5618        record(queue, task);
5619    }
5620}
5621
5622/// Whether an attempt at a task whose newest run is `run` would resume that
5623/// run rather than start a fresh competition. `magi run --resume` hands a run
5624/// to a live loop only when this holds.
5625#[must_use]
5626pub fn loop_would_resume(run: &str) -> bool {
5627    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5628}
5629
5630/// A loop in another process that is alive right now: a fresh heartbeat in
5631/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
5632/// carries the pid it published (`None` inside when it published none - a
5633/// fresh heartbeat is still evidence of a live loop).
5634///
5635/// The one judgement of "is somebody else serving this queue", shared by the
5636/// web UI's refusal to start a second loop and by `magi run` / `magi review`
5637/// deciding whether to hand a task to the loop. A claim file proves nothing
5638/// here: whether a claim succeeds says nothing about whether its owner lives.
5639#[must_use]
5640pub fn foreign_loop(
5641    reading: Option<&Reading>,
5642    now: Timestamp,
5643    own_pid: u32,
5644) -> Option<Option<u32>> {
5645    let reading = reading.filter(|r| r.running(now))?;
5646    match reading.pid {
5647        Some(pid) if pid == own_pid => None,
5648        pid => Some(pid),
5649    }
5650}
5651
5652fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5653    reading.worker_protocol != Some(1)
5654        && (foreign_loop(Some(reading), now, own_pid).is_some()
5655            || reading
5656                .pid
5657                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5658}
5659
5660/// Low-level claimed-task execution shared by the detached standalone worker
5661/// and focused lifecycle fixtures. The caller must retain the queue claim for
5662/// this entire call. CLI callers transfer ownership through
5663/// [`run_detached_claimed`] instead of executing inside their own runtime.
5664///
5665/// The one deliberate difference from the loop: a task the attempt leaves
5666/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5667/// Nobody asked for a retry, and a daemon starting later must not spend agent
5668/// calls re-running a hand-started task behind the operator's back;
5669/// `magi task release` is the explicit retry.
5670pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5671    run_claimed_until(opts, queue, task, &Stop::new()).await;
5672}
5673
5674async fn run_claimed_until(
5675    opts: &Opts,
5676    queue: &Queue,
5677    task: &mut Task,
5678    stop: &Stop,
5679) -> Vec<QuotaLoss> {
5680    let status = Arc::new(Mutex::new(Status::new()));
5681    // An attempt embeds startup and graph futures. Keep it off the standalone
5682    // caller's stack, on both the initial execution and withheld-text resume.
5683    let mut quota = Box::pin(attempt(
5684        opts,
5685        queue,
5686        &status,
5687        stop,
5688        crate::graph::Pause::new(),
5689        task,
5690    ))
5691    .await;
5692    // A run parked on the owner's word about a withheld PR title/body has no
5693    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5694    // here with the claim still held, and resume once the question is settled
5695    // (answered, or abandoned at its deadline -> the neutral text).
5696    // A rejected reply files one more question (the gate asks at most twice),
5697    // so after a resume the run may be waiting again: keep going, with a fresh
5698    // limit for the new question. `resumes` bounds it even if a resume parks
5699    // without asking anything new.
5700    let mut resumes = 0;
5701    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5702        let Some(timeout) = withheld_text_wait(task) else {
5703            break;
5704        };
5705        eprintln!(
5706            "waiting for the owner's answer on a withheld pull request text \
5707             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5708        );
5709        // The deadline abandons the question itself; the extra margin only
5710        // covers an abandon that could not be saved.
5711        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5712        let ready = loop {
5713            match land_resume_state(task) {
5714                LandResume::StillWaiting
5715                    if !stop.parking() && std::time::Instant::now() < limit =>
5716                {
5717                    tokio::time::sleep(WITHHELD_POLL).await;
5718                }
5719                LandResume::Ready => break true,
5720                _ => break false,
5721            }
5722        };
5723        if !ready || stop.parking() {
5724            break;
5725        }
5726        resumes += 1;
5727        quota.extend(
5728            Box::pin(attempt(
5729                opts,
5730                queue,
5731                &status,
5732                stop,
5733                crate::graph::Pause::new(),
5734                task,
5735            ))
5736            .await,
5737        );
5738    }
5739    hold_if_runnable(queue, task);
5740    quota
5741}
5742
5743/// Resumes an in-process run makes for withheld-text questions: the gate asks
5744/// at most twice, plus one for a resume that asks nothing new.
5745const MAX_WITHHELD_RESUMES: u32 = 3;
5746
5747/// How often an in-process run rechecks its withheld-text question.
5748const WITHHELD_POLL: Duration = Duration::from_secs(15);
5749
5750/// The `answer_timeout` (seconds) of the task's last run when that run is
5751/// parked on an unresolved withheld-text question; `None` otherwise.
5752fn withheld_text_wait(task: &Task) -> Option<u64> {
5753    let id = task.execution_runs().last()?;
5754    let s = RunState::load(id).ok()?;
5755    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5756        .then_some(s.config.graph.answer_timeout)
5757}
5758
5759/// The quota losses `after` holds that `before` did not: what one execution
5760/// suffered, as opposed to the run's history.
5761///
5762/// Compared by value rather than by length or position because
5763/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5764/// the vector can shrink and shift under a resume. A retried seat that hits
5765/// quota again is a `push` with a new `at`, so it shows up as new here.
5766/// Crash recovery uses the recorded pass start as its boundary when available;
5767/// legacy records without passes retain their original history-based policy.
5768fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5769    after
5770        .iter()
5771        .filter(|q| !before.contains(q))
5772        .cloned()
5773        .collect()
5774}
5775
5776/// When the loop-wide quota cooldown should end, given this attempt's losses;
5777/// `None` when there were none. Reset-hint parsing and the cap live here.
5778fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5779    let quota: Vec<_> = quota
5780        .iter()
5781        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5782        .collect();
5783    if quota.is_empty() {
5784        return None;
5785    }
5786    let with_hint = quota.iter().find(|q| q.reset.is_some());
5787    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5788    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5789    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5790    Some(
5791        now.checked_add(jiff::SignedDuration::from_secs(secs))
5792            .unwrap_or(Timestamp::MAX),
5793    )
5794}
5795
5796/// An explicit task count must agree with a run before any resume.
5797fn implementers_match(task: &Task, state: &RunState) -> bool {
5798    task.replacement.as_ref().map_or_else(
5799        || {
5800            task.implementers()
5801                .is_none_or(|n| n == state.config.graph.implementers)
5802        },
5803        |replacement| {
5804            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5805                && state.config.graph.implementers == 1
5806        },
5807    )
5808}
5809
5810/// Never resume or take over candidate work built for a different seat count.
5811fn starter_with_implementers(
5812    task: &Task,
5813    previous: Option<&RunState>,
5814    proposed: Starter,
5815) -> Starter {
5816    if previous.is_some_and(|s| !implementers_match(task, s)) {
5817        task.review_of
5818            .as_ref()
5819            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5820    } else {
5821        proposed
5822    }
5823}
5824
5825/// Apply this task's explicit count to the new attempt, without changing defaults.
5826fn apply_task_implementers(config: &mut Config, task: &Task) {
5827    if let Some(n) = task.implementers() {
5828        config.graph.implementers = n;
5829    }
5830}
5831
5832/// [`prepare`] for one task: its own `--config` and command-line overrides
5833/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5834/// over the loop's, so handing a hand-started task to a daemon changes nothing
5835/// about what it does.
5836#[cfg(test)]
5837fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5838    let explicit = match &task.overrides {
5839        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5840        _ => opts.config.as_deref(),
5841    };
5842    let (mut config, _) = Config::discover(repo, explicit)?;
5843    apply_options(&mut config, opts, task)?;
5844    Ok(config)
5845}
5846
5847fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5848    if task
5849        .overrides
5850        .as_ref()
5851        .is_none_or(|o| o.inherit_daemon_options)
5852        && let Some(mode) = opts.merge.as_deref()
5853    {
5854        config.merge.mode = merge_mode(mode)?;
5855    }
5856    if let Some(o) = &task.overrides {
5857        o.apply(config);
5858    }
5859    if let Some((mode, _)) = task.build_cache_override(config) {
5860        config.verify.build_cache = mode;
5861    }
5862    Ok(())
5863}
5864
5865/// Load the config for a task's repository, with the merge override applied.
5866fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5867    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5868    if let Some(mode) = &opts.merge {
5869        config.merge.mode = merge_mode(mode)?;
5870    }
5871    Ok(config)
5872}
5873
5874/// Prune the shared build cache at a between-runs boundary. The detached cache
5875/// service checks authoritative task jobs first; dispatch waits for that finite
5876/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5877/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5878async fn maybe_prune_cache_between_runs(
5879    repo: &Path,
5880    opts: &Opts,
5881    home: &Path,
5882    stop: &Stop,
5883    last_checked: &mut Option<Timestamp>,
5884    now: Timestamp,
5885) {
5886    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5887        return;
5888    }
5889    *last_checked = Some(now);
5890    let cfg = match prepare(repo, opts) {
5891        Ok(cfg) => cfg,
5892        Err(e) => {
5893            tracing::warn!("cache check: no config: {e:#}");
5894            return;
5895        }
5896    };
5897    match clean::prune_cache_if_over_limit(&cfg, home) {
5898        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5899            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5900            pruned.files,
5901            pruned.freed
5902        ),
5903        Ok(_) => {}
5904        Err(e) => {
5905            tracing::warn!("housekeep: prune cache: {e:#}");
5906            notices::raise_in(
5907                home,
5908                Notice::warn(
5909                    "housekeep:cache",
5910                    format!(
5911                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5912                        e.to_string()
5913                            .lines()
5914                            .next()
5915                            .unwrap_or("unknown cleanup error")
5916                    ),
5917                ),
5918            );
5919        }
5920    }
5921}
5922
5923/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5924/// now, given when it last did (if ever). Pure, so the cadence is asserted
5925/// directly rather than by waiting out real minutes in a test.
5926fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5927    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5928}
5929
5930/// The disk janitor, with its housekeeping logged rather than fatal.
5931///
5932/// Called only at the loop's idle points, for the reason the caller documents:
5933/// a prune racing a live compile would delete files mid-build. The config is
5934/// re-read on every call because the repository that just ran may not be the
5935/// daemon's own default, and the cache directory is a repository fact.
5936///
5937/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5938/// and [`crate::run::default_worktree_root`] read here, for the same reason
5939/// [`drive`] takes its queue and status file rather than resolving them: a
5940/// test driving the loop must not reach through to the operator's real home
5941/// or worktree bay just because the janitor runs on every idle tick.
5942/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5943/// to get wrong silently - a test's `home` was already isolated, but nothing
5944/// exercised the parameter next to it, so a real worktree bay stayed wired in
5945/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5946/// it for real, every test in this file that drives the loop at all started
5947/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5948async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5949    let cfg = match prepare(repo, opts) {
5950        Ok(cfg) => cfg,
5951        Err(e) => {
5952            tracing::warn!("housekeep: no config: {e:#}");
5953            return;
5954        }
5955    };
5956    // A run's own worktree lives under `config.graph.worktree_root` when the
5957    // repository sets one - the same precedence `RunState::worktree_root`
5958    // uses - and `worktrees_root` only stands in for the *default* an
5959    // unconfigured repository resolves to (see this function's own
5960    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5961    // that always swept the default regardless of this override would never
5962    // see, and so never reclaim, a single worktree for a repository that
5963    // relocated them elsewhere.
5964    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5965    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5966    // Reported whenever there is anything to say, not only when `folded > 0`:
5967    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5968    // folded, on every single pass, for months - a report gated on `folded`
5969    // would have stayed silent through every one of them.
5970    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5971        let mut extra = Vec::new();
5972        if out.unreadable > 0 {
5973            extra.push(format!("{} unreadable", out.unreadable));
5974        }
5975        if out.orphaned_worktrees > 0 {
5976            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5977        }
5978        let detail = if extra.is_empty() {
5979            String::new()
5980        } else {
5981            format!(" ({})", extra.join(", "))
5982        };
5983        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5984    }
5985    if out.external_merges_recorded > 0 {
5986        tracing::info!(
5987            "housekeep: recorded {} run(s) as merged externally",
5988            out.external_merges_recorded
5989        );
5990    }
5991    if out.stale_pr_states_repaired > 0 {
5992        tracing::info!(
5993            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5994            out.stale_pr_states_repaired
5995        );
5996    }
5997    if out.cache_files > 0 {
5998        tracing::info!(
5999            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
6000            out.cache_files,
6001            out.cache_freed
6002        );
6003    }
6004    if out.questions_abandoned > 0 {
6005        tracing::info!(
6006            "housekeep: abandoned {} question(s) left open by a finished run",
6007            out.questions_abandoned
6008        );
6009    }
6010}
6011
6012/// Run [`triage::run_once`] and log whatever it did, the same "only when
6013/// there is something to say" rule [`janitor`] follows for its own report.
6014///
6015/// Called at the same idle points as [`janitor`] - once per full poll
6016/// interval, never mid-attempt - for the same reason: it is not liveness
6017/// critical, and a task's own `hold_reason` string is the one thing this
6018/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
6019/// tick for no benefit.
6020async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
6021    let questions = Questions::at(home.join("questions"));
6022    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
6023    if report.is_empty() {
6024        return;
6025    }
6026    if !report.quarantined.is_empty() {
6027        tracing::info!(
6028            "triage: held {} blocked task(s) whose blocked-on task or \
6029             question no longer exists: {}",
6030            report.quarantined.len(),
6031            report.quarantined.join(", ")
6032        );
6033    }
6034    if !report.resumed.is_empty() {
6035        tracing::info!(
6036            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
6037            report.resumed.len(),
6038            report.resumed.join(", ")
6039        );
6040    }
6041    if !report.asked.is_empty() {
6042        tracing::info!(
6043            "triage: asked about {} held task(s): {}",
6044            report.asked.len(),
6045            report.asked.join(", ")
6046        );
6047    }
6048    if !report.answered.is_empty() {
6049        tracing::info!(
6050            "triage: applied {} operator answer(s): {}",
6051            report.answered.len(),
6052            report.answered.join(", ")
6053        );
6054    }
6055}
6056
6057/// The free-space gate: what stands between this task and a new run, if
6058/// anything. `Some(reason)` holds the task; `None` lets it start.
6059///
6060/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
6061/// the operator opted out. A measurement failure is a gate, not a pass: both
6062/// sides of "cannot tell" are served by not starting.
6063pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
6064    disk_gate_at(repo, config, crate::run::home)
6065}
6066
6067pub(crate) fn disk_gate_at(
6068    repo: &Path,
6069    config: &Config,
6070    home: impl FnOnce() -> PathBuf,
6071) -> Option<String> {
6072    let measure = if crate::build_target::isolated(config) {
6073        crate::disk::managed_free_bytes
6074    } else {
6075        crate::disk::free_bytes
6076    };
6077    disk_gate_with(repo, config, home, measure)
6078}
6079
6080/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
6081/// test can assert the exact wiring `attempt` runs - config's threshold in,
6082/// task-holding reason out - without asking the real machine's disk anything.
6083fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
6084    repo: &Path,
6085    config: &Config,
6086    home: impl FnOnce() -> PathBuf,
6087    free_bytes: F,
6088) -> Option<String> {
6089    let min = config.disk.min_free_bytes;
6090    if min == 0 {
6091        return None;
6092    }
6093    let output = match config.verify.build_cache {
6094        BuildCache::Shared => config.cache_dir(),
6095        BuildCache::Isolated => Some(home()),
6096    };
6097    let default_worktree_root;
6098    let worktree_root = match config.graph.worktree_root.as_deref() {
6099        Some(root) => root,
6100        None => {
6101            default_worktree_root = crate::run::default_worktree_root();
6102            &default_worktree_root
6103        }
6104    };
6105    for path in [Some(repo), output.as_deref(), Some(worktree_root)]
6106        .into_iter()
6107        .flatten()
6108    {
6109        let probe = if path == repo {
6110            path
6111        } else {
6112            path.ancestors().find(|p| p.exists()).unwrap_or(path)
6113        };
6114        let reason = match free_bytes(probe) {
6115            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
6116            Err(e) => Some(crate::disk::unmeasured_in(
6117                probe,
6118                &e,
6119                &config.graph.language,
6120            )),
6121        };
6122        if reason.is_some() {
6123            return reason;
6124        }
6125    }
6126    None
6127}
6128
6129/// How long to wait before offering another task when a run lost a seat to a
6130/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
6131/// could read, or carried nothing at all. Long enough that a quota outage
6132/// cannot burn through a whole backlog in the few seconds each doomed attempt
6133/// takes to fail; short enough that a quota which clears early is not left
6134/// idle for the fallback's sake.
6135const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
6136
6137/// Longest a parsed reset hint may push the wait out to. The hint comes from
6138/// the CLI's own words, not a contract, so a parsing slip that lands a day
6139/// away must not leave the loop asleep for a day.
6140const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
6141
6142/// How long [`poll`] should wait before offering the next task, after a run
6143/// lost at least one seat to a rate limit.
6144///
6145/// Pure and separate from the loop so the policy can be exercised without a
6146/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
6147/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
6148/// nothing to parse, or the parsed time has already passed; `cap` bounds how
6149/// far a parsed hint is trusted to push the wait out.
6150fn quota_wait(
6151    reset_at: Option<Timestamp>,
6152    now: Timestamp,
6153    fallback: Duration,
6154    cap: Duration,
6155) -> Duration {
6156    match reset_at {
6157        Some(at) if at > now => {
6158            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
6159            Duration::from_secs(secs).min(cap)
6160        }
6161        _ => fallback,
6162    }
6163}
6164
6165/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
6166///
6167/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
6168/// explains why parsing it exactly "would be a bug factory" — so this only
6169/// recognises the shapes actually observed in the wild, and returns `None`
6170/// for anything else rather than guess at a format nobody has seen.
6171///
6172/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
6173/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
6174/// said it, not from whenever this loop happens to read it: anchoring on `now`
6175/// would push the reset later on every read and would read an already-elapsed
6176/// reset as still in the future. (A long hint is still clamped by
6177/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
6178fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
6179    parse_reset_hint_zoned(text, now)
6180        .or_else(|| parse_reset_hint_dated(text))
6181        .or_else(|| parse_reset_hint_relative(text, recorded))
6182}
6183
6184/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
6185/// optional but at least one required, in that order. A bare number or any
6186/// unknown unit is refused.
6187fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
6188    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
6189    let mut rest = rest.trim();
6190    if rest.is_empty() {
6191        return None;
6192    }
6193    let mut total: i64 = 0;
6194    let mut matched = false;
6195    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
6196        if let Some((digits, tail)) = rest.split_once(unit)
6197            && !digits.is_empty()
6198            && digits.bytes().all(|b| b.is_ascii_digit())
6199        {
6200            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
6201            rest = tail;
6202            matched = true;
6203        }
6204    }
6205    if !rest.is_empty() || !matched {
6206        return None;
6207    }
6208    recorded
6209        .checked_add(jiff::SignedDuration::from_secs(total))
6210        .ok()
6211}
6212
6213/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
6214/// case-insensitive) into a 24-hour hour and minute. Shared by every
6215/// reset-hint shape below.
6216fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
6217    let clock = clock.trim().to_lowercase();
6218    let (digits, pm) = clock
6219        .strip_suffix("am")
6220        .map(|d| (d, false))
6221        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
6222    let (h, m) = digits.trim().split_once(':')?;
6223    let mut hour: i8 = h.trim().parse().ok()?;
6224    let minute: i8 = m.trim().parse().ok()?;
6225    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
6226        return None;
6227    }
6228    if pm && hour != 12 {
6229        hour += 12;
6230    } else if !pm && hour == 12 {
6231        hour = 0;
6232    }
6233    Some((hour, minute))
6234}
6235
6236/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
6237/// and a zone, never a date. A clock reading already past today is read as
6238/// tomorrow's: a CLI naming a same-day reset that has already gone by means
6239/// the window rolled over while nothing was watching.
6240fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
6241    let open = text.find('(')?;
6242    let close = text.rfind(')')?;
6243    if close <= open {
6244        return None;
6245    }
6246    let zone = text[open + 1..close].trim();
6247    let (hour, minute) = parse_12h_clock(&text[..open])?;
6248    let tz = jiff::tz::TimeZone::get(zone).ok()?;
6249    let candidate = now
6250        .to_zoned(tz)
6251        .with()
6252        .hour(hour)
6253        .minute(minute)
6254        .second(0)
6255        .millisecond(0)
6256        .microsecond(0)
6257        .nanosecond(0)
6258        .build()
6259        .ok()?;
6260    let mut at = candidate.timestamp();
6261    if at <= now {
6262        at += jiff::SignedDuration::from_hours(24);
6263    }
6264    Some(at)
6265}
6266
6267/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
6268/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
6269/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
6270/// "already past today" correction to make: the year already disambiguates
6271/// it. Scanned as a five-word window so it can be pulled out of the middle
6272/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
6273/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
6274/// any other timestamp with no zone attached.
6275fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
6276    let words: Vec<&str> = text.split_whitespace().collect();
6277    if words.len() < 5 {
6278        return None;
6279    }
6280    (0..=words.len() - 5)
6281        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
6282}
6283
6284/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
6285/// parenthesis right after the window is refused rather than ignored — it
6286/// reads as an explicit zone annotation on a shape that otherwise carries
6287/// none, and guessing UTC anyway would be exactly the silent misread this
6288/// module's parsing otherwise avoids.
6289fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
6290    if trailing.is_some_and(|next| next.starts_with('(')) {
6291        return None;
6292    }
6293    let month = month_number(window[0])?;
6294    let day_token = window[1].strip_suffix(',')?.to_lowercase();
6295    let day_digits = ["st", "nd", "rd", "th"]
6296        .iter()
6297        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
6298    let day: i8 = day_digits.parse().ok()?;
6299    let year_token = window[2];
6300    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
6301        return None;
6302    }
6303    let year: i16 = year_token.parse().ok()?;
6304    // The am/pm word carries the sentence's own trailing punctuation, e.g.
6305    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
6306    // reusing the same 12-hour clock reader the bracketed shape uses.
6307    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
6308    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
6309    let date = jiff::civil::Date::new(year, month, day).ok()?;
6310    let candidate = date
6311        .at(hour, minute, 0, 0)
6312        .to_zoned(jiff::tz::TimeZone::UTC)
6313        .ok()?;
6314    Some(candidate.timestamp())
6315}
6316
6317/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
6318/// case-insensitively, into a 1-based month number.
6319fn month_number(name: &str) -> Option<i8> {
6320    const NAMES: [&str; 12] = [
6321        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
6322    ];
6323    let lower = name.to_lowercase();
6324    NAMES
6325        .iter()
6326        .position(|n| *n == lower.as_str())
6327        .map(|i| i as i8 + 1)
6328}
6329
6330/// Test probe for the shared resume policy's review-budget exclusion.
6331#[cfg(test)]
6332fn exhausted_review_budget(state: &RunState) -> bool {
6333    // A run whose task-head publication failed has nothing left to review:
6334    // resuming it only retries the publication, so it is never "exhausted".
6335    !crate::handover::can_resume(state)
6336        && state.status == RunStatus::Blocked
6337        && !state.released()
6338        && state.retired_to.is_none()
6339}
6340
6341/// This task's *most recent* run, if resuming it would actually make
6342/// progress. `short` is only for the warning's own message.
6343///
6344/// Only ever `runs.last()` — never a search back through older history.
6345/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
6346/// mint, oldest first, and every entry before the last one was already
6347/// superseded at the moment it was minted: the daemon only ever starts a new
6348/// run when the previous one was not worth resuming (unresumable, exhausted,
6349/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
6350/// opens a fresh review-only run alongside an older, already-failed
6351/// competition. Searching further back would let an old run that merely
6352/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
6353/// behind, say — get resumed instead of the fresh competition
6354/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
6355/// nothing asked to revisit.
6356///
6357/// Two runs paid for the "prefer resuming over restarting" half of this
6358/// lesson, which is why this still checks `runs.last()` rather than always
6359/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
6360/// task a moment later, duplicating two and a half hours of agent work. Then
6361/// b25f stalled on a judge that timed out and one that answered with no JSON
6362/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
6363/// **one second** later, buying three fresh implementations to reach the
6364/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
6365/// the second case: a stall is terminal, and its cheap recovery re-asks only
6366/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
6367/// that is technically `resumable()` but provably cannot progress must not
6368/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
6369/// no-op instead of the fresh competition it promises.
6370///
6371/// A load failure is warned about rather than silently read as "not
6372/// resumable": the alternative is exactly what let a schema mismatch on run
6373/// `eba2` fall through to a full re-competition with nobody told why.
6374/// `crate::conduct` is what actually offers a better answer than
6375/// `Runner::start` here (see `Recovery::Review`), once this task's next
6376/// failure shows it up as `held`/`failed` with the run state unreadable.
6377fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
6378    unfinished_run_with(runs, short, RunState::load)
6379}
6380
6381/// [`unfinished_run`] with an injected state reader. Tests provide their
6382/// fixtures directly rather than touching the process-global run home.
6383pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6384where
6385    F: FnMut(&str) -> Result<RunState>,
6386{
6387    let mut id = runs.last()?.clone();
6388    let mut visited = std::collections::BTreeSet::new();
6389    let mut repo = None;
6390    loop {
6391        if !runs.contains(&id) || !visited.insert(id.clone()) {
6392            tracing::warn!("invalid or cyclic recovery authority for task {short}");
6393            return None;
6394        }
6395        let state = match load(&id) {
6396            Ok(state) if state.id == id => state,
6397            Ok(_) => return None,
6398            Err(e) => {
6399                tracing::warn!("could not read run {id} for task {short}: {e:#}");
6400                return None;
6401            }
6402        };
6403        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6404            return None;
6405        }
6406        repo = Some(state.repo.clone());
6407        if let Some(authority) = state.retired_to {
6408            id = authority;
6409            continue;
6410        }
6411        return (crate::handover::can_resume(&state)
6412            && state.liveness(false) != crate::run::Liveness::Live)
6413            .then_some(id);
6414    }
6415}
6416
6417/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
6418/// that [`attempt`] will resume it on its own?
6419///
6420/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
6421/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
6422/// injected reader like its sibling. An unreadable run is not awaiting
6423/// anything: it keeps going to the conductor as before.
6424fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6425where
6426    F: FnOnce(&str) -> Result<RunState>,
6427{
6428    // `Failed` stays: a record an older build wrote for a parked run.
6429    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6430        || task.fresh_start
6431        || task.review_branch.is_some()
6432    {
6433        return false;
6434    }
6435    let Some(id) = task.execution_runs().last() else {
6436        return false;
6437    };
6438    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6439}
6440
6441/// Which of the three ways [`attempt`] can mint or continue a run this task
6442/// should use.
6443#[derive(Debug, Clone, PartialEq, Eq)]
6444enum Starter {
6445    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
6446    /// and that still exists.
6447    Review(String),
6448    /// `crate::graph::Runner::resume` on an unfinished run of this task.
6449    Resume(String),
6450    /// `crate::graph::Runner::start`: a fresh competition.
6451    Start,
6452}
6453
6454/// A second bound independent of inputs and the resettable failure counter.
6455/// Count execution and failed-startup recovery records once per run. Startup
6456/// failures can retain unrecorded preparation assets without an execution pass.
6457/// Unknown history is not evidence that a new set of worktrees is affordable.
6458fn retained_attempt_hold(
6459    task: &Task,
6460    starter: &Starter,
6461    limit: usize,
6462    mut load: impl FnMut(&str) -> Result<RunState>,
6463) -> Option<String> {
6464    if limit == 0 || matches!(starter, Starter::Resume(_)) {
6465        return None;
6466    }
6467    let mut retained = 0;
6468    for id in task
6469        .runs
6470        .iter()
6471        .chain(task.startup_failures.iter().map(|failure| &failure.run))
6472        .collect::<std::collections::BTreeSet<_>>()
6473    {
6474        let state = match load(id) {
6475            Ok(state) if state.id == *id => state,
6476            _ => {
6477                return Some(format!(
6478                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6479                ));
6480            }
6481        };
6482        if state.retired_to.is_some() || state.released() {
6483            continue;
6484        }
6485        // Neither a completed status nor an empty candidate array proves that
6486        // all recovery sources (including unrecorded preparation) were retired.
6487        retained += 1;
6488    }
6489    (retained >= limit).then(|| format!(
6490        "[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."
6491    ))
6492}
6493
6494/// A selected public implementation overrides every historical candidate and pin.
6495fn selected_starter(
6496    selected: &crate::pr_recovery::Selection,
6497    previous: Option<&RunState>,
6498    unfinished: Option<&str>,
6499) -> Starter {
6500    if let Some(id) = unfinished
6501        && previous.is_some_and(|r| {
6502            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6503        })
6504    {
6505        Starter::Resume(id.to_owned())
6506    } else {
6507        Starter::Review(selected.branch.clone())
6508    }
6509}
6510
6511/// The owner's answer to this branch's divergence question, consumed from the
6512/// task so a later, different divergence asks again. The runner applies it
6513/// (see `Runner::review_taking_over`), after the earlier worktree is released.
6514fn take_divergence_answer(
6515    branch: &str,
6516    remote: &str,
6517    task: &mut Task,
6518) -> Option<crate::reconcile::Choice> {
6519    let summary = crate::reconcile::summary_for(branch, remote);
6520    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6521        (a.question == summary)
6522            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6523            .flatten()
6524            .map(|c| (i, c))
6525    })?;
6526    task.answers.remove(idx);
6527    Some(choice)
6528}
6529
6530/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
6531/// this attempt should use. Pure, and separate from [`attempt`], so the
6532/// routing itself is assertable without spawning a real graph or a git
6533/// process: `attempt`'s own `crate::git::branch_exists` call has already
6534/// happened by the time this is called.
6535///
6536/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
6537/// whose branch is gone falls all the way through to [`Starter::Start`], not
6538/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
6539/// old (likely `Blocked`) run in the first place, and a branch that vanished
6540/// out from under that choice is not evidence resuming it would fare better.
6541fn choose_starter(
6542    review_branch: Option<&str>,
6543    branch_exists: bool,
6544    unfinished: Option<&str>,
6545) -> Starter {
6546    match review_branch {
6547        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6548        Some(_) => Starter::Start,
6549        None => match unfinished {
6550            Some(id) => Starter::Resume(id.to_owned()),
6551            None => Starter::Start,
6552        },
6553    }
6554}
6555
6556/// Reuse a compatible latest review owner instead of taking its checked-out
6557/// branch into a new run. Different branches and changed criteria still use
6558/// the ordinary review/takeover policy.
6559fn review_retry_starter(
6560    task: &Task,
6561    previous: Option<&RunState>,
6562    branch: Option<&str>,
6563    exists: bool,
6564    unfinished: Option<&str>,
6565) -> Starter {
6566    if let Some(run) = previous
6567        && unfinished == Some(run.id.as_str())
6568        && run.reviewed_commits.is_some()
6569        && branch.is_some_and(|branch| {
6570            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6571        })
6572        && may_resume_run(run, task)
6573    {
6574        return Starter::Resume(run.id.clone());
6575    }
6576    match (branch, unfinished, &task.review_of) {
6577        (None, None, Some(branch)) => Starter::Review(branch.clone()),
6578        _ => choose_starter(branch, exists, unfinished),
6579    }
6580}
6581
6582/// A retained review is valid only while its authored criteria still match.
6583fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
6584    task.review_branch
6585        .as_deref()
6586        .filter(|&branch| match &task.review_instruction {
6587            Some(authored) => *authored == task.instruction,
6588            // Legacy retained branches must agree with their prior run; only an
6589            // explicitly pinned review can proceed without recoverable provenance.
6590            None => previous.map_or_else(
6591                || task.review_of.as_deref() == Some(branch),
6592                |run| compatible_run_instruction(run, task),
6593            ),
6594        })
6595}
6596
6597/// A current explicit pin can select an otherwise incompatible run. Edits
6598/// and subsequent approvals invalidate pins selected for earlier criteria.
6599fn may_resume_run(run: &RunState, task: &Task) -> bool {
6600    if !task.assignment_accepts(run) {
6601        return false;
6602    }
6603    task.resume_override
6604        .as_ref()
6605        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6606        || compatible_run_instruction(run, task)
6607}
6608
6609/// Review scaffolding is execution context, not evidence of an operator edit.
6610pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6611    if let Some(authored) = &run.task_instruction {
6612        return compatible_instruction(authored, task);
6613    }
6614    if compatible_instruction(&run.instruction, task) {
6615        return true;
6616    }
6617    // Recognize only the existing generated review shapes on legacy runs.
6618    // Ordinary authored text with a similar heading is left intact.
6619    if run.reviewed_commits.is_some() {
6620        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6621            return strip_answers_block(authored, task).trim() == task.instruction.trim();
6622        }
6623        if let Some(branch) = &task.review_of {
6624            let canonical = format!(
6625                "Review the branch `{branch}` (review-only: no implementation, no judging)."
6626            );
6627            let generated = format!(
6628                "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"
6629            );
6630            return task.instruction == canonical && run.instruction.starts_with(&generated);
6631        }
6632    }
6633    false
6634}
6635
6636/// Compare authored instructions, excluding answer blocks appended by the daemon.
6637pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6638    strip_answers_block(old, task) == task.instruction
6639}
6640
6641/// Which repository a task runs in. A task that names none — the normal case
6642/// for one filed from a phone — runs in the daemon's own default.
6643fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6644    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6645        return fallback.to_path_buf();
6646    }
6647    task.repo.clone()
6648}
6649
6650/// The header [`append_answers`] appends operator answers under. Shared with
6651/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
6652/// rather than grown a new block on every resume.
6653const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6654
6655/// Render the first `count` answers in the block appended to an instruction.
6656fn answers_block(task: &Task, count: usize) -> String {
6657    let mut s = ANSWERS_HEADER.to_owned();
6658    for a in &task.answers[..count] {
6659        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6660    }
6661    s
6662}
6663
6664/// Render the approval independently of transient task state, so historical
6665/// suffixes remain recognizable after another explicit release.
6666fn resumption_block(r: &crate::queue::Resumption) -> String {
6667    format!(
6668        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6669         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6670        r.generation, r.at, r.instruction, r.answers_through,
6671    )
6672}
6673
6674/// Append audit answers and the latest explicit approval to the instruction.
6675fn append_answers(base: &str, task: &Task) -> String {
6676    let mut s = base.to_owned();
6677    if !task.answers.is_empty() {
6678        s.push_str(&answers_block(task, task.answers.len()));
6679    }
6680    if let Some(r) = &task.resumption {
6681        s.push_str(&resumption_block(r));
6682    }
6683    s
6684}
6685
6686/// Drop the prior answer block only when it is exactly the suffix this task
6687/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6688/// the task author is ordinary instruction text, not a block to remove.
6689fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6690    let mut instruction = instruction;
6691    for approval in task
6692        .resumption
6693        .iter()
6694        .chain(task.resumption_history.iter().rev())
6695    {
6696        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6697            instruction = base;
6698            break;
6699        }
6700    }
6701    for count in (1..=task.answers.len()).rev() {
6702        let block = answers_block(task, count);
6703        if let Some(base) = instruction.strip_suffix(&block) {
6704            return base;
6705        }
6706    }
6707    instruction
6708}
6709
6710/// The instruction handed to `Runner::start`: the task's own text, plus any
6711/// operator answers `crate::conduct` collected for it (see
6712/// [`Task::answers`]), so a decision the operator actually made reaches the
6713/// implementers rather than only clearing the block that was waiting on it.
6714///
6715/// Appended rather than merged into [`Task::instruction`] itself, so the
6716/// task's own record stays exactly what its author wrote.
6717fn instruction_for(task: &Task) -> String {
6718    append_answers(&task.instruction, task)
6719}
6720
6721/// The instruction a resumed run should carry on with: whatever it already
6722/// had, refreshed with the task's *current* operator answers.
6723///
6724/// A resumable run's own `RunState::instruction` predates any answer
6725/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6726/// the behaviour before this function existed — silently drops the very
6727/// decision the operator made to unblock it. Re-stripping any block this
6728/// function appended on an earlier resume before re-appending the current
6729/// list (rather than blindly appending again) is what keeps a task resumed
6730/// three times over three answered questions from carrying the same answer
6731/// three times.
6732fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6733    append_answers(strip_answers_block(old_instruction, task), task)
6734}
6735
6736/// Preserve the producer's verified boundary and target, independent of prose.
6737fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6738    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6739    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6740    if let Some(cause) = task.hold_notice_cause.as_mut() {
6741        cause.target = failure.map(|f| f.target.clone());
6742    }
6743}
6744
6745#[derive(Debug, thiserror::Error)]
6746#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6747struct MissingAttachment {
6748    name: String,
6749    path: PathBuf,
6750}
6751
6752/// The task's attachments as absolute paths, each checked to still exist.
6753fn task_attachments(
6754    queue: &Queue,
6755    task: &Task,
6756) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6757    let paths = queue.attachment_paths(task);
6758    for (name, path) in task.attachments.iter().zip(&paths) {
6759        if !path.is_file() {
6760            return Err(MissingAttachment {
6761                name: name.clone(),
6762                path: path.clone(),
6763            });
6764        }
6765    }
6766    Ok(paths)
6767}
6768
6769/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6770/// answers before handing it to `Runner` — the actual boundary between
6771/// [`choose_starter`]'s routing and the graph, factored out so it is
6772/// assertable without a real repository, git branch, or agent CLI.
6773///
6774/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6775/// instruction from the reviewed branch's own commit log because there is no
6776/// task statement to speak of for hand-written work, and splicing operator
6777/// answers into that text would contradict the very message it sends
6778/// reviewers ("there is no task statement").
6779fn prepare_instruction(
6780    starter: &Starter,
6781    old_instruction: Option<&str>,
6782    task: &Task,
6783) -> Option<String> {
6784    match starter {
6785        Starter::Start => Some(instruction_for(task)),
6786        Starter::Resume(_) => Some(resumed_instruction(
6787            old_instruction.expect("a resumed run always has a prior instruction"),
6788            task,
6789        )),
6790        Starter::Review(_) => None,
6791    }
6792}
6793
6794/// Persist a transition. A queue write failure is logged rather than fatal: the
6795/// run already happened, and taking the daemon down would only add a lost
6796/// backlog to a full disk.
6797fn record(queue: &Queue, task: &mut Task) {
6798    if let Err(e) = queue.put(task) {
6799        tracing::error!("could not record task {}: {e:#}", task.short());
6800        let notice = Notice::error(
6801            "loop:record",
6802            format!(
6803                "Task {} state could not be saved: {}. Check the disk.",
6804                task.id,
6805                e.to_string().lines().next().unwrap_or("unknown save error")
6806            ),
6807        )
6808        .link(Link::Task {
6809            id: task.id.clone(),
6810        });
6811        // The queue lives at `<home>/queue`, so its parent is the home.
6812        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6813            Some(home) => notices::raise_in(home, notice),
6814            None => notices::raise(notice),
6815        }
6816    }
6817}
6818
6819/// Every runnable task, in the order the loop should try them.
6820///
6821/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6822/// tail exists so that a claim somebody else holds costs the loop the next
6823/// candidate rather than a whole poll interval of idleness.
6824fn runnable(queue: &Queue) -> Vec<Task> {
6825    let mut tasks: Vec<Task> = queue
6826        .list()
6827        .into_iter()
6828        .filter(|t| t.status.runnable())
6829        .collect();
6830    tasks.sort_unstable_by(crate::queue::dispatch_order);
6831    tasks
6832}
6833
6834/// Why a run ended where it did, in one line, for [`Task::last_error`].
6835///
6836/// A stalled run names the seats the quota took out: "out of quota" is not
6837/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6838/// agent to replace or which plan to top up.
6839///
6840/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6841/// purpose: unlike `label`'s other callers (an internal log line, an
6842/// already-a-bug fallback message), this string becomes `Task::last_error`
6843/// verbatim, which the phone renders in the same alarm-styled box an
6844/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6845/// `.err` styling. A bare `verified_noop` there would read exactly like the
6846/// failure this whole feature exists to tell apart from one.
6847fn describe(state: &RunState) -> String {
6848    let p = phrases(&state.config.graph.language);
6849    let mut detail = if state.status == RunStatus::Stalled {
6850        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6851        seats.sort_unstable();
6852        seats.dedup();
6853        if seats.is_empty() {
6854            p.quorum_lost.to_owned()
6855        } else {
6856            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6857        }
6858    } else {
6859        format!("{}{}", p.run_ended, state.status.display_label())
6860    };
6861    if let Some(cause) = state.verification_blocking_cause() {
6862        detail.push_str(&format!(" ({cause})"));
6863    } else if let Some(last) = state.events.last() {
6864        // The review loop's "never answered" stop is the one event worth
6865        // translating; it is recognised from structured state, not by
6866        // matching the English event text (which stays as recorded).
6867        let unanswered = state
6868            .reviews
6869            .last()
6870            .filter(|r| {
6871                state.status == RunStatus::Blocked
6872                    && last.node == "review"
6873                    && r.incomplete()
6874                    && r.blocking == 0
6875                    && r.round == state.config.graph.review_rounds
6876                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6877            })
6878            .map(|r| (r.expected - r.answered, r.round));
6879        match unanswered {
6880            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6881                detail.push_str(&format!(
6882                    " ({}: {})",
6883                    last.node,
6884                    (p.reviewers_never_answered)(missing, rounds)
6885                ));
6886            }
6887            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6888        }
6889    }
6890    detail.push_str(&format!(" [run {}]", state.id));
6891    detail
6892}
6893
6894/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6895///
6896/// The task file lives in the backlog indefinitely; a diagnostic is an
6897/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6898/// stay small regardless of how much a gate command or a candidate printed.
6899const DIAGNOSTIC_MAX: usize = 4_000;
6900
6901/// Tail kept from a single failing command's output inside a diagnostic.
6902/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6903/// pointer for a human deciding whether to go read the full artifact by hand,
6904/// not a replacement for reading it.
6905const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6906
6907/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6908/// `magi task show` says more than the one-line reason in [`describe`].
6909///
6910/// The one-liner answers "where did the run stop"; this answers "what would a
6911/// human have found opening `artifacts/` by hand" — the point of the whole
6912/// feature is the case that one-liner actively misleads on: a run held as "no
6913/// candidate produced a change" can mean the implementer actually finished
6914/// the task (opened a PR, merged it, tagged a release) and only left a clean
6915/// local worktree behind, which reads as "nothing happened" unless someone
6916/// goes and reads what the agent actually said. `None` when the run carries
6917/// none of the three shapes this recognises — an ordinary run held for
6918/// something not diagnosable from `RunState` alone still explains itself
6919/// through `Task::last_error`.
6920fn diagnostic(state: &RunState) -> Option<String> {
6921    let mut parts: Vec<String> = Vec::new();
6922
6923    // Gate failure: which check(s), and the tail of what each printed.
6924    for o in state.gate.iter().filter(|o| !o.ok()) {
6925        parts.push(format!(
6926            "gate `{}` failed ({}):\n{}",
6927            o.command,
6928            notices::exit_status(o.code),
6929            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6930        ));
6931    }
6932
6933    // The land loop gave up because the fixer declined while checks were
6934    // still red: the message already names them (see `land::run`).
6935    if let Some(last) = state
6936        .events
6937        .iter()
6938        .rev()
6939        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6940    {
6941        parts.push(last.message.clone());
6942    }
6943
6944    // No viable candidate: every implementer's own final word, sanitized the
6945    // same way a judge would have read it, so a run that actually finished
6946    // the job does not read as an unexplained failure. A verified no-op is
6947    // called out ahead of its own summary and apart from an ordinary
6948    // failure's `why` — this is the one candidate shape whose diagnostic a
6949    // human is expected to actually judge, not just skim.
6950    if state.viable().is_empty() {
6951        for c in &state.candidates {
6952            if let Some(evidence) = &c.verified_noop {
6953                parts.push(format!(
6954                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6955                    c.label
6956                ));
6957            } else if !c.summary.trim().is_empty() {
6958                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6959            } else if let Some(why) = &c.failed {
6960                parts.push(format!("candidate {}: {why}", c.label));
6961            }
6962        }
6963    }
6964
6965    if parts.is_empty() {
6966        return None;
6967    }
6968    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6969    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6970    // back slightly over. Leave it enough room to always land under the
6971    // limit.
6972    Some(crate::run::tail(
6973        &parts.join("\n\n"),
6974        DIAGNOSTIC_MAX.saturating_sub(100),
6975    ))
6976}
6977
6978/// Stable lower-case name for a run status, for an internal log line and the
6979/// "graph stopped without reaching a terminal status" bug message in
6980/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6981/// doc for why that one reads [`RunStatus::display_label`] instead. One
6982/// definition of a status's name, on the type that owns it: this table used
6983/// to live here as a second copy, and a status renamed in one place would
6984/// have gone on reading correctly in the other.
6985fn label(status: RunStatus) -> &'static str {
6986    status.as_str()
6987}
6988
6989/// Parse a merge mode override.
6990pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6991    match mode {
6992        "none" => Ok(MergeMode::None),
6993        "local" => Ok(MergeMode::Local),
6994        "pr" => Ok(MergeMode::Pr),
6995        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6996    }
6997}
6998
6999/// Take the status lock, recovering from a poisoned one.
7000///
7001/// A panic elsewhere must not silently stop the heartbeat: the status is plain
7002/// data, and the worst a poisoned lock can hold is a stale timestamp.
7003fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
7004    mutex
7005        .lock()
7006        .unwrap_or_else(std::sync::PoisonError::into_inner)
7007}
7008
7009#[cfg(test)]
7010mod tests {
7011    use super::*;
7012    use crate::queue::{Source, TaskStatus};
7013    use crate::run::{Candidate, CommandOutcome};
7014    use pretty_assertions::assert_eq;
7015
7016    fn task() -> Task {
7017        Task::new(
7018            "add retries".to_owned(),
7019            "add retries".to_owned(),
7020            PathBuf::from("/repo"),
7021            Source::Human,
7022        )
7023    }
7024
7025    #[test]
7026    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
7027        let skips = DispatchSkips::from([
7028            ("a".into(), SkipReason::CoolingDown),
7029            ("b".into(), SkipReason::WaitingOnLanding),
7030            ("c".into(), SkipReason::WaitingOnLanding),
7031            ("d".into(), SkipReason::OrdinaryCapacity),
7032        ]);
7033        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
7034        assert_eq!(wait.runnable, 4);
7035        assert_eq!(
7036            wait.reasons
7037                .iter()
7038                .map(|r| (r.reason.as_str(), r.count))
7039                .collect::<Vec<_>>(),
7040            [
7041                ("waiting_on_landing", 2),
7042                ("cooling_down", 1),
7043                ("ordinary_capacity", 1)
7044            ]
7045        );
7046        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
7047        assert!(
7048            aggregate_dispatch_wait(2, &DispatchSkips::new())
7049                .unwrap()
7050                .reasons
7051                .is_empty()
7052        );
7053    }
7054
7055    #[test]
7056    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
7057        let before = vec!["a".into(), "b".into(), "c".into()];
7058        let allowed = vec![task_with_id("b")];
7059        let skips = interrupt_skips(&before, &allowed);
7060        assert_eq!(
7061            skips,
7062            DispatchSkips::from([
7063                ("a".into(), SkipReason::InterruptGate),
7064                ("c".into(), SkipReason::InterruptGate),
7065            ])
7066        );
7067        let mut previous = DispatchSkips::new();
7068        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7069        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
7070        assert!(!changed_dispatch_skips(&mut previous, skips));
7071        assert!(changed_dispatch_skips(
7072            &mut previous,
7073            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
7074        ));
7075        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7076    }
7077
7078    #[test]
7079    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
7080        let mut value = serde_json::to_value(Status::new()).unwrap();
7081        value.as_object_mut().unwrap().remove("dispatch_wait");
7082        assert!(
7083            serde_json::from_value::<Status>(value.clone())
7084                .unwrap()
7085                .dispatch_wait
7086                .is_none()
7087        );
7088        assert!(
7089            serde_json::from_value::<Reading>(value.clone())
7090                .unwrap()
7091                .dispatch_wait
7092                .is_none()
7093        );
7094        value["dispatch_wait"] = serde_json::json!({
7095            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
7096        });
7097        let reading = serde_json::from_value::<Reading>(value).unwrap();
7098        assert_eq!(
7099            reading.dispatch_wait.unwrap().reasons[0].reason,
7100            "future_reason"
7101        );
7102    }
7103
7104    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
7105        let job = crate::worker::Job {
7106            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
7107            sequence: 1,
7108            kind: "task".into(),
7109            key: format!("task:{}", request.task),
7110            payload: serde_json::to_value(request).unwrap(),
7111            generation: "a".repeat(64),
7112            version: None,
7113            status: crate::worker::Status::Starting,
7114            result: None,
7115            pid: None,
7116            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
7117            finished_at: None,
7118        };
7119        let dir = home.join("workers/jobs").join(&job.id);
7120        std::fs::create_dir_all(&dir).unwrap();
7121        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
7122        job
7123    }
7124
7125    #[test]
7126    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
7127        let home = tempfile::tempdir().unwrap();
7128        let request = TaskWorker {
7129            opts: Opts::default(),
7130            queue: home.path().join("queue"),
7131            task: "startup".into(),
7132            lane: PermitKind::Ordinary,
7133            standalone: false,
7134        };
7135        let job = starting_task_reservation(home.path(), &request);
7136        let error = task_worker_spawn_error(
7137            home.path(),
7138            &request,
7139            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
7140        )
7141        .expect_err("our own reservation must not turn a failed spawn into a resync");
7142        let active = crate::worker::active(home.path()).unwrap();
7143        assert_eq!(active.len(), 1);
7144        assert_eq!(active[0].id, job.id);
7145        assert_eq!(active[0].status, crate::worker::Status::Starting);
7146        assert!(
7147            crate::worker::control(home.path(), &job.key)
7148                .unwrap()
7149                .is_none()
7150        );
7151        let notices = notices::Notices::at(home.path().join("notifications")).list();
7152        assert_eq!(notices.len(), 1);
7153        assert_eq!(notices[0].key, "loop:worker-startup");
7154        assert!(!notices[0].message.contains("private-error-detail"));
7155        assert!(notices[0].message.contains(&request.task));
7156        assert!(
7157            notices[0]
7158                .message
7159                .contains("could not be started or acknowledged")
7160        );
7161        assert!(notices[0].message.contains("worker.log"));
7162        assert_eq!(
7163            notices[0].link,
7164            Some(Link::Task {
7165                id: request.task.clone()
7166            })
7167        );
7168        assert!(format!("{error:#}").contains("private-error-detail"));
7169    }
7170
7171    #[test]
7172    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
7173        let home = tempfile::tempdir().unwrap();
7174        let mut request = TaskWorker {
7175            opts: Opts::default(),
7176            queue: home.path().join("queue"),
7177            task: "handoff".into(),
7178            lane: PermitKind::Ordinary,
7179            standalone: true,
7180        };
7181        let job = starting_task_reservation(home.path(), &request);
7182        request.standalone = false;
7183        task_worker_spawn_error(
7184            home.path(),
7185            &request,
7186            anyhow::anyhow!("operation key is already reserved for a different request"),
7187        )
7188        .expect("a different standalone request is the handoff race, not our startup failure");
7189        let active = crate::worker::active(home.path()).unwrap();
7190        assert_eq!(active.len(), 1);
7191        assert_eq!(active[0].id, job.id);
7192        assert_eq!(active[0].payload, job.payload);
7193        assert!(
7194            notices::Notices::at(home.path().join("notifications"))
7195                .list()
7196                .is_empty()
7197        );
7198    }
7199
7200    #[test]
7201    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
7202        let home = tempfile::tempdir().unwrap();
7203        let queue = Queue::at(home.path().join("queue"));
7204        let mut task = task();
7205        task.runs = vec!["previous".into()];
7206        queue.put(&mut task).unwrap();
7207        let request = TaskWorker {
7208            opts: Opts::default(),
7209            queue: home.path().join("queue"),
7210            task: task.id.clone(),
7211            lane: PermitKind::Ordinary,
7212            standalone: false,
7213        };
7214        let job = starting_task_reservation(home.path(), &request);
7215        let claims = current_work(home.path(), Timestamp::now());
7216        assert_eq!(claims.len(), 1);
7217        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
7218        assert_eq!(claims[0].run, "previous");
7219        assert!(other_claims_run(&claims, "previous", None));
7220        // Only after confirming the executing caller may admission ignore
7221        // this exact projection. Cleanup continues to observe it as live.
7222        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
7223        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
7224    }
7225
7226    #[test]
7227    fn admission_excludes_only_the_callers_exact_reservation() {
7228        let own = Current {
7229            worker: Some("own".into()),
7230            task: "same-task".into(),
7231            run: "previous".into(),
7232        };
7233        assert!(!other_claims_run(
7234            std::slice::from_ref(&own),
7235            "previous",
7236            Some("own")
7237        ));
7238        assert!(other_claims_run(
7239            std::slice::from_ref(&own),
7240            "previous",
7241            None
7242        ));
7243        for worker in [None, Some("other".into())] {
7244            let other = Current {
7245                worker,
7246                ..own.clone()
7247            };
7248            assert!(other_claims_run(
7249                &[own.clone(), other],
7250                "previous",
7251                Some("own")
7252            ));
7253        }
7254        let legacy: Current =
7255            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
7256        assert!(other_claims_run(&[legacy], "previous", Some("own")));
7257    }
7258
7259    #[test]
7260    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
7261        let mut task = task();
7262        let mut run = run_state(RunStatus::Reviewing);
7263        run.task_instruction = Some(task.instruction.clone());
7264        run.reviewed_commits = Some(vec!["committed-fix".into()]);
7265        let branch = "magi/test/B";
7266        run.candidates.push(crate::run::Candidate {
7267            branch: branch.into(),
7268            ..candidate('B', "preserved work", false, None)
7269        });
7270        task.runs = vec![run.id.clone()];
7271        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
7272        assert_eq!(
7273            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7274            Starter::Resume(run.id.clone())
7275        );
7276        assert!(matches!(
7277            review_retry_starter(
7278                &task,
7279                Some(&run),
7280                Some("different"),
7281                true,
7282                unfinished.as_deref()
7283            ),
7284            Starter::Review(_)
7285        ));
7286        assert_eq!(
7287            review_retry_starter(
7288                &task,
7289                Some(&run),
7290                Some(branch),
7291                false,
7292                unfinished.as_deref()
7293            ),
7294            Starter::Start
7295        );
7296        task.instruction.push_str(" changed criteria");
7297        assert!(matches!(
7298            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7299            Starter::Review(_)
7300        ));
7301        assert!(matches!(
7302            review_retry_starter(&task, Some(&run), Some(branch), true, None),
7303            Starter::Review(_)
7304        ));
7305    }
7306
7307    #[test]
7308    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
7309        let dir = tempfile::tempdir().unwrap();
7310        let queue = Queue::at(dir.path().join("queue"));
7311        let mut task = task();
7312        task.status = TaskStatus::Running;
7313        task.attempts = 1;
7314        queue.put(&mut task).unwrap();
7315        let live = std::collections::BTreeSet::from([task.id.clone()]);
7316        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
7317        drop(queue.claim(&task.id).unwrap());
7318        let saved = queue.get(&task.id).unwrap();
7319        assert_eq!(saved.status, TaskStatus::Running);
7320        assert_eq!(saved.attempts, 1);
7321        assert!(saved.last_error.is_none());
7322    }
7323
7324    #[test]
7325    fn standalone_workers_do_not_consume_scheduler_lanes() {
7326        let request = |task: &str, lane, standalone| TaskWorker {
7327            opts: Opts::default(),
7328            queue: PathBuf::from("/queue"),
7329            task: task.to_owned(),
7330            lane,
7331            standalone,
7332        };
7333        let mut jobs = vec![
7334            request("ordinary", PermitKind::Ordinary, false),
7335            request("standalone-urgent", PermitKind::Urgent, true),
7336            request("standalone-ordinary", PermitKind::Ordinary, true),
7337            request("decision", PermitKind::None, false),
7338        ];
7339        assert_eq!(available_slots(&jobs, 2), (1, 1));
7340        jobs.push(request("urgent", PermitKind::Urgent, false));
7341        assert_eq!(available_slots(&jobs, 2), (1, 0));
7342        assert_eq!(available_slots(&jobs, 0), (0, 0));
7343    }
7344
7345    #[test]
7346    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
7347        let now = Timestamp::now();
7348        let mut reading = Reading {
7349            pid: Some(std::process::id()),
7350            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
7351            ..Reading::default()
7352        };
7353        assert!(!reading.running(now));
7354        assert!(legacy_scheduler_running(&reading, now, 0));
7355        reading.worker_protocol = Some(1);
7356        assert!(!legacy_scheduler_running(&reading, now, 0));
7357    }
7358
7359    #[test]
7360    fn selected_public_head_overrides_historical_resume_and_pin() {
7361        let mut t = task();
7362        let mut old = run_state(RunStatus::Blocked);
7363        let selection = crate::pr_recovery::Selection {
7364            url: "url".into(),
7365            branch: format!("magi/task-{}", t.id),
7366            head: "a".repeat(40),
7367            source_head: None,
7368            source_run: None,
7369            source_proof: None,
7370            disposition: Some(crate::pr_recovery::Disposition::Review),
7371            instruction: t.instruction.clone(),
7372            approved_at: Timestamp::now(),
7373        };
7374        t.resume_override = Some(crate::queue::OperatorResume {
7375            pinned_run: Some(old.id.clone()),
7376            question_id: "choice".into(),
7377            at: Timestamp::now(),
7378            conductor_rehold: None,
7379            forced: false,
7380        });
7381        assert_eq!(
7382            selected_starter(&selection, Some(&old), Some(&old.id)),
7383            Starter::Review(selection.branch.clone())
7384        );
7385        old.pr_recovery = Some(selection.clone());
7386        assert_eq!(
7387            selected_starter(&selection, Some(&old), Some(&old.id)),
7388            Starter::Review(selection.branch.clone())
7389        );
7390        old.reviewed_commits = Some(vec!["implementation".into()]);
7391        assert_eq!(
7392            selected_starter(&selection, Some(&old), Some(&old.id)),
7393            Starter::Resume(old.id.clone())
7394        );
7395        let mut changed = selection.clone();
7396        changed.head = "b".repeat(40);
7397        assert_eq!(
7398            selected_starter(&changed, Some(&old), Some(&old.id)),
7399            Starter::Review(changed.branch)
7400        );
7401    }
7402
7403    #[test]
7404    fn candidate_transplant_failure_is_one_actionable_hold() {
7405        let dir = tempfile::tempdir().unwrap();
7406        let q = Queue::at(dir.path().join("queue"));
7407        let mut t = task();
7408        let mut state = run_state(RunStatus::Blocked);
7409        state.event("prep", "cannot apply referenced commit: conflict");
7410        state.prep_failure = Some("conflict".into());
7411        t.start(state.id.clone());
7412        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
7413        assert_eq!(t.attempts, 1);
7414        assert_eq!(t.status, TaskStatus::Held);
7415        assert!(t.operator_held());
7416        assert!(!t.status.runnable());
7417        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
7418        let first = t.chat_notice_key().unwrap();
7419        t.chat_notices.push(first.clone());
7420        t.release_operator("test", None);
7421        state.id = "another-unprepared-run".into();
7422        t.start(state.id.clone());
7423        finish_attempt(
7424            3,
7425            &q,
7426            &mut t,
7427            &state,
7428            &[],
7429            Err(anyhow::anyhow!("still conflicts")),
7430        );
7431        assert_eq!(
7432            t.chat_notice_key().as_ref(),
7433            Some(&first),
7434            "no work happened"
7435        );
7436        t.release_operator("test", None);
7437        state.prep_failure = None;
7438        state.status = RunStatus::Failed;
7439        state.begin_pass();
7440        t.start(state.id.clone());
7441        finish_attempt(
7442            1,
7443            &q,
7444            &mut t,
7445            &state,
7446            &[],
7447            Err(anyhow::anyhow!("new gate failure")),
7448        );
7449        let failure = t.chat_notice_key().unwrap();
7450        assert_ne!(failure, first, "approved recovery reached a real failure");
7451        t.release_operator("test", None);
7452        state.begin_pass();
7453        t.start(state.id.clone());
7454        finish_attempt(
7455            1,
7456            &q,
7457            &mut t,
7458            &state,
7459            &[],
7460            Err(anyhow::anyhow!("new failure on resume")),
7461        );
7462        assert_ne!(
7463            t.chat_notice_key().as_ref(),
7464            Some(&failure),
7465            "a new settled pass"
7466        );
7467    }
7468
7469    #[test]
7470    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7471        for source in ["cli", "web"] {
7472            let mut t = task();
7473            let mut run = run_state(RunStatus::Blocked);
7474            run.instruction = "Run A original criteria".into();
7475            run.task_instruction = Some(run.instruction.clone());
7476            t.start(run.id.clone());
7477            t.release_operator("choice", Some("resume-question"));
7478            t.resume_override = Some(crate::queue::OperatorResume {
7479                question_id: "resume-question".into(),
7480                at: Timestamp::now(),
7481                conductor_rehold: None,
7482                forced: true,
7483                pinned_run: Some(run.id.clone()),
7484            });
7485            t.hold_machine(Some("not enough free space to start a run".into()));
7486            let mut unchanged = t.clone();
7487            unchanged
7488                .edit("title changed".into(), unchanged.instruction.clone())
7489                .unwrap();
7490            unchanged.release_operator(source, None);
7491            assert_eq!(
7492                unchanged
7493                    .resume_override
7494                    .as_ref()
7495                    .unwrap()
7496                    .pinned_run
7497                    .as_deref(),
7498                Some(run.id.as_str())
7499            );
7500            assert!(!compatible_run_instruction(&run, &unchanged));
7501            assert!(may_resume_run(&run, &unchanged));
7502
7503            t.edit(
7504                "approved recovery".into(),
7505                "Reuse measured PR head B; fix Clippy; review".into(),
7506            )
7507            .unwrap();
7508            assert!(t.resume_override.is_none());
7509            t.release_operator(source, None);
7510            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7511            assert!(reloaded.resume_override.is_none());
7512            assert!(!may_resume_run(&run, &reloaded));
7513            let unfinished =
7514                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7515                    .filter(|_| may_resume_run(&run, &reloaded));
7516            assert_eq!(
7517                choose_starter(None, false, unfinished.as_deref()),
7518                Starter::Start
7519            );
7520            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7521            assert_eq!(
7522                reloaded.resumption_history[0].question_id.as_deref(),
7523                Some("resume-question")
7524            );
7525
7526            // A revision already persisted with the old approval/pin is also
7527            // invalidated when the new operator release is recorded.
7528            unchanged.instruction = "Reuse measured PR head B".into();
7529            unchanged.hold_machine(Some("disk hold".into()));
7530            unchanged.release_operator(source, None);
7531            assert!(unchanged.resume_override.is_none());
7532            assert!(!may_resume_run(&run, &unchanged));
7533        }
7534    }
7535
7536    #[test]
7537    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7538        let mut t = task();
7539        let mut run = run_state(RunStatus::Blocked);
7540        t.review_of = Some("approved-head".into());
7541        t.instruction =
7542            "Review the branch `approved-head` (review-only: no implementation, no judging)."
7543                .into();
7544        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();
7545        run.reviewed_commits = Some(vec!["Commit log".into()]);
7546        t.start(run.id.clone());
7547        t.hold_machine(Some("interrupted review".into()));
7548        t.release_operator("cli", None);
7549        assert!(
7550            compatible_run_instruction(&run, &t),
7551            "legacy explicit review remains resumable"
7552        );
7553        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7554            .filter(|_| compatible_run_instruction(&run, &t));
7555        assert_eq!(
7556            choose_starter(None, false, unfinished.as_deref()),
7557            Starter::Resume(run.id.clone())
7558        );
7559        run.task_instruction = Some(t.instruction.clone());
7560        assert!(compatible_run_instruction(&run, &t));
7561        let reloaded: RunState =
7562            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7563        assert!(compatible_run_instruction(&reloaded, &t));
7564        t.edit(
7565            "new approved head".into(),
7566            "Reuse measured PR head B".into(),
7567        )
7568        .unwrap();
7569        assert!(!compatible_run_instruction(&run, &t));
7570
7571        // Legacy recovery reviews retain the task criteria ahead of the log.
7572        t.review_of = None;
7573        t.instruction = "Fix Clippy on approved head".into();
7574        run.task_instruction = None;
7575        run.instruction = format!(
7576            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7577            t.instruction
7578        );
7579        assert!(compatible_run_instruction(&run, &t));
7580        t.instruction.push('\n');
7581        assert!(
7582            compatible_run_instruction(&run, &t),
7583            "legacy generated review trimmed the original criteria"
7584        );
7585        t.hold_for_handover(Some("approved-head".into()), "refused".into());
7586        assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
7587        t.edit("new plan".into(), "Reuse measured PR head B".into())
7588            .unwrap();
7589        assert!(review_branch_for(&t, Some(&run)).is_none());
7590        assert!(!compatible_run_instruction(&run, &t));
7591        t.review_branch = Some("approved-head".into());
7592        t.review_instruction = None;
7593        assert!(
7594            review_branch_for(&t, Some(&run)).is_none(),
7595            "legacy retained candidate cannot replace a revised approved head"
7596        );
7597    }
7598
7599    #[test]
7600    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7601        let home = crate::run::test_home();
7602        crate::run::pin_test_home();
7603        let dir = tempfile::tempdir().unwrap();
7604        let queue = Queue::at(dir.path().join("queue"));
7605        for resume in [true, false] {
7606            let state = run_state(RunStatus::Blocked);
7607            let mut t = task();
7608            t.start(state.id.clone());
7609            let action = if resume {
7610                ask::ChoiceAction::Resume {
7611                    run: state.id.clone(),
7612                }
7613            } else {
7614                ask::ChoiceAction::Requeue
7615            };
7616            let mut q = action_question(&state.id, action);
7617            q.status = ask::QuestionStatus::Open;
7618            q.answer = None;
7619            q.answered_at = None;
7620            t.fail("run stopped with a question", 3);
7621            hold_if_runnable(&queue, &mut t);
7622            assert!(t.operator_decided_at.is_none());
7623            assert!(t.operator_held());
7624            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7625            let expected = if resume {
7626                ActionDecision::Resume(state.id.clone())
7627            } else {
7628                ActionDecision::Requeue
7629            };
7630            assert_eq!(
7631                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7632                expected
7633            );
7634            t.hold_manual(Some("later explicit hold".into()));
7635            assert_eq!(
7636                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7637                ActionDecision::Stale
7638            );
7639        }
7640    }
7641
7642    #[test]
7643    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7644        let mut t = task();
7645        t.answers.push(crate::queue::AnsweredQuestion {
7646            question: "Inspect the remote?".into(),
7647            answer: "Inspect then wait".into(),
7648        });
7649        let old = instruction_for(&t);
7650        assert!(compatible_instruction(&old, &t));
7651        t.instruction = "Reuse approved PR head and review".into();
7652        t.release_operator("cli", None);
7653        assert!(!compatible_instruction(&old, &t));
7654        let approved = instruction_for(&t);
7655        assert!(approved.contains("waiting premises are superseded"));
7656        assert!(compatible_instruction(&approved, &t));
7657        assert_eq!(resumed_instruction(&approved, &t), approved);
7658        t.release_operator("web", None);
7659        assert!(compatible_instruction(&approved, &t));
7660        assert_eq!(t.resumption_history.len(), 1);
7661        t.start("run".into());
7662        assert!(instruction_for(&t).contains("Explicit operator resumption"));
7663    }
7664
7665    /// A run that stopped on an infrastructure wait asked no agent anything:
7666    /// the task is held by the machine under a `[resource]` reason (resumable,
7667    /// re-checked by triage), and the attempt it started is given back.
7668    #[test]
7669    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7670        let mut state = RunState::new(
7671            PathBuf::from("/repo"),
7672            "main".into(),
7673            "base".into(),
7674            "task".into(),
7675            Config::default(),
7676        );
7677        state.status = RunStatus::Landing;
7678        state.parked = true;
7679        state.pr_pushed_head = Some("head".into());
7680        state.land_unrelated = Some(
7681            serde_json::from_value(serde_json::json!({
7682                "head": "head", "question": "ci-question",
7683                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7684            }))
7685            .unwrap(),
7686        );
7687        let mut t = task();
7688        t.start(state.id.clone());
7689        let verdict = Verdict {
7690            status: RunStatus::Landing,
7691            left_pr: true,
7692            quota_hit: false,
7693            parked: true,
7694            no_viable_candidates: false,
7695        };
7696        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7697        assert_eq!(t.attempts, 0);
7698        assert_eq!(t.status, TaskStatus::Held);
7699        assert!(!t.operator_held());
7700        assert!(
7701            t.hold_reason
7702                .as_deref()
7703                .unwrap()
7704                .starts_with("[ci-unrelated]")
7705        );
7706        // A second settlement must not refund an earlier task attempt.
7707        t.attempts = 1;
7708        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7709        assert_eq!(t.attempts, 1);
7710        assert_eq!(t.passes.len(), 1);
7711        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7712        state.pr_pushed_head = Some("new-head".into());
7713        state.parked = false;
7714        state.status = RunStatus::Blocked;
7715        let stale = Verdict {
7716            status: RunStatus::Blocked,
7717            parked: false,
7718            ..verdict
7719        };
7720        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7721        assert_eq!(t.attempts, 1);
7722        // A new execution pass can refund its own newly charged attempt.
7723        state.begin_pass();
7724        state.begin_pass();
7725        state.status = RunStatus::Landing;
7726        state.parked = true;
7727        state.pr_pushed_head = Some("head".into());
7728        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7729        assert_eq!(t.attempts, 0);
7730        assert_eq!(t.passes.len(), 2);
7731    }
7732
7733    #[test]
7734    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7735        let mut state = run_state(RunStatus::Failed);
7736        state
7737            .quota
7738            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7739        state.begin_pass();
7740        let mut t = task();
7741        t.start(state.id.clone());
7742        reclaim(&mut t, Some(state), 2, "en");
7743        assert_eq!(t.attempts, 1);
7744    }
7745
7746    #[test]
7747    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7748        let mut state = run_state(RunStatus::Blocked);
7749        let losses: Vec<_> = ["alpha", "beta"]
7750            .into_iter()
7751            .enumerate()
7752            .map(|(i, agent)| {
7753                QuotaLoss::from_report(
7754                    format!("advisor-{i}"),
7755                    "advise",
7756                    Some(&crate::agent::Quota {
7757                        cause: crate::agent::QuotaCause::Authentication,
7758                        agent: agent.to_owned(),
7759                        reset: None,
7760                    }),
7761                )
7762            })
7763            .collect();
7764        crate::graph::block_machine_outage(&mut state, "advise", &losses);
7765        state.quota = losses;
7766        let mut t = task();
7767        t.start(state.id.clone());
7768        let verdict = Verdict {
7769            status: state.status,
7770            left_pr: false,
7771            quota_hit: true,
7772            parked: false,
7773            no_viable_candidates: true,
7774        };
7775        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7776        assert_eq!(t.attempts, 0);
7777        assert_eq!(t.status, TaskStatus::Held);
7778        assert!(!t.operator_held());
7779        let reason = t.hold_reason.as_deref().unwrap();
7780        assert!(reason.starts_with("[authentication]"));
7781        assert!(
7782            reason.contains("alpha")
7783                && reason.contains("beta")
7784                && reason.contains("re-authenticate")
7785        );
7786        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7787        // Orphan recovery uses the same settlement and cannot spend an attempt.
7788        let mut orphan = task();
7789        orphan.start(state.id.clone());
7790        reclaim(&mut orphan, Some(state), 2, "en");
7791        assert_eq!(orphan.attempts, 0);
7792        assert_eq!(orphan.status, TaskStatus::Held);
7793    }
7794
7795    #[test]
7796    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7797        let mut state = RunState::new(
7798            PathBuf::from("/repo"),
7799            "main".to_owned(),
7800            "abc1234".to_owned(),
7801            "task".to_owned(),
7802            Config::default(),
7803        );
7804        state.status = RunStatus::Blocked;
7805        state.resource_block = Some(crate::run::ResourceBlock {
7806            cause: crate::run::ResourceBlockCause::Other,
7807            node: "graft".to_owned(),
7808            kind: "shared build cache".to_owned(),
7809            detail: "timed out".to_owned(),
7810            at: jiff::Timestamp::now(),
7811        });
7812        let mut t = task();
7813        t.start("20260902-000000-aaaa".to_owned());
7814        assert_eq!(t.attempts, 1);
7815        let verdict = Verdict {
7816            status: RunStatus::Blocked,
7817            left_pr: false,
7818            quota_hit: false,
7819            parked: false,
7820            no_viable_candidates: false,
7821        };
7822        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7823        assert_eq!(t.status, TaskStatus::Held);
7824        assert_eq!(t.attempts, 0, "the attempt is refunded");
7825        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7826        assert!(
7827            !t.operator_held(),
7828            "a machine hold, released without a human"
7829        );
7830
7831        let mut selected = task();
7832        selected.start("20260902-000000-cccc".into());
7833        selected.replacement = Some(crate::merge_decision::Replacement {
7834            question: "fixture".into(),
7835            run: "earlier".into(),
7836            pr: "https://example.invalid/pr/1".into(),
7837            agent: "selected".into(),
7838            context: "fixture".into(),
7839        });
7840        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7841        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7842        assert_eq!(selected.attempts, 0);
7843        assert!(
7844            !selected.operator_held(),
7845            "a selected agent also retains a machine resource hold"
7846        );
7847        assert!(
7848            selected
7849                .hold_reason
7850                .as_deref()
7851                .unwrap()
7852                .starts_with("[resource] ")
7853        );
7854
7855        // A park request outranks it: still the operator's doing.
7856        let mut p = task();
7857        p.start("20260902-000000-bbbb".to_owned());
7858        settle_and_diagnose(
7859            &mut p,
7860            Verdict {
7861                parked: true,
7862                ..verdict
7863            },
7864            "parked",
7865            2,
7866            &state,
7867        );
7868        assert_eq!(p.status, TaskStatus::Parked);
7869        assert_eq!(
7870            p.attempts, 0,
7871            "parking refunds once rather than also settling the resource hold"
7872        );
7873    }
7874
7875    #[test]
7876    fn record_failure_notice_links_the_task() {
7877        let dir = tempfile::tempdir().unwrap();
7878        // A regular file where the queue directory should be makes every
7879        // `put` fail, on every platform and whoever runs the test.
7880        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7881        let queue = Queue::at(dir.path().join("queue"));
7882        let mut t = interrupt_task("rec-fail-1");
7883        record(&queue, &mut t);
7884
7885        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7886        assert_eq!(found.len(), 1);
7887        assert_eq!(found[0].key, "loop:record");
7888        assert_eq!(
7889            found[0].link,
7890            Some(Link::Task {
7891                id: "rec-fail-1".to_owned()
7892            })
7893        );
7894    }
7895
7896    /// A runnable task marked to interrupt, with an id fixed for assertions
7897    /// rather than the random one [`Task::new`] mints.
7898    fn interrupt_task(id: &str) -> Task {
7899        let mut t = task();
7900        t.id = id.to_owned();
7901        t.interrupt = true;
7902        t
7903    }
7904
7905    /// An ordinary runnable task with an id fixed for assertions.
7906    fn task_with_id(id: &str) -> Task {
7907        let mut t = task();
7908        t.id = id.to_owned();
7909        t
7910    }
7911
7912    /// A runnable task marked `--urgent`, with an id fixed for assertions.
7913    fn urgent_task(id: &str) -> Task {
7914        let mut t = task();
7915        t.id = id.to_owned();
7916        t.urgent = true;
7917        t
7918    }
7919
7920    #[test]
7921    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7922        let dir = tempfile::tempdir().unwrap();
7923        let queue = Queue::at(dir.path().join("queue"));
7924        let mut parked = task_with_id("parked");
7925        parked.start("run".into());
7926        parked.park("upgrade");
7927        parked.record_pass_at(
7928            "run",
7929            0,
7930            Some(Timestamp::now()),
7931            1,
7932            Some(crate::run::ParkCause::Upgrade {
7933                from: "old".into(),
7934                to: None,
7935            }),
7936        );
7937        let mut fresh = task_with_id("fresh");
7938        fresh.priority = 100;
7939        let mut urgent_task = urgent_task("urgent");
7940        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7941            queue.put(t).unwrap();
7942        }
7943        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7944        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7945        let candidates = runnable(&queue);
7946        assert_eq!(candidates[0].id, parked.id);
7947        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7948        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
7949        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
7950        drop(first);
7951        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7952        let next = runnable(&queue)
7953            .into_iter()
7954            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
7955            .unwrap();
7956        assert_eq!(next.task.id, fresh.id);
7957        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7958        drop(claimed_elsewhere);
7959        drop(next);
7960        assert!(matches!(
7961            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
7962            Err(SkipReason::CoolingDown)
7963        ));
7964    }
7965
7966    #[test]
7967    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7968        let dir = tempfile::tempdir().unwrap();
7969        let queue = Queue::at(dir.path().join("queue"));
7970        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7971        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7972        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7973        let mut first = task();
7974        queue.put(&mut first).unwrap();
7975        let stale_plain = queue.get(&first.id).unwrap();
7976        first.set_urgent(true).unwrap();
7977        queue.put(&mut first).unwrap();
7978        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7979        let mut second = urgent_task("second");
7980        queue.put(&mut second).unwrap();
7981        assert!(matches!(
7982            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
7983            Err(SkipReason::UrgentCapacity)
7984        ));
7985        drop(queue.claim(&second.id).unwrap());
7986        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7987        drop(dispatched);
7988        let stale_urgent = queue.get(&first.id).unwrap();
7989        first.set_urgent(false).unwrap();
7990        queue.put(&mut first).unwrap();
7991        assert!(matches!(
7992            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
7993            Err(SkipReason::OrdinaryCapacity)
7994        ));
7995        assert_eq!(urgent.available_permits(), 1);
7996        drop(queue.claim(&first.id).unwrap());
7997        drop(occupied);
7998    }
7999
8000    #[test]
8001    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
8002        let dir = tempfile::tempdir().unwrap();
8003        let queue = Queue::at(dir.path().join("queue"));
8004        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8005        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8006        let mut t = task();
8007        queue.put(&mut t).unwrap();
8008        for enabled in [true, false] {
8009            let stale = queue.get(&t.id).unwrap();
8010            t.set_urgent(enabled).unwrap();
8011            queue.put(&mut t).unwrap();
8012            assert_ne!(stale.urgent, enabled);
8013            let DispatchClaim {
8014                task: fresh,
8015                claim,
8016                permit,
8017            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
8018            assert_eq!(fresh.urgent, enabled);
8019            assert_eq!(ordinary.available_permits(), usize::from(enabled));
8020            assert_eq!(urgent.available_permits(), usize::from(!enabled));
8021            assert!(queue.claim(&t.id).is_err());
8022            assert_eq!(fresh.attempts, stale.attempts);
8023            drop((claim, permit));
8024            assert_eq!(ordinary.available_permits(), 1);
8025            assert_eq!(urgent.available_permits(), 1);
8026        }
8027        t.set_urgent(true).unwrap();
8028        queue.put(&mut t).unwrap();
8029        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
8030        assert!(matches!(
8031            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8032            Err(SkipReason::UrgentCapacity)
8033        ));
8034        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
8035        drop(queue.claim(&t.id).unwrap());
8036        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
8037        drop(occupied);
8038        assert!(matches!(
8039            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
8040            Err(SkipReason::CoolingDown)
8041        ));
8042        drop(queue.claim(&t.id).unwrap());
8043        let held = queue.claim(&t.id).unwrap();
8044        assert!(matches!(
8045            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8046            Err(SkipReason::ClaimUnavailable)
8047        ));
8048        drop(held);
8049        t.status = TaskStatus::Held;
8050        queue.put(&mut t).unwrap();
8051        assert!(matches!(
8052            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8053            Err(SkipReason::NoLongerRunnable)
8054        ));
8055        drop(queue.claim(&t.id).unwrap());
8056        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
8057        assert!(matches!(
8058            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8059            Err(SkipReason::RereadFailed)
8060        ));
8061        drop(queue.claim(&t.id).unwrap());
8062        assert_eq!(urgent.available_permits(), 1);
8063    }
8064
8065    /// The land-resume exemption wins outright, whether or not the candidate
8066    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
8067    /// queue behind anything" guarantee cannot be weaker just because the
8068    /// same task was also filed with `--urgent`.
8069    #[test]
8070    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
8071        assert_eq!(permit_kind(true, false), PermitKind::None);
8072        assert_eq!(permit_kind(true, true), PermitKind::None);
8073    }
8074
8075    /// The one property this whole feature exists for: `--urgent` draws from
8076    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
8077    /// ordinary candidate draws from the ordinary pool exactly as before,
8078    /// untouched by the urgent slot's existence.
8079    #[test]
8080    fn permit_kind_separates_urgent_from_ordinary() {
8081        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
8082        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
8083    }
8084
8085    /// The exact wiring `attempt` runs before minting anything: a config's
8086    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
8087    /// Free space is injected rather than asked of the real disk - the point
8088    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
8089    /// is deterministic on every machine this test runs on, never dependent
8090    /// on how full the CI runner's own disk happens to be.
8091    #[test]
8092    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
8093        let cfg = Config::default();
8094        let repo = Path::new("/any/repo/path");
8095
8096        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
8097            .expect("must hold below the threshold");
8098        assert!(reason.contains("1024"), "{reason}");
8099        assert!(
8100            reason.contains(&cfg.disk.min_free_bytes.to_string()),
8101            "{reason}"
8102        );
8103
8104        assert_eq!(
8105            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
8106            None,
8107            "exactly at the floor is open"
8108        );
8109        assert_eq!(
8110            disk_gate_with(
8111                repo,
8112                &cfg,
8113                PathBuf::new,
8114                |_| Ok(cfg.disk.min_free_bytes + 1)
8115            ),
8116            None,
8117            "comfortably above the floor is open"
8118        );
8119    }
8120
8121    #[test]
8122    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
8123        let dir = tempfile::tempdir().unwrap();
8124        let repo = dir.path().join("repo");
8125        let cache = dir.path().join("cache");
8126        let worktrees = dir.path().join("worktrees");
8127        for path in [&repo, &cache, &worktrees] {
8128            std::fs::create_dir(path).unwrap();
8129        }
8130        let mut cfg = Config::default();
8131        cfg.graph.worktree_root = Some(worktrees.clone());
8132        cfg.verify.gate = vec![format!(
8133            "CARGO_TARGET_DIR='{}' cargo build",
8134            cache.display()
8135        )];
8136        for blocked in [&cache, &worktrees] {
8137            for unmeasured in [false, true] {
8138                assert!(
8139                    disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
8140                        if path == blocked {
8141                            if unmeasured {
8142                                Err(anyhow::anyhow!("measurement failed"))
8143                            } else {
8144                                Ok(0)
8145                            }
8146                        } else {
8147                            Ok(u64::MAX)
8148                        }
8149                    })
8150                    .is_some(),
8151                    "a blocked secondary output volume must close admission"
8152                );
8153            }
8154        }
8155        assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
8156    }
8157
8158    #[test]
8159    fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
8160        let dir = tempfile::tempdir().unwrap();
8161        let repo = dir.path().join("repo");
8162        let cache = dir.path().join("cache");
8163        let home_parent = dir.path().join("run-volume");
8164        let home = home_parent.join("new-home");
8165        for path in [&repo, &cache, &home_parent] {
8166            std::fs::create_dir(path).unwrap();
8167        }
8168        let mut cfg = Config::default();
8169        cfg.graph.worktree_root = Some(repo.clone());
8170        cfg.verify.gate = vec![format!(
8171            "CARGO_TARGET_DIR='{}' cargo build",
8172            cache.display()
8173        )];
8174        cfg.verify.build_cache = BuildCache::Isolated;
8175        let denied = |blocked: &Path| {
8176            disk_gate_with(
8177                &repo,
8178                &cfg,
8179                || home.clone(),
8180                |path| Ok(if path == blocked { 0 } else { u64::MAX }),
8181            )
8182            .is_some()
8183        };
8184        assert!(!denied(&cache));
8185        assert!(denied(&home_parent));
8186    }
8187
8188    #[test]
8189    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
8190        let mut cfg = Config::default();
8191        cfg.disk.min_free_bytes = 0;
8192        let repo = Path::new("/any/repo/path");
8193        assert_eq!(
8194            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
8195            None,
8196            "a zero floor never measures at all"
8197        );
8198    }
8199
8200    #[test]
8201    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
8202        let cfg = Config::default();
8203        let repo = Path::new("/any/repo/path");
8204        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
8205            Err(anyhow::anyhow!("no df on this box"))
8206        })
8207        .expect("a measurement failure must close the gate, not open it");
8208        assert!(reason.contains("could not measure"), "{reason}");
8209    }
8210
8211    #[test]
8212    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
8213        let ordinary = task();
8214        let next = advance_interrupt(
8215            Interrupt::Idle,
8216            std::slice::from_ref(&ordinary.id),
8217            std::slice::from_ref(&ordinary),
8218        );
8219        assert_eq!(next, Interrupt::Idle);
8220    }
8221
8222    #[test]
8223    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
8224        // Nothing to interrupt - this is just an ordinary candidate, and the
8225        // loop's normal dispatch will pick it up like any other.
8226        let marked = interrupt_task("marked");
8227        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8228        assert_eq!(next, Interrupt::Idle);
8229    }
8230
8231    #[test]
8232    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
8233        let marked = interrupt_task("marked");
8234        let next = advance_interrupt(
8235            Interrupt::Idle,
8236            &["running".to_owned()],
8237            std::slice::from_ref(&marked),
8238        );
8239        assert_eq!(
8240            next,
8241            Interrupt::Parking {
8242                parked: vec!["running".to_owned()],
8243                interrupt_task: "marked".to_owned(),
8244            }
8245        );
8246    }
8247
8248    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
8249    /// one run can be in flight when a task becomes runnable and marked.
8250    /// Parking all of them would mean `Resuming` later has more than one id
8251    /// to release back to ordinary dispatch, which cannot be made safe
8252    /// against that same setting's own extra concurrency slots letting two
8253    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
8254    /// The simplification the task's own constraints ask for: do not begin
8255    /// a sequence at all until the herd settles back to exactly one.
8256    #[test]
8257    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
8258        let marked = interrupt_task("marked");
8259
8260        let two = advance_interrupt(
8261            Interrupt::Idle,
8262            &["a".to_owned(), "b".to_owned()],
8263            std::slice::from_ref(&marked),
8264        );
8265        assert_eq!(two, Interrupt::Idle);
8266
8267        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8268        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
8269    }
8270
8271    #[test]
8272    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
8273        let state = Interrupt::Parking {
8274            parked: vec!["running".to_owned()],
8275            interrupt_task: "marked".to_owned(),
8276        };
8277        // Still in flight: no change.
8278        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
8279        assert_eq!(still_going, state);
8280
8281        // Left flight, but the interrupt task has not been dispatched yet on
8282        // this tick - stays `Parking` so `interrupt_gate` can let it through,
8283        // as long as it is still runnable.
8284        let stopped_but_not_yet_dispatched =
8285            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
8286        assert_eq!(stopped_but_not_yet_dispatched, state);
8287
8288        // Left flight, and the interrupt task is now in flight itself.
8289        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
8290        assert_eq!(
8291            dispatched,
8292            Interrupt::Running {
8293                parked: vec!["running".to_owned()],
8294                interrupt_task: "marked".to_owned(),
8295            }
8296        );
8297    }
8298
8299    #[test]
8300    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
8301        let state = Interrupt::Running {
8302            parked: vec!["running".to_owned()],
8303            interrupt_task: "marked".to_owned(),
8304        };
8305        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
8306        assert_eq!(still_running, state);
8307
8308        // Whatever it ended as - merged, failed, held - is not this
8309        // function's concern: leaving flight is the only trigger, driven
8310        // straight off the same in-flight list `poll` already reaps. It does
8311        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
8312        // why that would let an unrelated task start ahead of, or alongside,
8313        // the guaranteed resume.
8314        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
8315        assert_eq!(
8316            ended,
8317            Interrupt::Resuming {
8318                parked: vec!["running".to_owned()]
8319            }
8320        );
8321    }
8322
8323    #[test]
8324    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
8325        let state = Interrupt::Resuming {
8326            parked: vec!["running".to_owned()],
8327        };
8328        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
8329        assert_eq!(still_waiting, state);
8330
8331        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
8332        assert_eq!(dispatched, Interrupt::Idle);
8333    }
8334
8335    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
8336    /// or otherwise moved on by an operator with no claim standing in the
8337    /// way - must not wedge the sequence (and so the whole loop's dispatch,
8338    /// via `interrupt_gate`) waiting forever for a dispatch that can never
8339    /// come. The parked run still gets its resume.
8340    #[test]
8341    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
8342    {
8343        let state = Interrupt::Parking {
8344            parked: vec!["running".to_owned()],
8345            interrupt_task: "marked".to_owned(),
8346        };
8347        // `marked` has been held/blocked/deleted since the sequence began:
8348        // it no longer appears in `runnable` at all.
8349        let next = advance_interrupt(state, &[], &[]);
8350        assert_eq!(
8351            next,
8352            Interrupt::Resuming {
8353                parked: vec!["running".to_owned()]
8354            },
8355            "abandoning the interrupt must not abandon the resume it owes"
8356        );
8357    }
8358
8359    /// The same abandonment, one step later: `Resuming` itself must not wait
8360    /// forever for a parked task that has since become unrunnable.
8361    #[test]
8362    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
8363        let state = Interrupt::Resuming {
8364            parked: vec!["running".to_owned()],
8365        };
8366        let next = advance_interrupt(state, &[], &[]);
8367        assert_eq!(
8368            next,
8369            Interrupt::Idle,
8370            "nothing is left to wait for; the loop must not stay wedged"
8371        );
8372    }
8373
8374    #[test]
8375    fn disabled_by_config_the_sequence_can_never_leave_idle() {
8376        let marked = interrupt_task("marked");
8377        let next = advance_interrupt_tick(
8378            false,
8379            Interrupt::Idle,
8380            &["running".to_owned()],
8381            std::slice::from_ref(&marked),
8382        );
8383        assert_eq!(
8384            next,
8385            Interrupt::Idle,
8386            "an unmarked, unconfigured daemon must behave exactly as before"
8387        );
8388    }
8389
8390    #[test]
8391    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
8392        let state = Interrupt::Parking {
8393            parked: vec!["running".to_owned()],
8394            interrupt_task: "marked".to_owned(),
8395        };
8396        let candidates = vec![interrupt_task("marked"), task()];
8397        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8398        assert!(
8399            allowed.is_empty(),
8400            "nothing may dispatch - not even the interrupt task itself - \
8401             until the parked run has actually stopped"
8402        );
8403    }
8404
8405    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
8406    /// grow a special case for it: an urgent candidate that is not the
8407    /// interrupt task withholds exactly like an ordinary one for as long as
8408    /// the parked run it is racing has not actually left flight. A version
8409    /// of this feature once bypassed the gate for urgent candidates, on the
8410    /// theory that a genuinely separate concurrency lane could not collide
8411    /// with 75dd's own; it could, and did - the bypassed task dispatched
8412    /// alongside a run 75dd's own state machine had only *asked* to park,
8413    /// not yet confirmed gone, which is exactly the second run
8414    /// `Interrupt::Parking`'s own doc says must never happen. There is no
8415    /// tick during Parking/Running/Resuming where letting an extra
8416    /// candidate through is safe, urgent or not - the parked run may still
8417    /// be genuinely mid-call.
8418    #[test]
8419    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
8420        for state in [
8421            Interrupt::Parking {
8422                parked: vec!["running".to_owned()],
8423                interrupt_task: "marked".to_owned(),
8424            },
8425            Interrupt::Running {
8426                parked: vec!["running".to_owned()],
8427                interrupt_task: "marked".to_owned(),
8428            },
8429            Interrupt::Resuming {
8430                parked: vec!["running".to_owned()],
8431            },
8432        ] {
8433            let candidates = vec![
8434                interrupt_task("marked"),
8435                urgent_task("hot"),
8436                task_with_id("ordinary"),
8437            ];
8438            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8439            assert!(
8440                !allowed.iter().any(|t| t.id == "hot"),
8441                "an urgent candidate must wait out the same gate as anything \
8442                 else while the run it would run alongside has not actually \
8443                 left flight, for state {state:?}: {allowed:?}"
8444            );
8445        }
8446    }
8447
8448    /// The one case where marking a task `--urgent` and `interrupt` at once
8449    /// is not redundant: once the interrupt sequence's own guaranteed
8450    /// resume/dispatch actually admits the task, it is unaffected by also
8451    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
8452    /// never on the urgent flag.
8453    #[test]
8454    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
8455        let state = Interrupt::Resuming {
8456            parked: vec!["hot".to_owned()],
8457        };
8458        let candidates = vec![urgent_task("hot"), task()];
8459        let allowed = interrupt_gate(&state, &[], candidates);
8460        assert_eq!(
8461            allowed.iter().filter(|t| t.id == "hot").count(),
8462            1,
8463            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
8464        );
8465    }
8466
8467    #[test]
8468    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
8469        let state = Interrupt::Parking {
8470            parked: vec!["running".to_owned()],
8471            interrupt_task: "marked".to_owned(),
8472        };
8473        let other = task();
8474        let candidates = vec![interrupt_task("marked"), other.clone()];
8475        let allowed = interrupt_gate(&state, &[], candidates);
8476        assert_eq!(allowed.len(), 1);
8477        assert_eq!(allowed[0].id, "marked");
8478    }
8479
8480    #[test]
8481    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
8482        let state = Interrupt::Running {
8483            parked: vec!["running".to_owned()],
8484            interrupt_task: "marked".to_owned(),
8485        };
8486        let candidates = vec![task(), task()];
8487        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
8488        assert!(allowed.is_empty());
8489    }
8490
8491    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
8492    /// sequence began (only reachable above the default
8493    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
8494    /// never both in the same tick, which is what "exactly one resume, no
8495    /// simultaneous run" actually requires structurally rather than by
8496    /// coincidence of how many ordinary slots happen to be free.
8497    #[test]
8498    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
8499        let state = Interrupt::Resuming {
8500            parked: vec!["a".to_owned(), "c".to_owned()],
8501        };
8502        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
8503        let allowed = interrupt_gate(&state, &[], candidates);
8504        assert_eq!(
8505            allowed.len(),
8506            1,
8507            "at most one candidate may be offered while resuming: {allowed:?}"
8508        );
8509        assert_eq!(allowed[0].id, "a");
8510    }
8511
8512    #[test]
8513    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
8514        let state = Interrupt::Resuming {
8515            parked: vec!["a".to_owned()],
8516        };
8517        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
8518        assert!(allowed.is_empty());
8519    }
8520
8521    /// The invariant the completion criteria ask for by name: across a whole
8522    /// simulated sequence, there is never a tick where the gate would let
8523    /// through both the parked run's resume and the interrupt task, and
8524    /// exactly one candidate resumes the instant the interrupt task's run
8525    /// ends - never zero, never more than one.
8526    #[test]
8527    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8528        let running = task(); // id: whatever `Task::new` minted
8529        let marked = interrupt_task("marked");
8530
8531        let mut state = Interrupt::Idle;
8532        // Tick 1: `running` is in flight, `marked` becomes runnable.
8533        let in_flight = vec![running.id.clone()];
8534        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8535        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8536        assert!(gated.is_empty(), "still waiting on `running` to park");
8537
8538        // Tick 2: `running` parked and left flight; nothing dispatched yet.
8539        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8540        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8541        assert_eq!(
8542            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8543            vec!["marked"],
8544            "only the interrupt task may be offered to the dispatcher now"
8545        );
8546
8547        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
8548        state = advance_interrupt_tick(
8549            true,
8550            state,
8551            &["marked".to_owned()],
8552            std::slice::from_ref(&running),
8553        );
8554        let gated = interrupt_gate(
8555            &state,
8556            &["marked".to_owned()],
8557            vec![marked.clone(), running.clone()],
8558        );
8559        assert!(
8560            gated.is_empty(),
8561            "the parked run must not be offered back while the interrupt \
8562             task is still running"
8563        );
8564
8565        // Tick 4: `marked`'s run reached a terminal status and left flight.
8566        // A higher-priority ordinary task `other` is also runnable now - it
8567        // must not be let through instead of, or alongside, `running`.
8568        let other = task_with_id("other");
8569        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8570        assert_eq!(
8571            state,
8572            Interrupt::Resuming {
8573                parked: vec![running.id.clone()]
8574            }
8575        );
8576        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8577        assert_eq!(
8578            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8579            vec![running.id.as_str()],
8580            "exactly the parked run resumes - not the unrelated task, even \
8581             though it was offered first"
8582        );
8583
8584        // Tick 5: `running` is now in flight (dispatched from tick 4's
8585        // gate). Only now does the sequence end and ordinary dispatch fully
8586        // resume.
8587        state = advance_interrupt_tick(
8588            true,
8589            state,
8590            std::slice::from_ref(&running.id),
8591            std::slice::from_ref(&other),
8592        );
8593        assert_eq!(state, Interrupt::Idle);
8594        let gated = interrupt_gate(
8595            &state,
8596            std::slice::from_ref(&running.id),
8597            vec![other.clone()],
8598        );
8599        assert_eq!(
8600            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8601            vec![other.id.as_str()],
8602            "ordinary dispatch is unrestricted again"
8603        );
8604    }
8605
8606    #[test]
8607    fn every_run_status_settles_the_task_it_came_from() {
8608        // run status, resulting task status, attempts still standing after one
8609        let table = [
8610            (RunStatus::Merged, TaskStatus::Done, 1),
8611            (RunStatus::Ready, TaskStatus::Done, 1),
8612            (RunStatus::Stalled, TaskStatus::Failed, 0),
8613            (RunStatus::Blocked, TaskStatus::Failed, 1),
8614            (RunStatus::Failed, TaskStatus::Failed, 1),
8615            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8616            (RunStatus::Prep, TaskStatus::Failed, 1),
8617            (RunStatus::Implementing, TaskStatus::Failed, 1),
8618            (RunStatus::Judging, TaskStatus::Failed, 1),
8619            (RunStatus::Deliberating, TaskStatus::Failed, 1),
8620            (RunStatus::Voting, TaskStatus::Failed, 1),
8621            (RunStatus::Reviewing, TaskStatus::Failed, 1),
8622            (RunStatus::Gating, TaskStatus::Failed, 1),
8623        ];
8624        for (run, want, attempts) in table {
8625            let mut t = task();
8626            t.start("20260902-000000-aaaa".to_owned());
8627            settle(
8628                &mut t,
8629                Verdict {
8630                    status: run,
8631                    left_pr: false,
8632                    parked: false,
8633                    quota_hit: matches!(run, RunStatus::Stalled),
8634                    no_viable_candidates: false,
8635                },
8636                "why",
8637                2,
8638            );
8639            assert_eq!(t.status, want, "task status after {}", label(run));
8640            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8641        }
8642    }
8643
8644    #[test]
8645    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8646        let mut stalled = task();
8647        stalled.start("20260902-000000-aaaa".to_owned());
8648        settle(
8649            &mut stalled,
8650            Verdict {
8651                status: RunStatus::Stalled,
8652                left_pr: false,
8653                parked: false,
8654                quota_hit: true,
8655                no_viable_candidates: false,
8656            },
8657            "quota",
8658            1,
8659        );
8660        assert_eq!(stalled.attempts, 0);
8661        assert!(
8662            stalled.status.runnable(),
8663            "a machine problem must leave the task in line"
8664        );
8665
8666        let mut blocked = task();
8667        blocked.start("20260902-000000-aaaa".to_owned());
8668        settle(
8669            &mut blocked,
8670            Verdict {
8671                status: RunStatus::Blocked,
8672                left_pr: false,
8673                parked: false,
8674                quota_hit: false,
8675                no_viable_candidates: false,
8676            },
8677            "findings open",
8678            1,
8679        );
8680        assert_eq!(blocked.attempts, 1);
8681        assert_eq!(
8682            blocked.status,
8683            TaskStatus::Held,
8684            "the last attempt hands the task to a human"
8685        );
8686    }
8687
8688    #[test]
8689    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8690        // Attempts to spare: without the pull request this task would go
8691        // straight back in line and run the whole competition again.
8692        let mut delivered = task();
8693        delivered.start("20260903-080619-01c2".to_owned());
8694        settle(
8695            &mut delivered,
8696            Verdict {
8697                status: RunStatus::Blocked,
8698                left_pr: true,
8699                parked: false,
8700                quota_hit: false,
8701                no_viable_candidates: false,
8702            },
8703            "no check status",
8704            4,
8705        );
8706        assert_eq!(
8707            delivered.status,
8708            TaskStatus::Held,
8709            "a pull request waiting on CI or a person is not a retryable failure"
8710        );
8711        assert!(
8712            !delivered.status.runnable(),
8713            "the loop must not pick this task up again"
8714        );
8715        assert_eq!(
8716            delivered.last_error.as_deref(),
8717            Some("no check status"),
8718            "the operator needs to be told what the gate was waiting for"
8719        );
8720
8721        // The same status without a pull request is a plain failure, and with
8722        // attempts left it is retried.
8723        let mut empty_handed = task();
8724        empty_handed.start("20260903-080619-01c2".to_owned());
8725        settle(
8726            &mut empty_handed,
8727            Verdict {
8728                status: RunStatus::Blocked,
8729                left_pr: false,
8730                parked: false,
8731                quota_hit: false,
8732                no_viable_candidates: false,
8733            },
8734            "findings open",
8735            4,
8736        );
8737        assert_eq!(empty_handed.status, TaskStatus::Failed);
8738        assert!(empty_handed.status.runnable());
8739    }
8740
8741    #[test]
8742    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8743        // Every candidate agreed, with evidence, that nothing belonged in the
8744        // worktree. That is not a confirmed success to close automatically -
8745        // a human still has to check the claim - and it is not an ordinary
8746        // failure either, so this settles exactly like a pull request nobody
8747        // merged yet: `Held`, same as `Blocked` with a PR.
8748        let mut noop = task();
8749        noop.start("20260912-131304-391f".to_owned());
8750        settle(
8751            &mut noop,
8752            Verdict {
8753                status: RunStatus::VerifiedNoop,
8754                left_pr: false,
8755                parked: false,
8756                quota_hit: false,
8757                no_viable_candidates: true,
8758            },
8759            "candidate A: already fixed by b32cfc4, on main",
8760            4,
8761        );
8762        assert_eq!(
8763            noop.status,
8764            TaskStatus::Held,
8765            "an unverified claim is a request for a human, not a failure"
8766        );
8767        assert!(
8768            !noop.status.runnable(),
8769            "the loop must not requeue this on the same unverified claim"
8770        );
8771        // `Task::release` resets attempts to zero the moment a human looks at
8772        // the evidence and lets it run again, so it does not matter here
8773        // whether the one attempt already spent stays spent - what matters is
8774        // that nothing retries this task unattended in the meantime.
8775        assert_eq!(noop.attempts, 1);
8776    }
8777
8778    #[test]
8779    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8780        // Parking is the operator asking for the process back - to replace the
8781        // binary, most of all. The run's work is intact on disk, so this is
8782        // not a failed attempt, and charging for it would mean a few upgrades
8783        // could exhaust a budget meant for agents that misbehaved.
8784        let mut parked = task();
8785        parked.start("20260903-183634-2d98".to_owned());
8786        settle(
8787            &mut parked,
8788            Verdict {
8789                status: RunStatus::Implementing,
8790                left_pr: false,
8791                quota_hit: false,
8792                parked: true,
8793                no_viable_candidates: false,
8794            },
8795            "parked after `implementing`",
8796            2,
8797        );
8798        assert_eq!(parked.attempts, 0, "a park is refunded");
8799        assert!(
8800            parked.status.runnable(),
8801            "and the task stays in line so the next loop resumes its run"
8802        );
8803        assert_eq!(parked.status, TaskStatus::Parked);
8804        assert_eq!(
8805            parked.park_reason.as_deref(),
8806            Some("parked after `implementing`"),
8807            "the card says where it stopped"
8808        );
8809        assert_eq!(parked.last_error, None, "nothing failed");
8810
8811        // Without the park flag the same non-terminal status is what it always
8812        // was: `execute` returning mid-flight, which is a bug and spends an
8813        // attempt so a task cannot loop on it forever.
8814        let mut broken = task();
8815        broken.start("20260903-183634-2d98".to_owned());
8816        settle(
8817            &mut broken,
8818            Verdict {
8819                status: RunStatus::Implementing,
8820                left_pr: false,
8821                quota_hit: false,
8822                parked: false,
8823                no_viable_candidates: false,
8824            },
8825            "returned mid-flight",
8826            2,
8827        );
8828        assert_eq!(broken.attempts, 1);
8829    }
8830
8831    #[test]
8832    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
8833        // Run e633: quorum lost because two judges answered with the wrong
8834        // JSON shape, `quota: []`. Refunding that takes the bound off the
8835        // retry loop, and each retry pays for a fresh hour-long implement
8836        // wave before it can fail the same way.
8837        let mut flaky = task();
8838        flaky.start("20260903-123023-e633".to_owned());
8839        settle(
8840            &mut flaky,
8841            Verdict {
8842                status: RunStatus::Stalled,
8843                left_pr: false,
8844                parked: false,
8845                quota_hit: false,
8846                no_viable_candidates: false,
8847            },
8848            "verdict rests on 1 of 3 judges",
8849            2,
8850        );
8851        assert_eq!(
8852            flaky.attempts, 1,
8853            "flakiness spends an attempt, so `max_attempts` still bounds it"
8854        );
8855        assert!(flaky.status.runnable(), "and it is still worth retrying");
8856
8857        // The same status, lost to a rate limit, is the machine's fault.
8858        let mut limited = task();
8859        limited.start("20260903-123023-e633".to_owned());
8860        settle(
8861            &mut limited,
8862            Verdict {
8863                status: RunStatus::Stalled,
8864                left_pr: false,
8865                parked: false,
8866                quota_hit: true,
8867                no_viable_candidates: false,
8868            },
8869            "judge-2, judge-3 out of quota",
8870            2,
8871        );
8872        assert_eq!(limited.attempts, 0, "a quota window is refunded");
8873        assert!(limited.status.runnable());
8874
8875        // And the bound really binds: a task that keeps stalling on flakiness
8876        // reaches a human instead of running the roster forever.
8877        let mut worn = task();
8878        for _ in 0..2 {
8879            worn.release();
8880        }
8881        worn.start("20260903-123023-e633".to_owned());
8882        worn.attempts = 2;
8883        settle(
8884            &mut worn,
8885            Verdict {
8886                status: RunStatus::Stalled,
8887                left_pr: false,
8888                parked: false,
8889                quota_hit: false,
8890                no_viable_candidates: false,
8891            },
8892            "no quorum again",
8893            2,
8894        );
8895        assert_eq!(worn.status, TaskStatus::Held);
8896        assert!(!worn.status.runnable());
8897    }
8898
8899    #[test]
8900    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8901        // The implement wave loses every seat to the same rate limit and
8902        // `after_implement` bails with nothing viable, which surfaces as
8903        // `Failed` rather than `Stalled`. That is the same machine fact the
8904        // `Stalled`-quota row already refunds, and must be refunded the same
8905        // way, or a quota outage quietly holds every task it touches instead
8906        // of leaving them in line for the reset.
8907        let mut wiped_out = task();
8908        wiped_out.start("20260907-025000-a1b2".to_owned());
8909        settle(
8910            &mut wiped_out,
8911            Verdict {
8912                status: RunStatus::Failed,
8913                left_pr: false,
8914                parked: false,
8915                quota_hit: true,
8916                no_viable_candidates: true,
8917            },
8918            "no candidate produced a change; nothing to judge",
8919            2,
8920        );
8921        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8922        assert!(
8923            wiped_out.status.runnable(),
8924            "a machine problem must leave the task in line"
8925        );
8926
8927        // This is the exemption that must stay narrow: a candidate that did
8928        // produce a change, and then failed for some other reason, still
8929        // spends the attempt even though a seat elsewhere hit its quota.
8930        // Otherwise every ordinary failure that happens to share a run with
8931        // an unrelated rate limit would be refunded for free.
8932        let mut partial_progress = task();
8933        partial_progress.start("20260907-025500-c3d4".to_owned());
8934        settle(
8935            &mut partial_progress,
8936            Verdict {
8937                status: RunStatus::Failed,
8938                left_pr: false,
8939                parked: false,
8940                quota_hit: true,
8941                no_viable_candidates: false,
8942            },
8943            "gate failed on the winning candidate",
8944            2,
8945        );
8946        assert_eq!(
8947            partial_progress.attempts, 1,
8948            "a candidate that actually produced a change spends the attempt \
8949             even though some other seat hit its quota"
8950        );
8951        assert!(partial_progress.status.runnable());
8952    }
8953
8954    #[test]
8955    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8956        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
8957        // disk, and that construction must reach the same conclusion as the
8958        // one `attempt` builds from a live run, or a crash at exactly the
8959        // wrong moment gives a recovered task a different policy than one a
8960        // daemon finished settling itself.
8961        let mut t = task();
8962        t.start("20260907-025000-a1b2".to_owned());
8963        let mut state = run_state(RunStatus::Failed);
8964        state.quota.push(QuotaLoss {
8965            cause: crate::agent::QuotaCause::UsageLimit,
8966            agent: String::new(),
8967            seat: "cand-a".to_owned(),
8968            node: "implement".to_owned(),
8969            at: Timestamp::now(),
8970            reset: None,
8971        });
8972        assert!(
8973            state.viable().is_empty(),
8974            "no candidate was added, so nothing is viable"
8975        );
8976        reclaim(&mut t, Some(state), 2, "en");
8977        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8978        assert!(t.status.runnable());
8979    }
8980
8981    #[test]
8982    fn a_held_task_is_never_offered_to_the_loop() {
8983        let dir = tempfile::tempdir().unwrap();
8984        let queue = Queue::at(dir.path().to_path_buf());
8985        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8986            let mut t = task();
8987            t.id = format!("2026090{n}-000000-000{n}");
8988            t.priority = priority;
8989            queue.put(&mut t).unwrap();
8990        }
8991        let mut held = task();
8992        held.id = "20260909-000000-9999".to_owned();
8993        held.priority = 99;
8994        held.hold_machine(None);
8995        queue.put(&mut held).unwrap();
8996
8997        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8998        assert_eq!(order.len(), 3);
8999        assert!(!order.contains(&held.id));
9000        assert_eq!(
9001            order.first().cloned(),
9002            queue.next_runnable().map(|t| t.id),
9003            "the loop's first candidate is exactly what the queue offers"
9004        );
9005        assert_eq!(
9006            order,
9007            vec![
9008                "20260902-000000-0002".to_owned(),
9009                "20260903-000000-0003".to_owned(),
9010                "20260901-000000-0001".to_owned(),
9011            ],
9012            "priority first, then oldest, so nothing starves"
9013        );
9014    }
9015
9016    #[test]
9017    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
9018        let dir = tempfile::tempdir().unwrap();
9019        let queue = Queue::at(dir.path().to_path_buf());
9020        let mut old = task();
9021        old.id = "20260101-000000-old0".to_owned();
9022        queue.put(&mut old).unwrap();
9023        let mut fresh = task();
9024        fresh.id = "20260101-000000-new0".to_owned();
9025        queue.put(&mut fresh).unwrap();
9026
9027        // No parseable pid at all, so age is the only signal there is to
9028        // check - unlike a real `Queue::claim`, which always names a real,
9029        // and therefore alive, pid this test cannot fake as dead.
9030        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
9031        std::thread::sleep(Duration::from_millis(60));
9032        let live = queue.claim(&fresh.id).unwrap();
9033
9034        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9035        assert_eq!(swept, vec![old.id.clone()]);
9036        assert!(
9037            queue.claim(&old.id).is_ok(),
9038            "an unparseable lock older than the threshold is swept"
9039        );
9040        assert!(
9041            queue.claim(&fresh.id).is_err(),
9042            "a live pid protects its lock regardless of age"
9043        );
9044        drop(live);
9045    }
9046
9047    #[test]
9048    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
9049        // A live worker's claim remains authoritative even beyond the sweep's
9050        // age limit. Sweeping it would permit a second competing attempt.
9051        let dir = tempfile::tempdir().unwrap();
9052        let queue = Queue::at(dir.path().to_path_buf());
9053        let mut t = task();
9054        t.id = "20260101-000000-live".to_owned();
9055        queue.put(&mut t).unwrap();
9056
9057        let claim = queue.claim(&t.id).unwrap();
9058        std::thread::sleep(Duration::from_millis(60));
9059
9060        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9061        assert!(
9062            swept.is_empty(),
9063            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
9064        );
9065        assert!(
9066            queue.claim(&t.id).is_err(),
9067            "the lock still protects its task"
9068        );
9069        drop(claim);
9070    }
9071
9072    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
9073    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
9074    fn injected_dead_pid() -> u32 {
9075        std::process::id().checked_add(1).unwrap_or(1)
9076    }
9077
9078    #[test]
9079    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
9080        let dir = tempfile::tempdir().unwrap();
9081        let queue = Queue::at(dir.path().to_path_buf());
9082        let mut t = task();
9083        t.id = "20260101-000000-dead".to_owned();
9084        queue.put(&mut t).unwrap();
9085        let dead_pid = injected_dead_pid();
9086
9087        // Written directly rather than through `Queue::claim`, which would
9088        // stamp this test process's own very much alive pid and defeat the
9089        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
9090        // like moments after it died, not six hours later.
9091        std::fs::write(
9092            dir.path().join(format!("{}.lock", t.id)),
9093            dead_pid.to_string(),
9094        )
9095        .unwrap();
9096
9097        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9098            pid != dead_pid
9099        });
9100        assert_eq!(
9101            swept,
9102            vec![t.id.clone()],
9103            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
9104        );
9105        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
9106    }
9107
9108    #[test]
9109    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
9110        let dir = tempfile::tempdir().unwrap();
9111        let queue = Queue::at(dir.path().to_path_buf());
9112        let mut t = task();
9113        t.id = "20260101-000000-late".to_owned();
9114        queue.put(&mut t).unwrap();
9115        let dead_pid = injected_dead_pid();
9116
9117        // Tick one, standing in for the sweep `poll` already runs at
9118        // startup: nothing to find yet.
9119        assert!(
9120            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
9121            "nothing has claimed the task yet"
9122        );
9123
9124        // A second daemon claims the task and dies before it ever writes
9125        // `running`, well after this loop's own startup sweep already ran.
9126        std::fs::write(
9127            dir.path().join(format!("{}.lock", t.id)),
9128            dead_pid.to_string(),
9129        )
9130        .unwrap();
9131
9132        // Tick two, standing in for a poll long into this daemon's uptime:
9133        // the same function, called again, notices what only just appeared -
9134        // proving the sweep is not a one-shot startup check.
9135        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9136            pid != dead_pid
9137        });
9138        assert_eq!(swept, vec![t.id.clone()]);
9139    }
9140
9141    #[test]
9142    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
9143        // `reclaim_orphaned_running` looks up the task's last run, which
9144        // touches `run::home()`; the first call anywhere in this binary wins,
9145        // so this is a no-op if another test already pinned one, and either
9146        // way the run id below is never written under it.
9147        crate::run::pin_test_home();
9148        let dir = tempfile::tempdir().unwrap();
9149        let queue = Queue::at(dir.path().to_path_buf());
9150        let mut t = task();
9151        t.id = "20260101-000000-crsh".to_owned();
9152        t.status = TaskStatus::Running;
9153        t.attempts = 1;
9154        // No `run.json` behind this id: standing in for a run this test does
9155        // not need to make readable, since the point is the lock, not the
9156        // recovery table `reclaim` already has its own tests for.
9157        t.runs.push("20260904-000000-4043".to_owned());
9158        queue.put(&mut t).unwrap();
9159        let dead_pid = injected_dead_pid();
9160
9161        // The crashed daemon's own claim, naming a pid nothing on the
9162        // machine holds anymore.
9163        std::fs::write(
9164            dir.path().join(format!("{}.lock", t.id)),
9165            dead_pid.to_string(),
9166        )
9167        .unwrap();
9168
9169        // Before the lock is swept the task looks claimed, and
9170        // `reclaim_orphaned_running` must leave it alone - this is exactly
9171        // the bug: a `running` task stranded behind a dead daemon's lock,
9172        // invisible to the claim-as-proof check because the lock outlived
9173        // the process that wrote it.
9174        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
9175        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9176
9177        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9178            pid != dead_pid
9179        });
9180        assert_eq!(swept, vec![t.id.clone()]);
9181
9182        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9183        assert_eq!(reclaimed, vec![t.id.clone()]);
9184        let after = queue.get(&t.id).unwrap();
9185        assert_eq!(
9186            after.status,
9187            TaskStatus::Held,
9188            "no run.json to recover from, so a human is asked"
9189        );
9190        assert_eq!(
9191            after.runs,
9192            vec!["20260904-000000-4043".to_owned()],
9193            "the crashed run's id is kept as evidence, not discarded"
9194        );
9195    }
9196
9197    #[test]
9198    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
9199        let dir = tempfile::tempdir().unwrap();
9200        let queue = Queue::at(dir.path().to_path_buf());
9201        let mut t = task();
9202        t.id = "20260101-000000-unknown".to_owned();
9203        queue.put(&mut t).unwrap();
9204        let dead_pid = injected_dead_pid();
9205        std::fs::write(
9206            dir.path().join(format!("{}.lock", t.id)),
9207            dead_pid.to_string(),
9208        )
9209        .unwrap();
9210
9211        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
9212        assert!(swept.is_empty(), "an unknown pid must keep its lock");
9213        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
9214    }
9215
9216    fn run_state_in(status: RunStatus, language: &str) -> RunState {
9217        let mut s = run_state(status);
9218        s.config.graph.language = language.to_owned();
9219        s
9220    }
9221
9222    fn unstarted_verdict(status: RunStatus) -> Verdict {
9223        Verdict {
9224            status,
9225            left_pr: false,
9226            quota_hit: false,
9227            parked: false,
9228            no_viable_candidates: false,
9229        }
9230    }
9231
9232    #[test]
9233    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
9234        let mut t = task();
9235        t.attempts = 1;
9236        settle_in(
9237            &mut t,
9238            unstarted_verdict(RunStatus::AlreadyInBase),
9239            "already in main",
9240            1,
9241            phrases("en"),
9242            None,
9243        );
9244        assert_eq!(t.status, TaskStatus::Done);
9245        assert_eq!(t.attempts, 0);
9246    }
9247
9248    #[test]
9249    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
9250        let reason = |language: &str| {
9251            let mut t = task();
9252            settle_in(
9253                &mut t,
9254                unstarted_verdict(RunStatus::Judging),
9255                "boom",
9256                1,
9257                phrases(language),
9258                None,
9259            );
9260            t.last_error.or(t.hold_reason).unwrap_or_default()
9261        };
9262        assert!(
9263            reason("en").starts_with("the graph stopped at `"),
9264            "{}",
9265            reason("en")
9266        );
9267        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
9268        assert!(reason("日本語").contains("boom"));
9269        assert_eq!(reason("fr"), reason("en"));
9270    }
9271
9272    #[test]
9273    fn describe_follows_the_run_language_and_keeps_the_run_id() {
9274        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
9275        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
9276        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
9277        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
9278        assert!(ja.contains("[run "), "{ja}");
9279        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
9280        assert!(ended.starts_with("run 終了: "), "{ended}");
9281        let mut de = run_state_in(RunStatus::Failed, "de");
9282        let mut en = run_state_in(RunStatus::Failed, "en");
9283        de.id = "same".to_owned();
9284        en.id = "same".to_owned();
9285        assert_eq!(describe(&de), describe(&en));
9286    }
9287
9288    #[test]
9289    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
9290        use crate::handover::Refused;
9291        let cases = [
9292            Refused::Foreign {
9293                branch: "b".into(),
9294                path: "/w/x".into(),
9295                why: "made by hand".into(),
9296            },
9297            Refused::Unsafe {
9298                branch: "b".into(),
9299                path: "/w/x".into(),
9300                why: "its worktree has uncommitted changes (a.rs)".into(),
9301            },
9302            Refused::ReleaseFailed {
9303                branch: "b".into(),
9304                path: "/w/x".into(),
9305                run: "ab12".into(),
9306            },
9307        ];
9308        for r in &cases {
9309            let en = (phrases("en").handover_refused)(r);
9310            assert_eq!(en, r.to_string());
9311            let ja = (phrases("ja").handover_refused)(r);
9312            assert!(
9313                !ja.contains("is checked out") && !ja.contains("try again"),
9314                "{ja}"
9315            );
9316            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
9317            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
9318                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
9319            }
9320        }
9321        assert!(phrases("en").handover_hint.contains("release the task"));
9322        assert!(phrases("ja").handover_hint.contains("解放"));
9323    }
9324
9325    #[test]
9326    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
9327        let build = |lang: &str| {
9328            let mut s = run_state_in(RunStatus::Blocked, lang);
9329            s.id = "same".to_owned();
9330            s.config.graph.review_rounds = 3;
9331            let mut r = review_round(3);
9332            r.expected = 3;
9333            r.answered = 1;
9334            s.reviews.push(r);
9335            s.event(
9336                "review",
9337                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
9338            );
9339            s
9340        };
9341        let en = describe(&build("en"));
9342        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
9343        let ja = describe(&build("ja"));
9344        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
9345        assert!(!ja.contains("never answered"), "{ja}");
9346        assert!(ja.contains("[run "), "{ja}");
9347
9348        // An incomplete panel whose verification failed is a different stop:
9349        // the real event must survive in ja too.
9350        let mut failed = build("ja");
9351        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
9352            command: "cargo test".to_owned(),
9353            code: Some(1),
9354            output_tail: String::new(),
9355            duration_ms: 0,
9356            resource_blocked: false,
9357        });
9358        failed.event("review", "stopped; e2e failed: cargo test");
9359        let ja = describe(&failed);
9360        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
9361        assert!(!ja.contains("席のレビュアー"), "{ja}");
9362    }
9363
9364    #[test]
9365    fn refusals_and_recovery_prose_follow_the_language() {
9366        let home = crate::run::test_home();
9367        let t = held_task_with("r1");
9368        let q = action_question(
9369            "r1",
9370            ask::ChoiceAction::Resume {
9371                run: "r1".to_owned(),
9372            },
9373        );
9374        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
9375            ActionDecision::Refuse(s) => s,
9376            other => panic!("{other:?}"),
9377        };
9378        assert!(refuse(phrases("en")).contains("could not be read: gone"));
9379        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
9380        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
9381
9382        let mut held = task();
9383        reclaim(&mut held, None, 2, "ja");
9384        assert!(held.hold_reason.unwrap().contains("保留にしました"));
9385        let mut held = task();
9386        reclaim(&mut held, None, 2, "xx");
9387        assert!(held.hold_reason.unwrap().contains("held for a human"));
9388    }
9389
9390    fn run_state(status: RunStatus) -> RunState {
9391        let mut state = RunState::new(
9392            PathBuf::from("/repo"),
9393            "main".to_owned(),
9394            "abc1234def".to_owned(),
9395            "add retries".to_owned(),
9396            Config::default(),
9397        );
9398        state.status = status;
9399        state
9400    }
9401
9402    #[test]
9403    fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
9404        crate::run::pin_test_home();
9405        let dir = tempfile::tempdir().unwrap();
9406        let mut state = run_state(RunStatus::Blocked);
9407        state.id = "20260101-000000-audit".into();
9408        state.save_under(dir.path()).unwrap();
9409        let mut t = task();
9410        t.start(state.id.clone());
9411        // The final state is newer than disk, as when a worker settles its
9412        // in-memory outcome or recovery is passed an already loaded run.
9413        state.status = RunStatus::Ready;
9414        settle_and_diagnose(
9415            &mut t,
9416            unstarted_verdict(RunStatus::Ready),
9417            "Verified local delivery",
9418            2,
9419            &state,
9420        );
9421        let completion = t.completion_history.last().unwrap();
9422        assert_eq!(completion.actor, CompletionActor::DaemonSettle);
9423        assert_eq!(completion.prior_status, TaskStatus::Running);
9424        assert_eq!(
9425            completion.reason.as_deref(),
9426            Some("Verified local delivery")
9427        );
9428        let snapshot = completion.run.as_ref().unwrap();
9429        assert_eq!(snapshot.id, state.id);
9430        assert_eq!(snapshot.status, Some(RunStatus::Ready));
9431        assert_eq!(
9432            RunState::load_under(&state.id, dir.path()).unwrap().status,
9433            RunStatus::Blocked,
9434            "settlement records the actual outcome without rewriting run history"
9435        );
9436    }
9437
9438    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
9439        Candidate {
9440            index: 0,
9441            label,
9442            agent: "claude".to_owned(),
9443            branch: format!("magi/x/{label}"),
9444            worktree: PathBuf::from("/repo"),
9445            summary: summary.to_owned(),
9446            stat: String::new(),
9447            files: 0,
9448            commits: usize::from(!empty),
9449            empty,
9450            failed: failed.map(str::to_owned),
9451            verified_noop: None,
9452            duration_ms: 0,
9453            folded: false,
9454        }
9455    }
9456
9457    #[test]
9458    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
9459        let mut state = run_state(RunStatus::Blocked);
9460        state.gate = vec![
9461            CommandOutcome {
9462                command: "cargo make check".to_owned(),
9463                code: Some(0),
9464                output_tail: "ok".to_owned(),
9465                duration_ms: 0,
9466                resource_blocked: false,
9467            },
9468            CommandOutcome {
9469                command: "cargo test".to_owned(),
9470                code: Some(101),
9471                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
9472                duration_ms: 0,
9473                resource_blocked: false,
9474            },
9475        ];
9476        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
9477        assert!(d.contains("cargo test"), "{d}");
9478        assert!(
9479            !d.contains("cargo make check"),
9480            "a passing check is not a diagnostic: {d}"
9481        );
9482        assert!(d.contains("assertion failed"), "{d}");
9483    }
9484
9485    #[test]
9486    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
9487        let mut state = run_state(RunStatus::Blocked);
9488        state.event(
9489            "land",
9490            "stopped: the fixer produced no commit while 2 check(s) were failing \
9491             (build, lint); stopping instead of looping on an unchanged tree",
9492        );
9493        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
9494        assert!(d.contains("build"), "{d}");
9495        assert!(d.contains("lint"), "{d}");
9496        assert!(d.contains("fixer produced no commit"), "{d}");
9497    }
9498
9499    #[test]
9500    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
9501        // `describe`'s output becomes `Task::last_error` verbatim, and the
9502        // phone renders that in the same alarm-styled box an ordinary
9503        // failure gets. A bare `verified_noop` there would read exactly like
9504        // the failure this status exists to be told apart from.
9505        let state = run_state(RunStatus::VerifiedNoop);
9506        let d = describe(&state);
9507        assert!(
9508            d.contains("agent-verified no-op"),
9509            "expected the display label, not the wire spelling: {d}"
9510        );
9511        assert!(!d.contains("verified_noop"), "{d}");
9512    }
9513
9514    #[test]
9515    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
9516        let mut state = run_state(RunStatus::Failed);
9517        state.gate.push(crate::run::CommandOutcome {
9518            command: "cargo test".into(),
9519            code: Some(101),
9520            output_tail: format!(
9521                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
9522                "  41: 0x1234 - backtrace frame\n".repeat(10000)
9523            ),
9524            duration_ms: 1,
9525            resource_blocked: false,
9526        });
9527        let d = diagnostic(&state).unwrap();
9528        assert!(d.contains("panicked at widget.rs:12"), "{d}");
9529        assert!(d.contains("assertion failed: widget missing"));
9530        assert!(d.contains("widget log"));
9531    }
9532
9533    #[test]
9534    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
9535        // The whole point of the feature: a run held as "no candidate produced
9536        // a change" can mean the implementer actually finished the task and
9537        // only left a clean local tree behind - see AGENTS.md on this exact
9538        // failure mode. The diagnostic has to carry what the agent actually
9539        // said, not just the fact that nothing was there to judge.
9540        let mut state = run_state(RunStatus::Failed);
9541        state.candidates = vec![candidate(
9542            'A',
9543            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
9544            true,
9545            None,
9546        )];
9547        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
9548        assert!(d.contains("candidate A"), "{d}");
9549        assert!(d.contains("tagged v1.2.3"), "{d}");
9550    }
9551
9552    #[test]
9553    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
9554        let mut state = run_state(RunStatus::Failed);
9555        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
9556        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
9557        assert!(d.contains("candidate A"), "{d}");
9558        assert!(d.contains("agent timed out"), "{d}");
9559    }
9560
9561    #[test]
9562    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9563        // A viable candidate existed, the gate never ran, and nothing land
9564        // said matches - `Task::last_error` is left to explain this one alone.
9565        let mut state = run_state(RunStatus::Failed);
9566        state.candidates = vec![candidate('A', "did the work", false, None)];
9567        assert!(diagnostic(&state).is_none());
9568    }
9569
9570    #[test]
9571    fn diagnostic_is_bounded_however_much_a_run_printed() {
9572        let mut state = run_state(RunStatus::Blocked);
9573        state.gate = vec![
9574            CommandOutcome {
9575                command: "cargo test".to_owned(),
9576                code: Some(101),
9577                output_tail: "x".repeat(50_000),
9578                duration_ms: 0,
9579                resource_blocked: false,
9580            },
9581            CommandOutcome {
9582                command: "cargo clippy".to_owned(),
9583                code: Some(1),
9584                output_tail: "y".repeat(50_000),
9585                duration_ms: 0,
9586                resource_blocked: false,
9587            },
9588        ];
9589        state.candidates = vec![
9590            candidate('A', &"z".repeat(50_000), true, None),
9591            candidate('B', &"w".repeat(50_000), true, None),
9592        ];
9593        let d = diagnostic(&state).expect("plenty here to diagnose");
9594        assert!(
9595            d.len() <= DIAGNOSTIC_MAX,
9596            "diagnostic grew to {} bytes, unbounded",
9597            d.len()
9598        );
9599    }
9600
9601    #[test]
9602    fn selected_delivery_guards_survive_recovery_failure_accounting() {
9603        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9604            let mut t = task();
9605            let mut state = run_state(status);
9606            t.pr_recovery = Some(crate::pr_recovery::Selection {
9607                url: "url".into(),
9608                branch: format!("magi/task-{}", t.id),
9609                head: "a".repeat(40),
9610                source_head: None,
9611                source_run: None,
9612                source_proof: None,
9613                disposition: Some(crate::pr_recovery::Disposition::Land),
9614                instruction: t.instruction.clone(),
9615                approved_at: Timestamp::now(),
9616            });
9617            state.pr_recovery = t.pr_recovery.clone();
9618            t.start(state.id.clone());
9619            settle_and_diagnose(
9620                &mut t,
9621                Verdict {
9622                    status,
9623                    left_pr: false,
9624                    quota_hit: false,
9625                    parked: false,
9626                    no_viable_candidates: false,
9627                },
9628                "delivery stopped",
9629                5,
9630                &state,
9631            );
9632            assert_eq!(t.status, TaskStatus::Held);
9633            let reason = t.hold_reason.as_deref().unwrap();
9634            if status == RunStatus::Ready {
9635                assert!(reason.contains("Selected PR delivery is incomplete"));
9636                assert!(t.recovery_budget.is_none());
9637            } else {
9638                assert!(reason.contains("Selected recovery stopped"));
9639                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9640            }
9641            assert!(t.pr_recovery.is_some());
9642        }
9643    }
9644
9645    #[test]
9646    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9647        let mut state = run_state(RunStatus::Voting);
9648        state.base_sync = Some(crate::run::BaseSync {
9649            tip: "base-tip".into(),
9650            behind: 3,
9651            attempts: 4,
9652            conflict: Some("base stopped".into()),
9653            already_in: None,
9654        });
9655        state.record_base_sync_stop("candidate-head");
9656        let mut t = task();
9657        t.start(state.id.clone());
9658        let verdict = Verdict {
9659            status: RunStatus::Blocked,
9660            left_pr: false,
9661            quota_hit: false,
9662            parked: false,
9663            no_viable_candidates: false,
9664        };
9665        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9666        assert_eq!(
9667            t.status,
9668            TaskStatus::Held,
9669            "unspent task attempts cannot start another competition"
9670        );
9671        let at = t.held_at;
9672        let cause = t.hold_notice_cause.clone();
9673        state.begin_pass();
9674        t.release_operator("test-resume", None);
9675        t.start(state.id.clone());
9676        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9677        assert_eq!(t.status, TaskStatus::Held);
9678        assert_eq!(t.held_at, at);
9679        assert_eq!(t.hold_notice_cause, cause);
9680    }
9681
9682    #[test]
9683    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9684        let mut state = run_state(RunStatus::Blocked);
9685        state.gate = vec![CommandOutcome {
9686            command: "cargo test".to_owned(),
9687            code: Some(101),
9688            output_tail: "assertion failed".to_owned(),
9689            duration_ms: 0,
9690            resource_blocked: false,
9691        }];
9692        let verdict = Verdict {
9693            status: RunStatus::Blocked,
9694            left_pr: false,
9695            quota_hit: false,
9696            parked: false,
9697            no_viable_candidates: false,
9698        };
9699
9700        // Attempt one of two still has a retry coming: no diagnostic yet, the
9701        // task is going to run again and this run's evidence would go stale.
9702        let mut t = task();
9703        t.start("run-1".to_owned());
9704        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9705        assert_eq!(t.status, TaskStatus::Failed);
9706        assert!(t.diagnostic.is_none());
9707
9708        // Attempt two exhausts the budget: now it is held, and the
9709        // diagnostic is what `magi task show` has to say more than one line.
9710        t.start("run-2".to_owned());
9711        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9712        assert_eq!(t.status, TaskStatus::Held);
9713        let d = t.diagnostic.expect("a held task must carry its diagnostic");
9714        assert!(d.contains("cargo test"), "{d}");
9715    }
9716
9717    #[test]
9718    fn a_held_task_names_the_open_question_it_is_waiting_on() {
9719        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
9720        // `magi ask` question settled Held with `hold_reason: null`, so the
9721        // notification said nothing actionable. `note_open_question` should
9722        // append the question id to whatever `handed_off` already wrote.
9723        crate::run::pin_test_home();
9724        let home = crate::run::home();
9725        let state = run_state(RunStatus::VerifiedNoop);
9726        let mut q = ask::Question::new(
9727            state.id.clone(),
9728            "implement".to_owned(),
9729            "impl-A".to_owned(),
9730            "is this really a no-op?".to_owned(),
9731            String::new(),
9732            Vec::new(),
9733        );
9734        Questions::at(home.join("questions")).put(&mut q).unwrap();
9735
9736        let verdict = Verdict {
9737            status: RunStatus::VerifiedNoop,
9738            left_pr: false,
9739            quota_hit: false,
9740            parked: false,
9741            no_viable_candidates: false,
9742        };
9743        let mut t = task();
9744        t.start(state.id.clone());
9745        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9746
9747        assert_eq!(t.status, TaskStatus::Held);
9748        let reason = t.hold_reason.expect("a held task must record why");
9749        assert!(
9750            reason.starts_with("run ended agent-verified no-op"),
9751            "the original settle reason must survive unchanged: {reason}"
9752        );
9753        assert!(
9754            reason.contains(q.short()),
9755            "the open question's id must be named so the notice is actionable: {reason}"
9756        );
9757    }
9758
9759    #[test]
9760    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9761        crate::run::pin_test_home();
9762        let state = run_state(RunStatus::VerifiedNoop);
9763
9764        let verdict = Verdict {
9765            status: RunStatus::VerifiedNoop,
9766            left_pr: false,
9767            quota_hit: false,
9768            parked: false,
9769            no_viable_candidates: false,
9770        };
9771        let mut t = task();
9772        t.start(state.id.clone());
9773        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9774
9775        assert_eq!(t.status, TaskStatus::Held);
9776        assert_eq!(
9777            t.hold_reason.as_deref(),
9778            Some("run ended agent-verified no-op"),
9779            "nothing to append when the question was already answered or never asked"
9780        );
9781    }
9782
9783    #[test]
9784    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
9785        crate::run::pin_test_home();
9786        let mut first = run_state(RunStatus::Blocked);
9787        first.id = "20260101-000000-sup1".to_owned();
9788        first.save().unwrap();
9789        let mut second = run_state(RunStatus::Merged);
9790        second.id = "20260101-000000-sup2".to_owned();
9791        second.save().unwrap();
9792
9793        let mut t = task();
9794        t.runs = vec![first.id.clone(), second.id.clone()];
9795        t.status = TaskStatus::Done;
9796
9797        supersede_prior_runs(&t, &crate::run::home());
9798
9799        assert_eq!(
9800            RunState::load(&first.id).unwrap().status,
9801            RunStatus::Superseded,
9802            "the first attempt's Blocked no longer needs anyone's attention"
9803        );
9804        assert_eq!(
9805            RunState::load(&second.id).unwrap().status,
9806            RunStatus::Merged,
9807            "the run that actually succeeded is left exactly as it was"
9808        );
9809    }
9810
9811    #[test]
9812    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
9813        // `is_working_on` alone only proves a *daemon* claim; a `magi run
9814        // --resume` invoked by hand outside the daemon never touches
9815        // `daemon.json` at all, so it would look identical to a genuinely
9816        // idle run without also consulting `RunState::liveness`, which reads
9817        // this run's own recorded `driver_pid` instead.
9818        crate::run::pin_test_home();
9819        let mut first = run_state(RunStatus::Blocked);
9820        first.id = "20260101-000000-sup9".to_owned();
9821        // This test process's own pid: guaranteed alive without needing a
9822        // real second process or daemon.
9823        first.driver_pid = Some(std::process::id());
9824        first.driver_started_at = Some(
9825            crate::proc::process_started_at(std::process::id())
9826                .expect("this test process's own start time must be queryable"),
9827        );
9828        first.save().unwrap();
9829        let mut second = run_state(RunStatus::Merged);
9830        second.id = "20260101-000000-supa".to_owned();
9831        second.save().unwrap();
9832
9833        let mut t = task();
9834        t.runs = vec![first.id.clone(), second.id.clone()];
9835        t.status = TaskStatus::Done;
9836
9837        supersede_prior_runs(&t, &crate::run::home());
9838
9839        assert_eq!(
9840            RunState::load(&first.id).unwrap().status,
9841            RunStatus::Blocked,
9842            "a live driver_pid means something is still actually working this run, \
9843             even though no daemon claims it - rewriting under it would just be \
9844             undone the next time that process saves"
9845        );
9846    }
9847
9848    #[test]
9849    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
9850        // The first resweep must skip a still-live attempt exactly like
9851        // `supersede_prior_runs` itself does; a later resweep, once that
9852        // process is no longer actually driving it, is what closes the gap
9853        // `supersede_prior_runs` alone leaves - a task only ever reaches
9854        // `Done` once, so nothing else would ever look at this run again.
9855        let dir = tempfile::tempdir().unwrap();
9856        let home = dir.path().to_path_buf();
9857        let queue = Queue::at(dir.path().join("queue"));
9858
9859        let mut first = run_state(RunStatus::Blocked);
9860        first.id = "20260101-000000-supd".to_owned();
9861        first.driver_pid = Some(std::process::id());
9862        first.driver_started_at = Some(
9863            crate::proc::process_started_at(std::process::id())
9864                .expect("this test process's own start time must be queryable"),
9865        );
9866        first.save_under(&home).unwrap();
9867        let mut second = run_state(RunStatus::Merged);
9868        second.id = "20260101-000000-supe".to_owned();
9869        second.save_under(&home).unwrap();
9870
9871        let mut t = task();
9872        t.runs = vec![first.id.clone(), second.id.clone()];
9873        t.status = TaskStatus::Done;
9874        queue.put(&mut t).unwrap();
9875
9876        resweep_superseded_attempts(&queue, &home);
9877        assert_eq!(
9878            RunState::load_under(&first.id, &home).unwrap().status,
9879            RunStatus::Blocked,
9880            "still live on the first pass, so still untouched"
9881        );
9882
9883        // Stand in for the manual process no longer being the one driving
9884        // this run: same pid (this test process really is still alive), but
9885        // an identity marker that no longer matches it - see
9886        // `RunState::liveness`'s own doc for why a mismatched
9887        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
9888        let mut stale = RunState::load_under(&first.id, &home).unwrap();
9889        stale.driver_started_at = Some("1".to_owned());
9890        stale.save_under(&home).unwrap();
9891
9892        resweep_superseded_attempts(&queue, &home);
9893        assert_eq!(
9894            RunState::load_under(&first.id, &home).unwrap().status,
9895            RunStatus::Superseded,
9896            "the second pass catches up what the first one correctly skipped"
9897        );
9898    }
9899
9900    #[test]
9901    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
9902        crate::run::pin_test_home();
9903        let mut first = run_state(RunStatus::Blocked);
9904        first.id = "20260101-000000-sup3".to_owned();
9905        first.save().unwrap();
9906        let mut second = run_state(RunStatus::Blocked);
9907        second.id = "20260101-000000-sup4".to_owned();
9908        second.save().unwrap();
9909
9910        let mut t = task();
9911        t.runs = vec![first.id.clone(), second.id.clone()];
9912        // Still retrying: nothing about this task's story is settled yet, so
9913        // neither Blocked run may be relabelled, even though a later attempt
9914        // already exists.
9915        t.status = TaskStatus::Failed;
9916
9917        supersede_prior_runs(&t, &crate::run::home());
9918
9919        assert_eq!(
9920            RunState::load(&first.id).unwrap().status,
9921            RunStatus::Blocked
9922        );
9923        assert_eq!(
9924            RunState::load(&second.id).unwrap().status,
9925            RunStatus::Blocked
9926        );
9927    }
9928
9929    #[test]
9930    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9931        // `magi task done` (or the API's equivalent) can close a task with no
9932        // run of its own ever having succeeded - there is nothing here that
9933        // counts as "the attempt that finished it", so nothing is rewritten.
9934        crate::run::pin_test_home();
9935        let mut first = run_state(RunStatus::Blocked);
9936        first.id = "20260101-000000-sup5".to_owned();
9937        first.save().unwrap();
9938
9939        let mut t = task();
9940        t.runs = vec![first.id.clone()];
9941        t.status = TaskStatus::Done;
9942
9943        supersede_prior_runs(&t, &crate::run::home());
9944
9945        assert_eq!(
9946            RunState::load(&first.id).unwrap().status,
9947            RunStatus::Blocked,
9948            "a single-attempt task has no earlier run to supersede"
9949        );
9950    }
9951
9952    #[test]
9953    fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
9954        for status in [
9955            RunStatus::Blocked,
9956            RunStatus::Stalled,
9957            RunStatus::Failed,
9958            RunStatus::Ready,
9959            RunStatus::Merged,
9960        ] {
9961            let dir = tempfile::tempdir().unwrap();
9962            let home = dir.path();
9963            let mut first = run_state(RunStatus::Blocked);
9964            first.id = "20260101-000000-supb".to_owned();
9965            first.save_under(home).unwrap();
9966            let mut second = run_state(status);
9967            second.id = "20260101-000000-supc".to_owned();
9968            second.save_under(home).unwrap();
9969
9970            let mut t = task();
9971            t.runs = vec![first.id.clone(), second.id.clone()];
9972            t.hold_manual(Some("Unmerged work remains".into()));
9973            let mut context = CompletionContext::new(
9974                CompletionActor::Cli,
9975                Some("Discard the unmerged attempts".into()),
9976                home,
9977                &t,
9978            );
9979            context.discard = true;
9980            t.succeed(context);
9981            assert_eq!(t.completion_history.len(), 1);
9982
9983            supersede_prior_runs(&t, home);
9984
9985            assert_eq!(
9986                RunState::load_under(&first.id, home).unwrap().status,
9987                RunStatus::Blocked,
9988                "an audited manual close is not proof the earlier work landed"
9989            );
9990            assert_eq!(
9991                RunState::load_under(&second.id, home).unwrap().status,
9992                status,
9993                "the latest attempt retains its actual outcome"
9994            );
9995        }
9996    }
9997
9998    #[test]
9999    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
10000        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
10001        // to look" - `Failed` and `VerifiedNoop` are already their own
10002        // terminal answers and must not be relabelled into a third one.
10003        crate::run::pin_test_home();
10004        let mut failed = run_state(RunStatus::Failed);
10005        failed.id = "20260101-000000-sup6".to_owned();
10006        failed.save().unwrap();
10007        let mut noop = run_state(RunStatus::VerifiedNoop);
10008        noop.id = "20260101-000000-sup7".to_owned();
10009        noop.save().unwrap();
10010        let mut winner = run_state(RunStatus::Ready);
10011        winner.id = "20260101-000000-sup8".to_owned();
10012        winner.save().unwrap();
10013
10014        let mut t = task();
10015        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
10016        t.status = TaskStatus::Done;
10017
10018        supersede_prior_runs(&t, &crate::run::home());
10019
10020        assert_eq!(
10021            RunState::load(&failed.id).unwrap().status,
10022            RunStatus::Failed
10023        );
10024        assert_eq!(
10025            RunState::load(&noop.id).unwrap().status,
10026            RunStatus::VerifiedNoop
10027        );
10028    }
10029
10030    fn approval_question(run: &str) -> ask::Question {
10031        ask::Question::new(
10032            run.to_owned(),
10033            land::APPROVAL_NODE.to_owned(),
10034            "land".to_owned(),
10035            "merge?".to_owned(),
10036            String::new(),
10037            vec!["merge".to_owned(), "hold".to_owned()],
10038        )
10039    }
10040
10041    #[test]
10042    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
10043        crate::run::pin_test_home();
10044        let mut state = run_state(RunStatus::Landing);
10045        state.id = "20260101-000000-fre1".to_owned();
10046        state.parked = true;
10047        state.save().unwrap();
10048        ask::Questions::open()
10049            .put(&mut approval_question(&state.id))
10050            .unwrap();
10051
10052        let mut t = task();
10053        t.runs.push(state.id.clone());
10054        assert_eq!(
10055            land_resume_state(&t),
10056            LandResume::StillWaiting,
10057            "nobody has answered and the timeout has not passed"
10058        );
10059    }
10060
10061    #[test]
10062    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
10063        crate::run::pin_test_home();
10064        let mut state = run_state(RunStatus::Gating);
10065        state.id = "20260101-000000-gt01".to_owned();
10066        state.parked = true;
10067        state.config.graph.answer_timeout = 60;
10068        state.github_text = Some(crate::run::GithubTextAsk {
10069            rewrite: None,
10070            fingerprint: "f".into(),
10071            title: true,
10072            body: false,
10073            categories: vec!["title-language".into()],
10074            question: None,
10075            asks: 1,
10076            resolved: false,
10077            chosen_title: None,
10078            choice: None,
10079            publication: None,
10080        });
10081        state.save().unwrap();
10082        let store = ask::Questions::open();
10083        let mut q = ask::Question::new(
10084            state.id.clone(),
10085            crate::github_text::ASK_NODE.to_owned(),
10086            crate::github_text::ASK_SEAT.to_owned(),
10087            "s".into(),
10088            String::new(),
10089            vec!["use fallback".into()],
10090        );
10091        store.put(&mut q).unwrap();
10092        let mut t = task();
10093        t.runs.push(state.id.clone());
10094        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
10095        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10096        store.put(&mut q).unwrap();
10097        assert_eq!(land_resume_state(&t), LandResume::Ready);
10098        assert!(!store.get(&q.id).unwrap().status.open());
10099        // Once decided, a parked run is an ordinary candidate again.
10100        state.github_text.as_mut().unwrap().resolved = true;
10101        state.save().unwrap();
10102        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
10103    }
10104
10105    #[test]
10106    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
10107        // `ask::ask_and_wait`'s own deadline used to retire a question
10108        // nobody answered; land's approval bypasses that wait (see
10109        // `land::approval_gate`), so this is now the only place
10110        // `graph.answer_timeout` is enforced for a land approval at all.
10111        crate::run::pin_test_home();
10112        let mut state = run_state(RunStatus::Landing);
10113        state.id = "20260101-000000-exp1".to_owned();
10114        state.parked = true;
10115        state.config.graph.answer_timeout = 60;
10116        state.save().unwrap();
10117
10118        let store = ask::Questions::open();
10119        let mut q = approval_question(&state.id);
10120        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10121        store.put(&mut q).unwrap();
10122
10123        let mut t = task();
10124        t.runs.push(state.id.clone());
10125        assert_eq!(
10126            land_resume_state(&t),
10127            LandResume::Ready,
10128            "an expired question must not be waited on forever"
10129        );
10130
10131        let after = store.get(&q.id).unwrap();
10132        assert!(
10133            !after.status.open(),
10134            "the question is abandoned, not silently ignored"
10135        );
10136        assert!(
10137            after.resolution().is_none(),
10138            "an abandoned question is not read as a decision"
10139        );
10140    }
10141
10142    #[test]
10143    fn reclaim_settles_a_running_task_against_its_last_run() {
10144        let mut t = task();
10145        t.start("20260904-000000-4043".to_owned());
10146        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
10147        assert_eq!(
10148            t.status,
10149            TaskStatus::Done,
10150            "a run that actually finished must not stay `running` forever"
10151        );
10152    }
10153
10154    #[test]
10155    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
10156        let dir = tempfile::tempdir().unwrap();
10157        let queue = Queue::at(dir.path().join("queue"));
10158        let mut task = task();
10159        let mut run = run_state(RunStatus::Blocked);
10160        run.reserve_under(dir.path()).unwrap();
10161        run.driver_exited = true;
10162        run.save_under(dir.path()).unwrap();
10163        queue.put(&mut task).unwrap();
10164        let stale = task.clone();
10165        task.resume_override = Some(crate::queue::OperatorResume {
10166            question_id: "pending-resume".into(),
10167            at: Timestamp::now(),
10168            conductor_rehold: None,
10169            forced: true,
10170            pinned_run: Some(run.id.clone()),
10171        });
10172        task.start(run.id.clone());
10173        queue.put(&mut task).unwrap();
10174        // Discard every in-memory handoff, as a worker death before execute does.
10175        let mut recovered = queue.get(&task.id).unwrap();
10176        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
10177        reclaim(&mut recovered, Some(disk), 2, "en");
10178        queue.put(&mut recovered).unwrap();
10179        assert!(recovered.resume_override.is_none());
10180        assert_eq!(
10181            recovered.dispatched_resumes.get("pending-resume"),
10182            Some(&run.id)
10183        );
10184        let mut stale = stale;
10185        queue.put(&mut stale).unwrap();
10186        assert_eq!(
10187            stale.dispatched_resumes, recovered.dispatched_resumes,
10188            "a stale task writer cannot erase dispatch ownership"
10189        );
10190        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
10191        assert!(resumed.decision_starts.is_empty());
10192        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
10193        assert!(
10194            resumed.decision_starts.is_empty(),
10195            "handoff is not execution proof"
10196        );
10197        resumed.begin_pass();
10198        resumed.save_under(dir.path()).unwrap();
10199        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
10200        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
10201        disk.carry_dispatched_resumes(&recovered);
10202        disk.begin_pass();
10203        assert_eq!(
10204            disk.decision_starts.get("pending-resume"),
10205            Some(&0),
10206            "later execution must preserve the original pass receipt"
10207        );
10208    }
10209
10210    #[test]
10211    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
10212        let mut t = task();
10213        t.start("20260904-000000-4043".to_owned());
10214        t.last_error = Some("earlier trouble".to_owned());
10215        let mut state = run_state(RunStatus::Judging);
10216        state.parked = true;
10217        reclaim(&mut t, Some(state), 1, "en");
10218        assert_eq!(t.status, TaskStatus::Parked);
10219        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
10220        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10221        assert!(t.park_reason.is_some());
10222        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
10223        assert!(!t.fresh_start);
10224        assert!(t.status.runnable());
10225    }
10226
10227    #[test]
10228    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
10229        let mut t = task();
10230        t.start("20260904-000000-4043".to_owned());
10231        t.last_error = Some("earlier trouble".to_owned());
10232        settle(
10233            &mut t,
10234            Verdict {
10235                status: RunStatus::Judging,
10236                left_pr: false,
10237                quota_hit: false,
10238                parked: true,
10239                no_viable_candidates: false,
10240            },
10241            "parked after `judging`",
10242            1,
10243        );
10244        assert_eq!(t.status, TaskStatus::Parked);
10245        assert_eq!(t.attempts, 0);
10246        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10247        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
10248        assert_eq!(t.schema, crate::queue::SCHEMA);
10249        assert!(
10250            crate::notices::task_held(&t).is_none(),
10251            "a park is not news"
10252        );
10253        t.start("20260904-000000-4043".to_owned());
10254        assert_eq!(t.park_reason, None);
10255    }
10256
10257    #[test]
10258    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
10259        // A blocked run with attempts left goes back to `Failed`, exactly as
10260        // it would from `attempt` itself - `reclaim` must not invent a second
10261        // policy for a task a daemon merely stopped without reporting.
10262        let mut t = task();
10263        t.start("20260904-000000-4043".to_owned());
10264        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
10265        assert_eq!(t.status, TaskStatus::Failed);
10266        assert!(t.status.runnable());
10267    }
10268
10269    #[test]
10270    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
10271        let mut t = task();
10272        t.start("20260904-000000-4043".to_owned());
10273        assert_eq!(t.attempts, 1);
10274        let mut run = run_state(RunStatus::Implementing);
10275        run.id = "20260904-000000-4043".to_owned();
10276        run.begin_pass();
10277        let cause = crate::run::ParkCause::Upgrade {
10278            from: "0.121.0".to_owned(),
10279            to: Some("0.121.1".to_owned()),
10280        };
10281        run.end_pass_parked(cause.clone());
10282        run.parked = true;
10283        let verdict = Verdict {
10284            status: run.status,
10285            left_pr: false,
10286            quota_hit: false,
10287            parked: true,
10288            no_viable_candidates: false,
10289        };
10290        // A crash after the checkpoint but before queue settlement must
10291        // recover exactly the same scheduling evidence and refund.
10292        let mut orphan = t.clone();
10293        reclaim(&mut orphan, Some(run.clone()), 2, "en");
10294        assert_eq!(orphan.status, TaskStatus::Parked);
10295        assert_eq!(orphan.attempts, 0);
10296        assert_eq!(
10297            orphan.upgrade_resume_key(),
10298            Some((run.passes[0].started_at, orphan.id.as_str()))
10299        );
10300        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
10301        assert_eq!(t.attempts, 0);
10302        assert_eq!(t.passes.len(), 1);
10303        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10304        assert_eq!(t.passes[0].parked, Some(cause));
10305        assert_eq!(t.passes[0].pass_index, 0);
10306        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
10307        assert!(t.upgrade_resume_key().is_some());
10308
10309        // A resumed pass that then fails spends its attempt, and the earlier
10310        // pass's entry is untouched.
10311        t.start("20260904-000000-4043".to_owned());
10312        run.begin_pass();
10313        run.status = RunStatus::Failed;
10314        let verdict = Verdict {
10315            status: RunStatus::Failed,
10316            left_pr: false,
10317            quota_hit: false,
10318            parked: false,
10319            no_viable_candidates: false,
10320        };
10321        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
10322        assert_eq!(t.passes.len(), 2);
10323        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10324        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
10325        assert_eq!(t.passes[1].pass_index, 1);
10326        assert_eq!(t.attempts, 1);
10327    }
10328
10329    #[test]
10330    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
10331        let mut t = task();
10332        t.start("20260904-000000-4043".to_owned());
10333        reclaim(&mut t, None, 2, "en");
10334        assert_eq!(t.status, TaskStatus::Held);
10335        assert!(
10336            t.last_error
10337                .as_deref()
10338                .is_some_and(|e| e.contains("running")),
10339            "the operator needs to know why this task was held"
10340        );
10341    }
10342
10343    #[test]
10344    fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
10345        let dir = tempfile::tempdir().unwrap();
10346        let queue = Queue::at(dir.path().to_path_buf());
10347        let mut task = task();
10348        let run = "20261124-000000-dead";
10349        task.link_run(run);
10350        task.attempts = 2;
10351        task.status = TaskStatus::Running;
10352        task.sync_only = Some(crate::base_sync_only::Request {
10353            run: run.into(),
10354            at: Timestamp::now(),
10355        });
10356        queue.put(&mut task).unwrap();
10357        assert_eq!(
10358            reclaim_orphaned_running(&queue, 3, &Default::default()),
10359            vec![task.id.clone()]
10360        );
10361        let saved = queue.get(&task.id).unwrap();
10362        assert_eq!(saved.status, TaskStatus::Held);
10363        assert_eq!(saved.attempts, 2);
10364        assert_eq!(saved.execution_runs(), [run]);
10365        assert!(
10366            saved
10367                .last_error
10368                .unwrap()
10369                .contains("verification was not allowed")
10370        );
10371        assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
10372    }
10373
10374    #[test]
10375    fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
10376        use crate::base_sync_only::{Outcome, Pass, Request};
10377
10378        let mut state = run_state(RunStatus::Blocked);
10379        let mut task = task();
10380        let request = Request {
10381            run: state.id.clone(),
10382            at: Timestamp::now(),
10383        };
10384        task.start(state.id.clone());
10385        task.sync_only = Some(request.clone());
10386        // Dedicated dispatch saves Running with the pre-pass attempt count.
10387        task.attempts = 2;
10388        let mut pass = Pass::new(request, &state);
10389        pass.result = Outcome::AlreadyCurrent;
10390        state.sync_only_passes.push(pass);
10391        state.begin_pass();
10392
10393        reclaim(&mut task, Some(state), 3, "en");
10394
10395        assert_eq!(task.status, TaskStatus::Held);
10396        assert_eq!(task.attempts, 2);
10397        assert!(task.sync_only.is_none());
10398        let detail = task.hold_reason.unwrap();
10399        assert!(detail.contains("HEAD already contains the base"));
10400        assert!(detail.contains("verification was not allowed"));
10401    }
10402
10403    #[test]
10404    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
10405        let dir = tempfile::tempdir().unwrap();
10406        let queue = Queue::at(dir.path().to_path_buf());
10407
10408        // No run recorded, so this never has to touch `RunState::load`.
10409        let mut orphaned = task();
10410        orphaned.id = "20260904-000000-orph".to_owned();
10411        orphaned.status = TaskStatus::Running;
10412        orphaned.attempts = 1;
10413        queue.put(&mut orphaned).unwrap();
10414
10415        let mut alive = task();
10416        alive.id = "20260904-000000-live".to_owned();
10417        alive.status = TaskStatus::Running;
10418        alive.attempts = 1;
10419        queue.put(&mut alive).unwrap();
10420        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
10421
10422        let mut queued = task();
10423        queued.id = "20260904-000000-wait".to_owned();
10424        queue.put(&mut queued).unwrap();
10425
10426        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10427        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
10428
10429        assert_eq!(
10430            queue.get(&orphaned.id).unwrap().status,
10431            TaskStatus::Held,
10432            "nothing was driving it and there was no run to recover"
10433        );
10434        assert_eq!(
10435            queue.get(&alive.id).unwrap().status,
10436            TaskStatus::Running,
10437            "a live claim must protect the task it belongs to"
10438        );
10439        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
10440    }
10441
10442    /// Read a run.json back from an explicit `home`, the same way
10443    /// `reclaim_abandoned_runs` itself does - never through the
10444    /// process-global `RunState::load`, which this test's own `home` (an
10445    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
10446    /// use at all.
10447    fn read_run_under(home: &Path, id: &str) -> RunState {
10448        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10449        serde_json::from_str(&body).unwrap()
10450    }
10451
10452    #[test]
10453    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
10454        let dir = tempfile::tempdir().unwrap();
10455        let home = dir.path().to_path_buf();
10456        let now = Timestamp::now();
10457        let overrun_seat = || crate::run::ActiveSeat {
10458            node: "implement".to_owned(),
10459            started_at: now - jiff::SignedDuration::new(21_000, 0),
10460            timeout_secs: 3_600,
10461            attempt: 0,
10462            task: None,
10463            command: None,
10464            index: None,
10465            total: None,
10466        };
10467
10468        let mut dead = run_state(RunStatus::Implementing);
10469        dead.id = "20260101-000000-dead".to_owned();
10470        dead.active.insert("impl-A".to_owned(), overrun_seat());
10471        // A `driver_pid` the injected query below confirms gone outright —
10472        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
10473        dead.driver_pid = Some(4242);
10474        dead.save_under(&home).unwrap();
10475
10476        // Same shape, but a live daemon's heartbeat names it: must be left
10477        // exactly alone, however far past its own timeout the seat sits.
10478        let mut alive = run_state(RunStatus::Implementing);
10479        alive.id = "20260101-000000-aliv".to_owned();
10480        alive.active.insert("impl-A".to_owned(), overrun_seat());
10481        alive.save_under(&home).unwrap();
10482        let mut status = Status::new();
10483        status.current = vec![Current {
10484            worker: None,
10485            task: "20260101-000000-task".to_owned(),
10486            run: alive.id.clone(),
10487        }];
10488        write_status_to(&home.join("daemon.json"), &status).unwrap();
10489
10490        // The abandoned seat left an open question behind: nobody is left to
10491        // read an answer once the run is failed, and this must not wait for
10492        // some later daemon startup's own sweep to notice that.
10493        let questions = Questions::at(home.join("questions"));
10494        let mut q = ask::Question::new(
10495            dead.id.clone(),
10496            "implement".to_owned(),
10497            "impl-A".to_owned(),
10498            "Which storage backend?".to_owned(),
10499            String::new(),
10500            vec!["SQLite".to_owned(), "Redis".to_owned()],
10501        );
10502        questions.put(&mut q).unwrap();
10503
10504        let abandoned = reclaim_abandoned_runs_with(
10505            &home,
10506            now,
10507            |pid| if pid == 4242 { Some(false) } else { None },
10508            |_| panic!("a query answering Dead outright needs no identity corroboration"),
10509        );
10510        assert_eq!(abandoned, vec![dead.id.clone()]);
10511
10512        let reloaded = read_run_under(&home, &dead.id);
10513        assert_eq!(reloaded.status, RunStatus::Failed);
10514        assert!(reloaded.active.is_empty());
10515        assert!(
10516            !questions.get(&q.id).unwrap().status.open(),
10517            "the failed run's own open question must be settled in the same pass"
10518        );
10519
10520        let still_alive = read_run_under(&home, &alive.id);
10521        assert_eq!(
10522            still_alive.status,
10523            RunStatus::Implementing,
10524            "a live daemon's claim protects it"
10525        );
10526        assert!(!still_alive.active.is_empty());
10527    }
10528
10529    /// The exact shape a review round flagged as broken: `magi serve` running
10530    /// in this same `home` scans *every* run on disk, including a manual
10531    /// `magi review` / `magi run` this daemon never started and that
10532    /// therefore claims no heartbeat of its own. Before this scan asked
10533    /// `liveness` rather than just `is_working_on`, a manual run whose active
10534    /// seat merely ran a little past its own timeout — the CLI finishing up,
10535    /// its result still being collected — got wiped and failed by a daemon
10536    /// that had nothing to do with it, out from under a process that was
10537    /// still very much running.
10538    #[test]
10539    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
10540        let dir = tempfile::tempdir().unwrap();
10541        let home = dir.path().to_path_buf();
10542        let now = Timestamp::now();
10543
10544        let mut manual = run_state(RunStatus::Reviewing);
10545        manual.id = "20260101-000000-manl".to_owned();
10546        manual.active.insert(
10547            "review-1".to_owned(),
10548            crate::run::ActiveSeat {
10549                node: "review".to_owned(),
10550                started_at: now - jiff::SignedDuration::new(21_000, 0),
10551                timeout_secs: 3_600,
10552                attempt: 0,
10553                task: None,
10554                command: None,
10555                index: None,
10556                total: None,
10557            },
10558        );
10559        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
10560        // but a real, still-running process: `liveness` must corroborate this
10561        // as `Live`, not read the missing daemon claim as death.
10562        manual.driver_pid = Some(4242);
10563        manual.driver_started_at = Some("1790000000".to_owned());
10564        manual.save_under(&home).unwrap();
10565
10566        let abandoned = reclaim_abandoned_runs_with(
10567            &home,
10568            now,
10569            |pid| if pid == 4242 { Some(true) } else { None },
10570            |pid| {
10571                if pid == 4242 {
10572                    Some("1790000000".to_owned())
10573                } else {
10574                    None
10575                }
10576            },
10577        );
10578        assert!(
10579            abandoned.is_empty(),
10580            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
10581        );
10582
10583        let reloaded = read_run_under(&home, &manual.id);
10584        assert_eq!(reloaded.status, RunStatus::Reviewing);
10585        assert!(!reloaded.active.is_empty());
10586    }
10587
10588    #[test]
10589    fn an_already_claimed_task_is_skipped_rather_than_failed() {
10590        let dir = tempfile::tempdir().unwrap();
10591        let queue = Queue::at(dir.path().to_path_buf());
10592        let mut only = task();
10593        queue.put(&mut only).unwrap();
10594
10595        let _elsewhere = queue.claim(&only.id).unwrap();
10596        let candidates = runnable(&queue);
10597        assert_eq!(candidates.len(), 1, "the task is still runnable");
10598        assert!(
10599            queue.claim(&candidates[0].id).is_err(),
10600            "the loop cannot take a claim somebody else holds"
10601        );
10602
10603        let after = queue.get(&only.id).unwrap();
10604        assert_eq!(after.status, TaskStatus::Queued);
10605        assert_eq!(
10606            after.attempts, 0,
10607            "losing the race is not an attempt at the task"
10608        );
10609        assert_eq!(after.last_error, None);
10610    }
10611
10612    #[test]
10613    fn the_status_file_round_trips_and_its_heartbeat_advances() {
10614        let dir = tempfile::tempdir().unwrap();
10615        let path = dir.path().join("daemon.json");
10616
10617        let mut status = Status::new();
10618        status.idle = false;
10619        status.completed = 7;
10620        status.current = vec![Current {
10621            worker: None,
10622            task: "20260902-000000-t111".to_owned(),
10623            run: "20260902-000001-r111".to_owned(),
10624        }];
10625        write_status_to(&path, &status).unwrap();
10626        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10627        assert_eq!(first.schema, SCHEMA);
10628        assert_eq!(first.pid, std::process::id());
10629        assert!(!first.idle);
10630        assert_eq!(first.completed, 7);
10631        assert_eq!(first.current, status.current);
10632        assert!(
10633            !path.with_extension("json.tmp").exists(),
10634            "the temp file is renamed, not left behind"
10635        );
10636
10637        std::thread::sleep(Duration::from_millis(5));
10638        status.updated_at = Timestamp::now();
10639        status.polls = 3;
10640        write_status_to(&path, &status).unwrap();
10641        let second: Status =
10642            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10643        assert!(
10644            second.updated_at > first.updated_at,
10645            "a reader can only detect staleness if the heartbeat moves"
10646        );
10647        assert_eq!(
10648            second.started_at, first.started_at,
10649            "the start time is not a heartbeat"
10650        );
10651        assert_eq!(second.polls, 3);
10652    }
10653
10654    #[test]
10655    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
10656        let dir = tempfile::tempdir().unwrap();
10657
10658        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
10659
10660        let mut status = Status::new();
10661        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
10662        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10663        let stale = read_status(dir.path()).unwrap();
10664        assert!(
10665            !stale.running(Timestamp::now()),
10666            "a minute without a heartbeat is a dead daemon, not a busy one"
10667        );
10668        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
10669
10670        status.updated_at = Timestamp::now();
10671        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10672        let fresh = read_status(dir.path()).unwrap();
10673        assert!(fresh.running(Timestamp::now()));
10674    }
10675
10676    #[test]
10677    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
10678        let dir = tempfile::tempdir().unwrap();
10679        let now = Timestamp::now();
10680        let mine = "20260903-080619-01c2";
10681
10682        assert!(
10683            !is_working_on(dir.path(), mine, now),
10684            "no status file means nobody is working on anything"
10685        );
10686
10687        let mut status = Status::new();
10688        status.current = vec![Current {
10689            worker: None,
10690            task: "20260903-080340-0167".to_owned(),
10691            run: mine.to_owned(),
10692        }];
10693        status.updated_at = now;
10694        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10695        assert!(is_working_on(dir.path(), mine, now));
10696        assert!(
10697            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
10698            "a daemon busy with one run is not working on another"
10699        );
10700
10701        // A killed daemon stops writing heartbeats but leaves the file behind
10702        // naming the run it died in. That run must not be undeletable forever.
10703        status.updated_at = now - jiff::SignedDuration::from_secs(600);
10704        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10705        assert!(
10706            !is_working_on(dir.path(), mine, now),
10707            "a stale heartbeat is a dead daemon, so its run is a leftover"
10708        );
10709    }
10710
10711    #[test]
10712    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
10713        let dir = tempfile::tempdir().unwrap();
10714        let now = Timestamp::now();
10715
10716        assert!(
10717            !is_working_on_short(dir.path(), "01c2", now),
10718            "no status file means nobody is working on anything"
10719        );
10720
10721        let mut status = Status::new();
10722        status.current = vec![Current {
10723            worker: None,
10724            task: "20260903-080340-0167".to_owned(),
10725            run: "20260903-080619-01c2".to_owned(),
10726        }];
10727        status.updated_at = now;
10728        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10729        assert!(
10730            is_working_on_short(dir.path(), "01c2", now),
10731            "the run's short id is the last block of its full id"
10732        );
10733        assert!(
10734            !is_working_on_short(dir.path(), "3cbf", now),
10735            "a daemon busy with one worktree bay is not working on another"
10736        );
10737    }
10738
10739    #[test]
10740    fn a_newer_status_file_still_yields_a_reading() {
10741        let dir = tempfile::tempdir().unwrap();
10742        // A field this build has never heard of must not turn the reading into
10743        // nothing at all; that is the whole reason the reader is permissive.
10744        std::fs::write(
10745            dir.path().join("daemon.json"),
10746            serde_json::json!({
10747                "schema": 2,
10748                "updated_at": Timestamp::now().to_string(),
10749                "idle": true,
10750                "surprise": { "nested": [1, 2, 3] },
10751            })
10752            .to_string(),
10753        )
10754        .unwrap();
10755
10756        let reading = read_status(dir.path()).expect("a forward-compatible read");
10757        assert!(reading.running(Timestamp::now()));
10758        assert!(reading.idle);
10759        assert!(reading.current.is_empty());
10760    }
10761
10762    #[test]
10763    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
10764        // A daemon started before `current` became a list keeps writing this
10765        // shape on every heartbeat until it is restarted. A rolling upgrade
10766        // - a newer `magi web` or `magi doctor` reading an older `magi
10767        // serve`'s heartbeat - must still see the run it is on, not "no
10768        // daemon" from a type mismatch failing the whole struct.
10769        let dir = tempfile::tempdir().unwrap();
10770        std::fs::write(
10771            dir.path().join("daemon.json"),
10772            serde_json::json!({
10773                "schema": 1,
10774                "pid": 4242,
10775                "updated_at": Timestamp::now().to_string(),
10776                "idle": false,
10777                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
10778                "completed": 3,
10779                "polls": 9,
10780            })
10781            .to_string(),
10782        )
10783        .unwrap();
10784
10785        let reading = read_status(dir.path()).expect("an older shape must still parse");
10786        assert!(reading.running(Timestamp::now()));
10787        assert_eq!(
10788            reading.current,
10789            vec![Current {
10790                worker: None,
10791                task: "20260902-140501-aaaa".to_owned(),
10792                run: "20260902-140502-bbbb".to_owned(),
10793            }]
10794        );
10795    }
10796
10797    #[test]
10798    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
10799        let dir = tempfile::tempdir().unwrap();
10800        std::fs::write(
10801            dir.path().join("daemon.json"),
10802            serde_json::json!({
10803                "schema": 1,
10804                "updated_at": Timestamp::now().to_string(),
10805                "idle": true,
10806                "current": null,
10807            })
10808            .to_string(),
10809        )
10810        .unwrap();
10811        let with_null = read_status(dir.path()).expect("null must still parse");
10812        assert!(with_null.current.is_empty());
10813
10814        std::fs::write(
10815            dir.path().join("daemon.json"),
10816            serde_json::json!({
10817                "schema": 1,
10818                "updated_at": Timestamp::now().to_string(),
10819                "idle": true,
10820            })
10821            .to_string(),
10822        )
10823        .unwrap();
10824        let absent = read_status(dir.path()).expect("a missing field must still parse");
10825        assert!(absent.current.is_empty());
10826    }
10827
10828    #[test]
10829    fn a_task_without_a_repository_runs_in_the_daemons_default() {
10830        let fallback = Path::new("/default");
10831        let mut blank = task();
10832        blank.repo = PathBuf::new();
10833        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
10834        let mut dot = task();
10835        dot.repo = PathBuf::from(".");
10836        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
10837        assert_eq!(
10838            repo_for(&task(), fallback),
10839            PathBuf::from("/repo"),
10840            "a task that names a repository keeps it"
10841        );
10842    }
10843
10844    #[test]
10845    fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
10846        let dir = tempfile::tempdir().unwrap();
10847        let repo = dir.path();
10848        let path = repo.join("explicit.toml");
10849        std::fs::write(
10850            &path,
10851            "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
10852        )
10853        .unwrap();
10854        let opts = Opts {
10855            config: Some(path),
10856            ..Opts::default()
10857        };
10858        let queue = Queue::at(repo.join("queue"));
10859        let mut new = task();
10860        queue.put(&mut new).unwrap();
10861        let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
10862        assert_eq!(
10863            resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
10864            BuildCache::Isolated
10865        );
10866
10867        let mut old = task();
10868        old.schema = 22;
10869        queue.put(&mut old).unwrap();
10870        let mut old = queue.get(&old.id).unwrap();
10871        let config = resolved(&old);
10872        assert_eq!(config.verify.build_cache, BuildCache::Shared);
10873        assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
10874        old.hold_manual(Some("wait".into()));
10875        queue.put(&mut old).unwrap();
10876
10877        let mut saved = queue.get(&old.id).unwrap();
10878        assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
10879        saved
10880            .overrides
10881            .as_mut()
10882            .unwrap()
10883            .merge_over(&crate::queue::RunOverrides {
10884                build_cache: Some(BuildCache::Isolated),
10885                ..Default::default()
10886            });
10887        queue.put(&mut saved).unwrap();
10888        assert_eq!(
10889            resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
10890            BuildCache::Isolated
10891        );
10892    }
10893
10894    #[test]
10895    fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
10896        let dir = tempfile::tempdir().unwrap();
10897        let path = dir.path().join("explicit.toml");
10898        let write = |verify: &str| {
10899            std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
10900        };
10901        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
10902        let opts = Opts {
10903            config: Some(path.clone()),
10904            ..Opts::default()
10905        };
10906        let mut task = task();
10907        task.set_urgent(true).unwrap();
10908        let resolved = |task: &Task| {
10909            prepare_for(dir.path(), &opts, task)
10910                .unwrap()
10911                .verify
10912                .build_cache
10913        };
10914        assert_eq!(resolved(&task), BuildCache::Isolated);
10915        task.change_build_cache(Some(BuildCache::Shared)).unwrap();
10916        assert_eq!(resolved(&task), BuildCache::Shared);
10917        task.change_build_cache(None).unwrap();
10918        assert_eq!(resolved(&task), BuildCache::Isolated);
10919        task.set_urgent(false).unwrap();
10920        assert_eq!(resolved(&task), BuildCache::Shared);
10921
10922        // Urgent work must never be the one stopped by isolation: with no
10923        // shared cache to wait behind, or with a verification command isolated
10924        // mode cannot run, an urgent task keeps the configured mode.
10925        task.set_urgent(true).unwrap();
10926        write("e2e = [\"npm test\"]\n");
10927        assert_eq!(resolved(&task), BuildCache::Shared);
10928        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
10929        assert_eq!(resolved(&task), BuildCache::Shared);
10930        // An explicit choice stays strict and is applied as asked.
10931        task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
10932        assert_eq!(resolved(&task), BuildCache::Isolated);
10933    }
10934
10935    #[test]
10936    fn task_implementers_edit_inherits_daemon_config_and_merge() {
10937        let dir = tempfile::tempdir().unwrap();
10938        let path = dir.path().join("explicit.toml");
10939        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
10940        let opts = Opts {
10941            config: Some(path),
10942            merge: Some("none".into()),
10943            ..Default::default()
10944        };
10945        let mut t = task();
10946        t.set_implementers(
10947            2,
10948            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10949                .unwrap(),
10950        )
10951        .unwrap();
10952        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10953        assert_eq!(cfg.graph.implementers, 2);
10954        assert_eq!(cfg.graph.judges, 1);
10955        assert_eq!(cfg.merge.mode, MergeMode::None);
10956        t.set_implementers(1, &cfg).unwrap();
10957        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10958        apply_task_implementers(&mut cfg, &t);
10959        assert_eq!(cfg.graph.implementers, 1);
10960        assert_eq!(cfg.graph.judges, 1);
10961        assert_eq!(cfg.merge.mode, MergeMode::None);
10962    }
10963
10964    #[test]
10965    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
10966        let dir = tempfile::tempdir().unwrap();
10967        let repo = dir.path().join("repo");
10968        std::fs::create_dir(&repo).unwrap();
10969        std::fs::write(
10970            repo.join("magi.toml"),
10971            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
10972        )
10973        .unwrap();
10974        let daemon_config = dir.path().join("daemon.toml");
10975        std::fs::write(
10976            &daemon_config,
10977            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
10978        )
10979        .unwrap();
10980        let opts = Opts {
10981            config: Some(daemon_config),
10982            merge: Some("pr".into()),
10983            ..Default::default()
10984        };
10985        let q = Queue::at(dir.path().join("queue"));
10986        let validation: Config =
10987            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10988                .unwrap();
10989        // No provenance field on legacy direct tasks: both shapes stay isolated.
10990        for record in ["{}", r#"{"candidates":2}"#] {
10991            let overrides = serde_json::from_str(record).unwrap();
10992            let filing = crate::direct::Filing {
10993                instruction: "work".into(),
10994                title: "direct".into(),
10995                repo: repo.clone(),
10996                source: crate::queue::Source::Human,
10997                solo: false,
10998                overrides,
10999                review_of: None,
11000                sources: Default::default(),
11001            };
11002            let filed =
11003                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
11004            let crate::direct::Filed::Standalone {
11005                mut task,
11006                claim: _claim,
11007            } = filed
11008            else {
11009                panic!("local filing")
11010            };
11011            let before = prepare_for(&repo, &opts, &task).unwrap();
11012            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
11013            assert_eq!(
11014                before.merge.mode,
11015                MergeMode::None,
11016                "daemon --merge must not leak"
11017            );
11018            for n in [2, 1, 2] {
11019                task.set_implementers(n, &validation).unwrap();
11020                q.put(&mut task).unwrap();
11021                task = q.get(&task.id).unwrap();
11022                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
11023                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
11024                apply_task_implementers(&mut cfg, &task);
11025                assert_eq!(cfg.graph.implementers, usize::from(n));
11026                assert_eq!(cfg.graph.judges, 2);
11027                assert_eq!(cfg.merge.mode, MergeMode::None);
11028            }
11029        }
11030    }
11031
11032    #[test]
11033    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
11034        let cfg: Config =
11035            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11036                .unwrap();
11037        let mut t = task();
11038        t.review_of = Some("review-target".into());
11039        t.hold_manual(Some("retry".into()));
11040        let mut previous = RunState::new(
11041            PathBuf::from("/repo"),
11042            "main".into(),
11043            "abc1234".into(),
11044            "review".into(),
11045            cfg.clone(),
11046        );
11047        previous.config.graph.implementers = 2;
11048        for count in [1, 3] {
11049            t.set_implementers(count, &cfg).unwrap();
11050            t.release();
11051            assert_eq!(t.review_of.as_deref(), Some("review-target"));
11052            for proposed in [
11053                Starter::Resume(previous.id.clone()),
11054                Starter::Review("recovery-target".into()),
11055            ] {
11056                assert_eq!(
11057                    starter_with_implementers(&t, Some(&previous), proposed),
11058                    Starter::Review("review-target".into())
11059                );
11060            }
11061            let mut configured = cfg.clone();
11062            apply_task_implementers(&mut configured, &t);
11063            assert_eq!(configured.graph.implementers, usize::from(count));
11064            assert_eq!(previous.config.graph.implementers, 2);
11065        }
11066    }
11067
11068    #[test]
11069    fn task_implementers_dispatch_and_resume_agree() {
11070        let mut t = task();
11071        let cfg: crate::config::Config =
11072            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11073                .unwrap();
11074        let mut run = RunState::new(
11075            PathBuf::from("/repo"),
11076            "main".into(),
11077            "abc1234".into(),
11078            "work".into(),
11079            cfg.clone(),
11080        );
11081        run.config.graph.implementers = 2;
11082        for n in [2, 1, 3, 2] {
11083            t.set_implementers(n, &cfg).unwrap();
11084            let mut dispatched = cfg.clone();
11085            apply_task_implementers(&mut dispatched, &t);
11086            assert_eq!(dispatched.graph.implementers, usize::from(n));
11087            assert_eq!(implementers_match(&t, &run), n == 2);
11088            for proposed in [
11089                Starter::Resume(run.id.clone()),
11090                Starter::Review("old-branch".into()),
11091            ] {
11092                let expected = if n == 2 {
11093                    proposed.clone()
11094                } else {
11095                    Starter::Start
11096                };
11097                assert_eq!(
11098                    starter_with_implementers(&t, Some(&run), proposed),
11099                    expected
11100                );
11101            }
11102            assert_eq!(
11103                run.config.graph.implementers, 2,
11104                "history must not be rewritten"
11105            );
11106        }
11107        t.solo = false;
11108        t.overrides = None;
11109        assert!(implementers_match(&t, &run));
11110    }
11111
11112    #[test]
11113    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
11114        // Three seats said out loud. What `solo` promises is one candidate
11115        // *whatever the config asks for*, so the contrast has to be a number
11116        // this test owns - it used to be `Config::default()`'s, which became
11117        // 1 when one implementation became the default and left the two
11118        // halves of this test asserting the same thing.
11119        let mut solo_cfg = Config::default();
11120        solo_cfg.graph.implementers = 3;
11121        let mut solo_task = task();
11122        solo_task.solo = true;
11123        apply_task_implementers(&mut solo_cfg, &solo_task);
11124        assert_eq!(solo_cfg.graph.implementers, 1);
11125
11126        let mut plain_cfg = Config::default();
11127        plain_cfg.graph.implementers = 3;
11128        let plain_task = task();
11129        assert!(!plain_task.solo);
11130        apply_task_implementers(&mut plain_cfg, &plain_task);
11131        assert_eq!(
11132            plain_cfg.graph.implementers, 3,
11133            "a task that did not ask to run alone keeps the config's candidates"
11134        );
11135    }
11136
11137    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
11138        QuotaLoss {
11139            cause: crate::agent::QuotaCause::UsageLimit,
11140            agent: String::new(),
11141            seat: seat.into(),
11142            node: "judge".into(),
11143            at: at.parse().unwrap(),
11144            reset: reset.map(str::to_string),
11145        }
11146    }
11147
11148    #[test]
11149    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
11150        let now = Timestamp::now();
11151        for reset in [None, Some("in 1h")] {
11152            let auth = crate::agent::Quota {
11153                cause: crate::agent::QuotaCause::Authentication,
11154                agent: "alpha".into(),
11155                reset: reset.map(str::to_owned),
11156            };
11157            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
11158            assert_eq!(cooldown_until(&[loss], now), None);
11159        }
11160    }
11161
11162    #[test]
11163    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
11164        let old: Vec<QuotaLoss> = (1..=4)
11165            .map(|i| {
11166                loss(
11167                    &format!("judge-{i}"),
11168                    "2026-09-23T05:23:00Z",
11169                    Some("2:40pm (Asia/Tokyo)"),
11170                )
11171            })
11172            .collect();
11173        let fresh = losses_this_attempt(&old, &old);
11174        assert!(fresh.is_empty());
11175        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
11176        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
11177    }
11178
11179    #[test]
11180    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
11181        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
11182        let now = Timestamp::now();
11183        let mut after = old.clone();
11184        after.push(loss("judge-2", &now.to_string(), None));
11185        let fresh = losses_this_attempt(&old, &after);
11186        assert_eq!(fresh, vec![after[1].clone()]);
11187        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
11188        assert_eq!(
11189            until,
11190            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
11191        );
11192    }
11193
11194    #[test]
11195    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
11196        // `recover_stall` removes judge-1's loss and the retry then hits quota
11197        // again: the vector is the same length, so an index diff sees nothing.
11198        let before = vec![
11199            loss("judge-1", "2026-09-23T05:23:00Z", None),
11200            loss("judge-2", "2026-09-23T05:24:00Z", None),
11201        ];
11202        let after = vec![
11203            loss("judge-2", "2026-09-23T05:24:00Z", None),
11204            loss("judge-1", "2026-09-24T01:00:00Z", None),
11205        ];
11206        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
11207    }
11208
11209    #[test]
11210    fn merge_overrides_are_parsed_or_refused() {
11211        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
11212        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
11213        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
11214        assert!(merge_mode("squash").is_err());
11215    }
11216
11217    #[test]
11218    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
11219        let now = Timestamp::now();
11220        let fallback = Duration::from_secs(300);
11221        let cap = Duration::from_secs(1800);
11222
11223        // No reset hint at all: the fallback.
11224        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
11225
11226        // A reset ten minutes out, well inside the cap: waited for exactly.
11227        let soon = now + jiff::SignedDuration::from_secs(600);
11228        assert_eq!(
11229            quota_wait(Some(soon), now, fallback, cap),
11230            Duration::from_secs(600)
11231        );
11232
11233        // A reset already in the past is not trusted: the fallback, not a
11234        // zero or negative wait that would spin the loop right back around.
11235        let past = now - jiff::SignedDuration::from_secs(60);
11236        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
11237
11238        // A reset further out than the cap is trusted for direction but not
11239        // for magnitude: a parsing slip must not sleep the loop for a day.
11240        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
11241        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
11242    }
11243
11244    #[test]
11245    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
11246        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11247
11248        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
11249        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
11250
11251        // Same clock reading, but it has already gone by today: read as
11252        // tomorrow's, since the CLI would not still be reporting a limit past
11253        // its own stated reset.
11254        let already_past =
11255            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
11256        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
11257
11258        assert!(
11259            parse_reset_hint("session limit reached", now, now).is_none(),
11260            "free text with no recognised shape is not guessed at"
11261        );
11262        assert!(
11263            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
11264            "an unresolvable zone name is not guessed at either"
11265        );
11266    }
11267
11268    #[test]
11269    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
11270        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11271
11272        let at = parse_reset_hint(
11273            "You've hit your usage limit. Visit \
11274             https://chatgpt.com/codex/settings/usage to purchase more \
11275             credits or try again at Sep 19th, 2026 5:10 PM.",
11276            now,
11277            now,
11278        )
11279        .expect("the codex reset wording is a recognised shape");
11280        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
11281
11282        // The month is explicit, so a date already earlier in the same
11283        // sentence-implied year than `now` is trusted as written rather than
11284        // rolled forward a year the way the bracketed shape rolls a
11285        // same-day clock reading to tomorrow.
11286        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
11287            .expect("an explicit year needs no rollover");
11288        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
11289
11290        assert!(
11291            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
11292            "a two-digit year is not the documented shape and is not guessed at"
11293        );
11294        assert!(
11295            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
11296            "a four-letter month name is not the documented three-letter abbreviation"
11297        );
11298        assert!(
11299            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
11300            "an explicit zone on the dated shape is a format nobody has \
11301             documented, and is refused rather than guessed at as UTC"
11302        );
11303    }
11304
11305    #[test]
11306    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
11307        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
11308        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
11309
11310        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
11311        assert_eq!(at.as_second() - recorded.as_second(), 3769);
11312
11313        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
11314        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
11315
11316        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
11317            assert!(
11318                parse_reset_hint(bad, now, recorded).is_none(),
11319                "{bad:?} must not be guessed at"
11320            );
11321        }
11322    }
11323
11324    /// A loop whose queue lives in a temp tree and whose poll interval is far
11325    /// longer than the test's patience, so anything that waits out a poll
11326    /// instead of noticing the stop fails rather than merely being slow.
11327    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
11328        let config = dir.join("magi.toml");
11329        std::fs::write(
11330            &config,
11331            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
11332        )
11333        .unwrap();
11334        let opts = Opts {
11335            poll: Duration::from_secs(30),
11336            config: Some(config),
11337            // The explicit fixture config keeps startup cleanup from reading
11338            // machine configuration. This fictional repository likewise
11339            // keeps any best-effort git cleanup away from this checkout.
11340            repo: dir.join("repo"),
11341            ..Opts::default()
11342        };
11343        // The status file goes in a directory that does not exist yet, so its
11344        // creation is itself evidence the loop published one. `worktrees`
11345        // must be just as fictional: the janitor reclaims worktrees under it
11346        // for real, and a test that let it fall through to
11347        // `crate::run::default_worktree_root()` would have it reclaim
11348        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
11349        // which is exactly what happened before this function took the
11350        // parameter at all.
11351        let home = dir.join("home");
11352        // These control-only fixtures do not launch native workers. Give the
11353        // independently tested maintenance services a fresh cadence receipt.
11354        let stamps = home.join("service-ticks");
11355        std::fs::create_dir_all(&stamps).unwrap();
11356        for service in ["waiter", "deputies", "release-watch"] {
11357            std::fs::write(
11358                stamps.join(service),
11359                Timestamp::now().as_second().to_string(),
11360            )
11361            .unwrap();
11362        }
11363        for operation in [
11364            "conductor",
11365            "maintenance",
11366            "housekeeping",
11367            "disk-pressure",
11368            "cache",
11369            "fetch",
11370            "chat-goals",
11371        ] {
11372            std::fs::write(
11373                stamps.join(format!("daemon-{operation}")),
11374                serde_json::to_vec(&Timestamp::now()).unwrap(),
11375            )
11376            .unwrap();
11377        }
11378        let worktrees = dir.join("wt");
11379        (
11380            opts,
11381            Queue::at(dir.join("queue")),
11382            home.join("daemon.json"),
11383            home,
11384            worktrees,
11385        )
11386    }
11387
11388    #[tokio::test]
11389    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
11390        let dir = tempfile::tempdir().unwrap();
11391        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11392        let mut waiting = task();
11393        waiting.repo = opts.repo.clone();
11394        waiting.hold_machine(crate::disk::gate(1, 100));
11395        waiting.mark_disk_capacity();
11396        waiting.attempts = 2;
11397        queue.put(&mut waiting).unwrap();
11398        let mut busy = task();
11399        busy.status = TaskStatus::Running;
11400        queue.put(&mut busy).unwrap();
11401        let payload = serde_json::to_value(ServiceWorker {
11402            opts,
11403            queue: queue.root().to_owned(),
11404            worktrees_root: worktrees,
11405            operation: "maintenance".into(),
11406        })
11407        .unwrap();
11408        run_service_worker(&home, payload.clone()).await.unwrap();
11409        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
11410        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11411        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
11412        run_service_worker(&home, payload).await.unwrap();
11413        assert!(
11414            crate::worker::active(&home).unwrap().is_empty(),
11415            "monitoring only queues; normal dispatch owns launches"
11416        );
11417        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11418    }
11419
11420    #[tokio::test]
11421    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
11422        let dir = tempfile::tempdir().unwrap();
11423        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11424        let cfg = Config::default();
11425        start_service(
11426            &home,
11427            &opts,
11428            &queue,
11429            &worktrees,
11430            "housekeeping",
11431            Some(&cfg),
11432            true,
11433        )
11434        .await
11435        .unwrap();
11436        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
11437        let read = |path: &Path| -> serde_json::Value {
11438            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
11439        };
11440        assert_eq!(read(&receipt)["detail"], "cadence not due");
11441        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
11442        start_service(
11443            &home,
11444            &opts,
11445            &queue,
11446            &worktrees,
11447            "housekeeping",
11448            Some(&cfg),
11449            true,
11450        )
11451        .await
11452        .unwrap();
11453        assert_eq!(
11454            read(&receipt)["detail"],
11455            "active work or runnable task queue"
11456        );
11457        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
11458        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
11459        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
11460        start_service(
11461            &home,
11462            &opts,
11463            &queue,
11464            &worktrees,
11465            "disk-pressure",
11466            Some(&cfg),
11467            false,
11468        )
11469        .await
11470        .unwrap();
11471        assert_eq!(
11472            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
11473            "no active work; idle housekeeping owns scan"
11474        );
11475        assert!(crate::worker::active(&home).unwrap().is_empty());
11476    }
11477
11478    #[tokio::test]
11479    async fn goal_observation_service_does_not_block_scheduler_decisions() {
11480        let dir = tempfile::tempdir().unwrap();
11481        let (opts, _, _, home, worktrees) = idle_loop(dir.path());
11482        let queue = Queue::at(home.join("queue"));
11483        let mut task = task();
11484        task.repo = opts.repo.clone();
11485        task.chat = Some("decision-chat".into());
11486        task.hold_machine(Some("waiting for a decision".into()));
11487        queue.put(&mut task).unwrap();
11488        let questions = Questions::at(home.join("questions"));
11489        let mut question = action_question(&task.id, ask::ChoiceAction::Done);
11490        question.node = crate::conduct::NODE.into();
11491        question.status = ask::QuestionStatus::Open;
11492        question.answer = None;
11493        question.answered_at = None;
11494        questions.put(&mut question).unwrap();
11495        questions
11496            .update(&question.id, |q| {
11497                q.answer(ask::Answer::Choice("resume で続行する".into()))
11498            })
11499            .unwrap();
11500
11501        let talks = crate::talk::Talks::at(home.join("talks"));
11502        let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
11503        decision_chat.pending = "Keep this unsent status question".into();
11504        talks.put(&mut decision_chat).unwrap();
11505        let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
11506        talk.goals.push(serde_json::from_value(serde_json::json!({
11507            "id":"goal","purpose":"follow the retained job","scope":"one task",
11508            "condition":{"description":"land the result","kind":"runs_merged"},
11509            "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
11510            "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
11511            "started":1,"wakes":1,"last_checked":null,"fingerprint":""
11512        })).unwrap());
11513        talks.put(&mut talk).unwrap();
11514
11515        // A retained service lease models an observation still waiting on its
11516        // external dependency. Admission must neither await nor repeat it.
11517        let directory = home.join("workers/jobs/abcdef");
11518        std::fs::create_dir_all(&directory).unwrap();
11519        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11520        crate::pr_head::try_lock_file(&lease).unwrap();
11521        let mut job = crate::worker::Job {
11522            id: "abcdef".into(),
11523            sequence: 1,
11524            kind: "daemon-service".into(),
11525            key: "service:daemon-chat-goals".into(),
11526            payload: serde_json::Value::Null,
11527            generation: "fixture".into(),
11528            version: None,
11529            status: crate::worker::Status::Running,
11530            result: None,
11531            pid: Some(std::process::id()),
11532            created_at: Timestamp::now().as_second() as u64,
11533            finished_at: None,
11534        };
11535        let record = directory.join("job.json");
11536        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11537        let status = Arc::new(Mutex::new(Status::new()));
11538        let stop = Stop::new();
11539        let mut dispatch = Box::pin(poll(
11540            &opts,
11541            &queue,
11542            &status,
11543            &home,
11544            &worktrees,
11545            &stop,
11546            DispatchLimits {
11547                max_concurrent: 1,
11548                pause_for_interrupts: false,
11549                recovery_cfg: None,
11550            },
11551        ));
11552        std::future::poll_fn(|cx| {
11553            assert!(dispatch.as_mut().poll(cx).is_pending());
11554            std::task::Poll::Ready(())
11555        })
11556        .await;
11557        assert!(lock(&status).polls > 0);
11558        let saved = queue.get(&task.id).unwrap();
11559        assert_eq!(saved.status, TaskStatus::Done);
11560        assert!(saved.action_applied(&question.id));
11561        assert!(
11562            talks
11563                .get("decision-chat")
11564                .unwrap()
11565                .pending
11566                .contains("Keep this unsent status question")
11567        );
11568        let goal = talks.get(&talk.id).unwrap().goals.remove(0);
11569        assert_eq!(goal.state, crate::chat_goal::State::Runnable);
11570        assert_eq!(
11571            goal.started,
11572            Some(1),
11573            "only the observation worker may reconcile its goal"
11574        );
11575        assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
11576
11577        stop.stop();
11578        dispatch.await.unwrap();
11579        job.status = crate::worker::Status::Finished;
11580        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
11581        drop(lease);
11582    }
11583
11584    #[test]
11585    fn a_stop_is_idempotent_and_once_set_stays_set() {
11586        let stop = Stop::new();
11587        assert!(!stop.stopped());
11588
11589        stop.stop();
11590        assert!(stop.stopped());
11591        stop.stop();
11592        assert!(stop.stopped(), "a second stop is not a toggle");
11593
11594        let shared = stop.clone();
11595        assert!(
11596            shared.stopped(),
11597            "a clone is the same stop; that is how the loop and its caller share one"
11598        );
11599    }
11600
11601    #[tokio::test]
11602    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
11603        for operation in ["conductor", "maintenance", "housekeeping"] {
11604            let dir = tempfile::tempdir().unwrap();
11605            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
11606            opts.once = true;
11607            opts.poll = Duration::from_millis(1);
11608            // This test exercises answer scheduling, not explicit discard:
11609            // ordinary Done requires a completed retained execution.
11610            let mut state = run_state(RunStatus::Ready);
11611            state.reserve_under(&home).unwrap();
11612            state.save_under(&home).unwrap();
11613            let mut task = task();
11614            task.runs.push(state.id.clone());
11615            queue.put(&mut task).unwrap();
11616            let claim = queue.claim(&task.id).unwrap();
11617
11618            // Model a live service holding the task's claim across the
11619            // scheduler's dispatch scan. No real subprocess or timed race.
11620            let directory = home.join("workers/jobs/abcdef");
11621            std::fs::create_dir_all(&directory).unwrap();
11622            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11623            crate::pr_head::try_lock_file(&lease).unwrap();
11624            let mut job = crate::worker::Job {
11625                id: "abcdef".into(),
11626                sequence: 1,
11627                kind: "daemon-service".into(),
11628                key: format!("service:daemon-{operation}"),
11629                payload: serde_json::Value::Null,
11630                generation: "fixture".into(),
11631                version: None,
11632                status: crate::worker::Status::Running,
11633                result: None,
11634                pid: Some(std::process::id()),
11635                created_at: Timestamp::now().as_second() as u64,
11636                finished_at: None,
11637            };
11638            let record = directory.join("job.json");
11639            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11640
11641            let status = Arc::new(Mutex::new(Status::new()));
11642            let stop = Stop::new();
11643            let mut drain = Box::pin(poll(
11644                &opts,
11645                &queue,
11646                &status,
11647                &home,
11648                &worktrees,
11649                &stop,
11650                DispatchLimits {
11651                    max_concurrent: 1,
11652                    pause_for_interrupts: false,
11653                    recovery_cfg: None,
11654                },
11655            ));
11656            std::future::poll_fn(|cx| {
11657                use std::future::Future;
11658                assert!(
11659                    drain.as_mut().poll(cx).is_pending(),
11660                    "--once must wait for {operation} to release its queue claim"
11661                );
11662                std::task::Poll::Ready(())
11663            })
11664            .await;
11665            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
11666
11667            // An answer arrives while the service still owns the claim. A
11668            // fresh scheduling pass must apply it before declaring idle.
11669            let questions = Questions::at(home.join("questions"));
11670            let mut q = action_question(&state.id, ask::ChoiceAction::Done);
11671            questions.put(&mut q).unwrap();
11672            drop(claim);
11673            // Model services that took longer than their cadence, without a
11674            // wall-clock sleep. The final scans must not respawn them even
11675            // though their receipts now permit another periodic invocation.
11676            let expired =
11677                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
11678            for service in [operation, "housekeeping"] {
11679                std::fs::write(
11680                    home.join("service-ticks").join(format!("daemon-{service}")),
11681                    &expired,
11682                )
11683                .unwrap();
11684            }
11685            job.status = crate::worker::Status::Finished;
11686            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11687            drop(lease);
11688            tokio::time::timeout(Duration::from_secs(2), drain)
11689                .await
11690                .expect("the settled service must allow the drain to finish")
11691                .unwrap();
11692            let after = queue.get(&task.id).unwrap();
11693            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
11694            assert!(after.action_applied(&q.id));
11695            for service in [operation, "housekeeping"] {
11696                assert_eq!(
11697                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
11698                        .unwrap(),
11699                    expired,
11700                    "the final once rescan must not restart {service}"
11701                );
11702            }
11703        }
11704    }
11705
11706    #[test]
11707    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
11708        let stop = Stop::new();
11709        stop.busy.store(1, Ordering::SeqCst);
11710        assert!(
11711            !stop.finishing(),
11712            "a busy loop nobody has asked to stop is just running"
11713        );
11714
11715        stop.stop();
11716        assert!(
11717            stop.finishing(),
11718            "a stop asked for mid-run has not landed until the run is settled"
11719        );
11720
11721        stop.busy.store(0, Ordering::SeqCst);
11722        assert!(
11723            !stop.finishing(),
11724            "once the run is settled the stop has landed and there is nothing to finish"
11725        );
11726    }
11727
11728    #[test]
11729    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
11730        let stop = Stop::new();
11731        stop.busy.store(2, Ordering::SeqCst);
11732        stop.stop();
11733        assert!(stop.finishing(), "two runs still in flight");
11734
11735        stop.busy.store(1, Ordering::SeqCst);
11736        assert!(
11737            stop.finishing(),
11738            "one run finished, but a sibling is still working"
11739        );
11740
11741        stop.busy.store(0, Ordering::SeqCst);
11742        assert!(
11743            !stop.finishing(),
11744            "the last run out is what actually lands the stop"
11745        );
11746    }
11747
11748    #[tokio::test]
11749    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
11750        let dir = tempfile::tempdir().unwrap();
11751        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11752        let stop = Stop::new();
11753        stop.stop();
11754
11755        let began = std::time::Instant::now();
11756        tokio::time::timeout(
11757            Duration::from_secs(2),
11758            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11759        )
11760        .await
11761        .expect("a stopped loop must return, not sit out its poll interval")
11762        .expect("the loop's own setup and teardown must not fail");
11763        assert!(
11764            began.elapsed() < opts.poll,
11765            "returned only after {:?}, which is a poll interval, not a stop",
11766            began.elapsed()
11767        );
11768    }
11769
11770    #[tokio::test]
11771    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
11772        let dir = tempfile::tempdir().unwrap();
11773        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11774        let stop = Stop::new();
11775
11776        // Asked for after the loop is already parked on its empty queue, which
11777        // is the case an operator tapping stop on a phone actually hits.
11778        let asker = {
11779            let stop = stop.clone();
11780            tokio::spawn(async move {
11781                tokio::time::sleep(Duration::from_millis(20)).await;
11782                stop.stop();
11783            })
11784        };
11785
11786        let began = std::time::Instant::now();
11787        tokio::time::timeout(
11788            Duration::from_secs(2),
11789            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11790        )
11791        .await
11792        .expect("a stop asked for while idle must wake the wait")
11793        .expect("the loop's own setup and teardown must not fail");
11794        asker.await.unwrap();
11795        assert!(
11796            began.elapsed() < opts.poll,
11797            "returned only after {:?}, so the stop waited on the sleep",
11798            began.elapsed()
11799        );
11800    }
11801
11802    #[tokio::test]
11803    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
11804        let dir = tempfile::tempdir().unwrap();
11805        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11806        let stop = Stop::new();
11807        stop.stop();
11808
11809        tokio::time::timeout(
11810            Duration::from_secs(2),
11811            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11812        )
11813        .await
11814        .expect("a stopped loop must return")
11815        .expect("the loop's own setup and teardown must not fail");
11816
11817        assert!(
11818            home.is_dir(),
11819            "the loop did publish a status file, so its removal is the teardown and not an absence"
11820        );
11821        assert!(
11822            !status_file.exists(),
11823            "a stopped loop clears its status file"
11824        );
11825        assert!(
11826            read_status(&home).is_none(),
11827            "a reader must see no daemon at all, not a heartbeat that merely stopped"
11828        );
11829    }
11830
11831    #[tokio::test]
11832    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
11833        let dir = tempfile::tempdir().unwrap();
11834        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11835
11836        let mut settled = RunState::new(
11837            dir.path().join("repo"),
11838            "main".to_owned(),
11839            "abc1234".to_owned(),
11840            "fixture".to_owned(),
11841            Config::default(),
11842        );
11843        settled.status = RunStatus::Ready;
11844        let run_dir = home.join("runs").join(&settled.id);
11845        std::fs::create_dir_all(&run_dir).unwrap();
11846        std::fs::write(
11847            run_dir.join("run.json"),
11848            serde_json::to_string_pretty(&settled).unwrap(),
11849        )
11850        .unwrap();
11851        let questions = Questions::at(home.join("questions"));
11852        let mut question = ask::Question::new(
11853            settled.id.clone(),
11854            "review".to_owned(),
11855            "reviewer-1".to_owned(),
11856            "Continue?".to_owned(),
11857            String::new(),
11858            Vec::new(),
11859        );
11860        questions.put(&mut question).unwrap();
11861
11862        run_service_worker(
11863            &home,
11864            serde_json::to_value(ServiceWorker {
11865                opts,
11866                queue: queue.root().to_path_buf(),
11867                worktrees_root: worktrees,
11868                operation: "housekeeping".to_owned(),
11869            })
11870            .unwrap(),
11871        )
11872        .await
11873        .unwrap();
11874
11875        assert_eq!(
11876            questions.get(&question.id).unwrap().status,
11877            ask::QuestionStatus::Abandoned,
11878            "the independent housekeeping worker settles ended-run questions"
11879        );
11880    }
11881
11882    #[test]
11883    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
11884        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11885
11886        assert!(
11887            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
11888            "never checked before: due at once"
11889        );
11890
11891        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
11892        assert!(
11893            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
11894            "well inside the interval: not due yet"
11895        );
11896
11897        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
11898        assert!(
11899            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
11900            "exactly at the edge: not yet due, same convention as `clean::due`"
11901        );
11902
11903        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11904        assert!(
11905            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
11906            "past the interval: due again"
11907        );
11908    }
11909
11910    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
11911    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
11912    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
11913    /// and the congestion test below both need, and must not drift apart.
11914    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
11915        let config = dir.join("magi.toml");
11916        // A literal (single-quoted) TOML string, not a basic one: the cache
11917        // path is a Windows path full of backslashes, and a basic string
11918        // would have TOML try to interpret `\U` (from `\Users\...`) as a
11919        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
11920        // `{{ vars.cache }}` rendering documents.
11921        std::fs::write(
11922            &config,
11923            format!(
11924                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
11925                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
11926                cache_dir.display()
11927            ),
11928        )
11929        .unwrap();
11930        Opts {
11931            config: Some(config),
11932            repo: dir.join("repo"),
11933            ..Opts::default()
11934        }
11935    }
11936
11937    #[tokio::test]
11938    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
11939        let dir = tempfile::tempdir().unwrap();
11940        let home = dir.path().join("home");
11941        let cache_dir = dir.path().join("cache");
11942        std::fs::create_dir_all(&cache_dir).unwrap();
11943        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11944        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11945
11946        // Nobody has asked this daemon to stop, which is the ordinary case;
11947        // the skip that a stop buys is asserted by its own test below.
11948        let running = Stop::new();
11949        let mut last_checked = None;
11950        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11951        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
11952            .await;
11953        assert_eq!(
11954            crate::disk::dir_size(&cache_dir),
11955            0,
11956            "over the cap on the first check ever: pruned at once, no idle queue required"
11957        );
11958        assert_eq!(last_checked, Some(t0));
11959
11960        // A fresh oversized file lands, but the next check is not due yet.
11961        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
11962        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
11963        maybe_prune_cache_between_runs(
11964            &opts.repo,
11965            &opts,
11966            &home,
11967            &running,
11968            &mut last_checked,
11969            too_soon,
11970        )
11971        .await;
11972        assert_eq!(
11973            crate::disk::dir_size(&cache_dir),
11974            10,
11975            "too soon since the last check: left alone rather than rescanned every call"
11976        );
11977        assert_eq!(
11978            last_checked,
11979            Some(t0),
11980            "an idle check does not reset the clock"
11981        );
11982
11983        // Once the interval elapses, the same oversized cache is caught again.
11984        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11985        maybe_prune_cache_between_runs(
11986            &opts.repo,
11987            &opts,
11988            &home,
11989            &running,
11990            &mut last_checked,
11991            due_again,
11992        )
11993        .await;
11994        assert_eq!(
11995            crate::disk::dir_size(&cache_dir),
11996            0,
11997            "due again: pruned back under the cap"
11998        );
11999    }
12000
12001    /// A stop must not queue behind housekeeping. The prune below is a
12002    /// synchronous walk of the whole cache with no await point in it, so a
12003    /// loop that entered it could not get back to its own `stopped()` test
12004    /// until the walk finished - and because no run is in flight at this
12005    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
12006    /// the stop had already landed. The idle branch has always made this same
12007    /// check before reaching `janitor`; the between-runs path makes it too.
12008    #[tokio::test]
12009    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
12010        let dir = tempfile::tempdir().unwrap();
12011        let home = dir.path().join("home");
12012        let cache_dir = dir.path().join("cache");
12013        std::fs::create_dir_all(&cache_dir).unwrap();
12014        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12015        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12016
12017        let stop = Stop::new();
12018        stop.stop();
12019        assert!(
12020            !stop.finishing(),
12021            "no run is in flight at a between-runs boundary, so nothing else \
12022             would tell the operator this stop had not taken effect yet"
12023        );
12024
12025        let mut last_checked = None;
12026        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12027        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
12028            .await;
12029        assert_eq!(
12030            crate::disk::dir_size(&cache_dir),
12031            10,
12032            "over its cap, and due for the first check ever, but a stop outranks \
12033             it: the cap is a standing policy the next start measures again"
12034        );
12035        assert_eq!(
12036            last_checked, None,
12037            "a check that never happened must not claim the interval"
12038        );
12039    }
12040
12041    /// A backlog must not starve cache pruning. The finite cache worker runs
12042    /// independently of queue drain and must not consume any task attempts.
12043    #[tokio::test]
12044    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
12045        let dir = tempfile::tempdir().unwrap();
12046        let cache_dir = dir.path().join("cache");
12047        std::fs::create_dir_all(&cache_dir).unwrap();
12048        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
12049
12050        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
12051        opts.poll = Duration::from_millis(20);
12052        opts.max_attempts = 1_000;
12053
12054        let queue = Queue::at(dir.path().join("queue"));
12055        for i in 0..128 {
12056            let mut task = Task::new(
12057                format!("queued work {i}"),
12058                format!("queued work {i}"),
12059                opts.repo.clone(),
12060                Source::Human,
12061            );
12062            queue.put(&mut task).unwrap();
12063        }
12064
12065        let home = dir.path().join("home");
12066        let worktrees = dir.path().join("wt");
12067        run_service_worker(
12068            &home,
12069            serde_json::to_value(ServiceWorker {
12070                opts,
12071                queue: queue.root().to_path_buf(),
12072                worktrees_root: worktrees,
12073                operation: "cache".to_owned(),
12074            })
12075            .unwrap(),
12076        )
12077        .await
12078        .unwrap();
12079        let after = queue.list();
12080        assert_eq!(after.len(), 128);
12081        assert!(
12082            after
12083                .iter()
12084                .all(|task| task.status.runnable() && task.attempts == 0)
12085        );
12086
12087        assert_eq!(
12088            crate::disk::dir_size(&cache_dir),
12089            0,
12090            "an oversized cache must not be left to grow unboundedly just because the \
12091             queue kept the loop busy the whole time"
12092        );
12093    }
12094
12095    #[test]
12096    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
12097        let dir = tempfile::tempdir().unwrap();
12098        let queue = Queue::at(dir.path().join("queue"));
12099        let questions = Questions::at(dir.path().join("questions"));
12100        let mut task = task();
12101        queue.put(&mut task).unwrap();
12102
12103        let mut task_question = ask::Question::new(
12104            task.id.clone(),
12105            crate::conduct::NODE.to_owned(),
12106            "conduct".to_owned(),
12107            "Which backend?".to_owned(),
12108            String::new(),
12109            Vec::new(),
12110        );
12111        questions.put(&mut task_question).unwrap();
12112        task.block(vec![task_question.id.clone()], None);
12113        queue.put(&mut task).unwrap();
12114
12115        let mut run_question = ask::Question::new(
12116            "20260101-000000-run1".to_owned(),
12117            "review".to_owned(),
12118            "reviewer-1".to_owned(),
12119            "Run question".to_owned(),
12120            String::new(),
12121            Vec::new(),
12122        );
12123        questions.put(&mut run_question).unwrap();
12124
12125        // A question from another node whose `run` happens to equal this
12126        // task's id — the same field, filled in for an unrelated reason. Only
12127        // `crate::conduct::NODE` questions use `run` as a task id; this one
12128        // must never be touched by this reconciliation, even after release.
12129        let mut coincidental = ask::Question::new(
12130            task.id.clone(),
12131            "review".to_owned(),
12132            "reviewer-1".to_owned(),
12133            "Unrelated review question".to_owned(),
12134            String::new(),
12135            Vec::new(),
12136        );
12137        questions.put(&mut coincidental).unwrap();
12138
12139        reconcile_task_questions(&queue, &questions);
12140        assert!(questions.get(&task_question.id).unwrap().status.open());
12141        assert!(questions.get(&run_question.id).unwrap().status.open());
12142        assert!(questions.get(&coincidental.id).unwrap().status.open());
12143
12144        task.release();
12145        queue.put(&mut task).unwrap();
12146        reconcile_task_questions(&queue, &questions);
12147        assert_eq!(
12148            questions.get(&task_question.id).unwrap().status,
12149            ask::QuestionStatus::Abandoned
12150        );
12151        assert!(
12152            questions.get(&run_question.id).unwrap().status.open(),
12153            "run questions remain the run janitor's responsibility"
12154        );
12155        assert!(
12156            questions.get(&coincidental.id).unwrap().status.open(),
12157            "a non-conductor question must not be abandoned just because its \
12158             run id coincides with a task id"
12159        );
12160    }
12161
12162    #[test]
12163    fn a_freshly_started_running_task_is_never_stalled() {
12164        let dir = tempfile::tempdir().unwrap();
12165        let mut t = task();
12166        t.start("run-1".to_owned());
12167        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
12168        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
12169        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
12170    }
12171
12172    #[test]
12173    fn a_long_running_task_with_no_live_daemon_is_stalled() {
12174        let dir = tempfile::tempdir().unwrap();
12175        let mut t = task();
12176        t.start("run-1".to_owned());
12177        t.updated_at = Timestamp::now()
12178            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12179        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
12180        assert_eq!(
12181            stalled_tasks(
12182                &Queue::at(dir.path().join("q")),
12183                dir.path(),
12184                Timestamp::now()
12185            )
12186            .len(),
12187            0,
12188            "the task was never written to this queue"
12189        );
12190    }
12191
12192    #[test]
12193    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
12194        let dir = tempfile::tempdir().unwrap();
12195        let mut t = task();
12196        t.id = "20260903-080340-0167".to_owned();
12197        t.start("20260903-080619-01c2".to_owned());
12198        t.updated_at = Timestamp::now()
12199            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12200
12201        let mut status = Status::new();
12202        status.current = vec![Current {
12203            worker: None,
12204            task: t.id.clone(),
12205            run: "20260903-080619-01c2".to_owned(),
12206        }];
12207        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12208
12209        assert!(
12210            !is_stalled(&t, dir.path(), Timestamp::now()),
12211            "a live daemon's own heartbeat rules out stalled, however long the task has run"
12212        );
12213    }
12214
12215    /// Rewrite a task's `updated_at` on disk directly, bypassing
12216    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
12217    /// a fixture look like it has genuinely been `running` for a while.
12218    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
12219        let path = queue.path_of(id);
12220        let body = std::fs::read_to_string(&path).unwrap();
12221        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
12222        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
12223        v["updated_at"] = serde_json::Value::String(old.to_string());
12224        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
12225    }
12226
12227    #[test]
12228    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
12229        // The realistic `poll()` ordering, not `is_stalled` in isolation:
12230        // `reclaim_orphaned_running` runs first, on every poll, and settles
12231        // any `running` task whose claim it can actually take. For most
12232        // crashes that is immediate - a dead pid is proof enough for
12233        // `sweep_stale_claims` to drop the lock the same tick, and the very
12234        // next claim attempt succeeds. But a lock whose pid cannot be parsed
12235        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
12236        // `sweep_stale_claims`'s own doc), so the lock - and the claim
12237        // failure behind it - can legitimately outlive many polls. This is
12238        // exactly the gap `stalled_tasks` exists to surface well before that
12239        // six-hour sweep would: reclaim leaves the task `running`, and it
12240        // must still reach the conductor as stalled.
12241        let dir = tempfile::tempdir().unwrap();
12242        let queue = Queue::at(dir.path().join("queue"));
12243        let home = dir.path().join("home");
12244
12245        let mut t = task();
12246        t.id = "20260101-000001-lock".to_owned();
12247        t.start("run-1".to_owned());
12248        queue.put(&mut t).unwrap();
12249        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12250        std::fs::write(
12251            dir.path().join("queue").join(format!("{}.lock", t.id)),
12252            "not a pid",
12253        )
12254        .unwrap();
12255
12256        let now = Timestamp::now();
12257        assert!(
12258            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
12259            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
12260             and reclaim must leave the task alone"
12261        );
12262        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
12263
12264        let stalled = stalled_tasks(&queue, &home, now);
12265        assert_eq!(
12266            stalled.len(),
12267            1,
12268            "reclaim's inability to claim it yet must not hide it from the conductor"
12269        );
12270        assert_eq!(stalled[0].id, t.id);
12271    }
12272
12273    #[test]
12274    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
12275        let dir = tempfile::tempdir().unwrap();
12276        crate::run::set_home(dir.path().join("run-home"));
12277        let queue = Queue::at(dir.path().join("queue"));
12278        let home = dir.path().join("home");
12279        let questions = Questions::at(dir.path().join("questions"));
12280
12281        let mut t = task();
12282        t.id = "20260101-000003-dead".to_owned();
12283        t.start("missing-run".to_owned());
12284        queue.put(&mut t).unwrap();
12285        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12286
12287        // This is the real poll ordering: retain the deterministic stalled
12288        // input before a claim proves the owner is gone and reclaims it.
12289        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12290        assert_eq!(
12291            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
12292            [&t.id]
12293        );
12294        assert_eq!(
12295            reclaim_orphaned_running(&queue, 2, &Default::default()),
12296            [t.id.clone()]
12297        );
12298        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12299
12300        // Reclaim drops its guard before conductor decisions are applied, so
12301        // the decision for the captured stalled input has a real write path.
12302        crate::conduct::apply(
12303            &queue,
12304            &questions,
12305            &crate::conduct::Verdict {
12306                decisions: vec![crate::conduct::Decision {
12307                    id: t.id.clone(),
12308                    recovery: Some(crate::conduct::Recovery::Requeue),
12309                    ..crate::conduct::Decision::default()
12310                }],
12311            },
12312        )
12313        .unwrap();
12314        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12315    }
12316
12317    #[test]
12318    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
12319        let dir = tempfile::tempdir().unwrap();
12320        let queue = Queue::at(dir.path().join("queue"));
12321        let home = dir.path().join("home");
12322
12323        let mut fresh = task();
12324        fresh.id = "20260101-000001-aaaa".to_owned();
12325        fresh.start("run-1".to_owned());
12326        queue.put(&mut fresh).unwrap();
12327
12328        let mut old = task();
12329        old.id = "20260101-000002-bbbb".to_owned();
12330        old.start("run-2".to_owned());
12331        queue.put(&mut old).unwrap();
12332        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
12333
12334        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12335        assert_eq!(stalled.len(), 1);
12336        assert_eq!(stalled[0].id, old.id);
12337    }
12338
12339    #[test]
12340    fn queued_and_finished_task_views_partition_by_status() {
12341        let dir = tempfile::tempdir().unwrap();
12342        let queue = Queue::at(dir.path().join("queue"));
12343
12344        let mut queued = task();
12345        queued.id = "20260101-000001-aaaa".to_owned();
12346        queue.put(&mut queued).unwrap();
12347
12348        let mut failed = task();
12349        failed.id = "20260101-000002-bbbb".to_owned();
12350        failed.start("run-1".to_owned());
12351        failed.fail("gate red", 5);
12352        queue.put(&mut failed).unwrap();
12353
12354        let mut held = task();
12355        held.id = "20260101-000003-cccc".to_owned();
12356        held.hold_machine(None);
12357        queue.put(&mut held).unwrap();
12358
12359        let mut running = task();
12360        running.id = "20260101-000004-dddd".to_owned();
12361        running.start("run-2".to_owned());
12362        queue.put(&mut running).unwrap();
12363
12364        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
12365        assert_eq!(queued_ids, [queued.id.clone()]);
12366
12367        let mut finished_ids: Vec<String> =
12368            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
12369        finished_ids.sort_unstable();
12370        let mut want = vec![failed.id.clone(), held.id.clone()];
12371        want.sort_unstable();
12372        assert_eq!(finished_ids, want);
12373    }
12374
12375    #[test]
12376    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
12377        for short in [false, true] {
12378            let dir = tempfile::tempdir().unwrap();
12379            let queue = Queue::at(dir.path().join("queue"));
12380            let questions = ask::Questions::at(dir.path().join("questions"));
12381            let mut running = task();
12382            running.id = "20261013-192213-feb2".into();
12383            running.start("existing-run".into());
12384            queue.put(&mut running).unwrap();
12385            let mut middle = task();
12386            middle.id = "20261013-193611-ca5b".into();
12387            middle.block(
12388                vec![if short {
12389                    "feb2".into()
12390                } else {
12391                    running.id.clone()
12392                }],
12393                None,
12394            );
12395            queue.put(&mut middle).unwrap();
12396            let mut waiting = task();
12397            waiting.id = "20261013-202849-ee37".into();
12398            waiting.block(
12399                vec![if short {
12400                    "ca5b".into()
12401                } else {
12402                    middle.id.clone()
12403                }],
12404                Some("wait for implementation".into()),
12405            );
12406            queue.put(&mut waiting).unwrap();
12407            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
12408            let inv = crate::blockers::Inventory::load(&queue, &questions);
12409            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
12410            assert!(inv.stuck().is_empty());
12411            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12412            assert!(report.quarantined.is_empty());
12413            assert!(report.asked.is_empty());
12414            resolve_blockers(&queue, &questions);
12415            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12416            assert!(questions.list().is_empty());
12417            // Finishing the transitive prerequisite alone does not satisfy
12418            // the task's direct dependency.
12419            running.succeed(CompletionContext::new(
12420                CompletionActor::DaemonSettle,
12421                None,
12422                dir.path(),
12423                &running,
12424            ));
12425            queue.put(&mut running).unwrap();
12426            resolve_blockers(&queue, &questions);
12427            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
12428            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12429            middle = queue.get(&middle.id).unwrap();
12430            middle.succeed(CompletionContext::new(
12431                CompletionActor::DaemonSettle,
12432                None,
12433                dir.path(),
12434                &middle,
12435            ));
12436            queue.put(&mut middle).unwrap();
12437            resolve_blockers(&queue, &questions);
12438            let after = queue.get(&waiting.id).unwrap();
12439            assert_eq!(after.status, TaskStatus::Queued);
12440            assert!(after.blocked_by.is_empty());
12441            assert_eq!(after.instruction, waiting.instruction);
12442        }
12443    }
12444
12445    #[test]
12446    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
12447        for future_schema in [false, true] {
12448            let name = "20261013-193611-ca5b";
12449            let mut future = task();
12450            future.id = name.into();
12451            future.schema = crate::queue::SCHEMA + 1;
12452            let contents = if future_schema {
12453                serde_json::to_string(&future).unwrap()
12454            } else {
12455                "corrupt".into()
12456            };
12457            let dir = tempfile::tempdir().unwrap();
12458            let queue = Queue::at(dir.path().join("queue"));
12459            let questions = ask::Questions::at(dir.path().join("questions"));
12460            let mut waiting = task();
12461            waiting.id = "20261013-202849-ee37".into();
12462            waiting.block(vec!["ca5b".into()], None);
12463            queue.put(&mut waiting).unwrap();
12464            std::fs::write(queue.path_of(name), contents).unwrap();
12465            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
12466            assert!(
12467                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
12468            );
12469            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12470            assert!(report.asked.is_empty());
12471            resolve_blockers(&queue, &questions);
12472            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12473            assert!(questions.list().is_empty());
12474        }
12475        let dir = tempfile::tempdir().unwrap();
12476        let queue = Queue::at(dir.path().join("queue"));
12477        let questions = ask::Questions::at(dir.path().join("questions"));
12478        let mut waiting = task();
12479        waiting.id = "20261013-202849-ee37".into();
12480        waiting.block(vec!["ca5b".into()], None);
12481        queue.put(&mut waiting).unwrap();
12482        let mut done = task();
12483        done.id = "20261013-193611-ca5b".into();
12484        done.succeed(CompletionContext::new(
12485            CompletionActor::Cli,
12486            None,
12487            dir.path(),
12488            &done,
12489        ));
12490        queue.put(&mut done).unwrap();
12491        // An unreadable second match must not disappear from uniqueness
12492        // checks just because Queue::list skips it.
12493        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
12494        assert!(queue.get("ca5b").is_err());
12495        assert_eq!(
12496            crate::queue::dependency(&queue, &questions, "ca5b"),
12497            crate::queue::Dependency::Ambiguous
12498        );
12499        resolve_blockers(&queue, &questions);
12500        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12501        assert!(report.asked.is_empty());
12502        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12503        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
12504    }
12505
12506    #[test]
12507    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
12508        for held in [false, true] {
12509            for question in [false, true] {
12510                for reference in ["ca5b", "20261013-193611-ca5b"] {
12511                    let dir = tempfile::tempdir().unwrap();
12512                    let queue = Queue::at(dir.path().join("queue"));
12513                    let questions = ask::Questions::at(dir.path().join("questions"));
12514                    let mut prerequisite = task();
12515                    prerequisite.id = "20261013-193611-ca5b".into();
12516                    prerequisite.start("existing-run".into());
12517                    queue.put(&mut prerequisite).unwrap();
12518                    let mut waiting = task();
12519                    waiting.id = "20261013-202849-ee37".into();
12520                    if held {
12521                        waiting.hold_machine(Some("waiting for separate consent".into()));
12522                    }
12523                    queue.put(&mut waiting).unwrap();
12524                    let reason = "Deleting saved data requires separate owner consent";
12525                    crate::conduct::apply(
12526                        &queue,
12527                        &questions,
12528                        &crate::conduct::Verdict {
12529                            decisions: vec![crate::conduct::Decision {
12530                                id: waiting.id.clone(),
12531                                blocked_by: vec![reference.into()],
12532                                question: question.then(|| "May the saved data be deleted?".into()),
12533                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
12534                                reason: Some(reason.into()),
12535                                ..crate::conduct::Decision::default()
12536                            }],
12537                        },
12538                    )
12539                    .unwrap();
12540                    let before = queue.get(&waiting.id).unwrap();
12541                    if question {
12542                        assert_eq!(before.status, TaskStatus::Blocked);
12543                        let q = questions.get(&before.blocked_by[0]).unwrap();
12544                        assert_eq!(q.summary, "May the saved data be deleted?");
12545                        assert!(q.status.open());
12546                    } else {
12547                        assert_eq!(before.status, TaskStatus::Held);
12548                        let recorded_reason = before.hold_reason.as_deref().unwrap();
12549                        assert!(recorded_reason.starts_with(reason));
12550                        if held {
12551                            assert!(recorded_reason.contains("waiting for separate consent"));
12552                        }
12553                    }
12554                    prerequisite.succeed(CompletionContext::new(
12555                        CompletionActor::DaemonSettle,
12556                        None,
12557                        dir.path(),
12558                        &prerequisite,
12559                    ));
12560                    queue.put(&mut prerequisite).unwrap();
12561                    resolve_blockers(&queue, &questions);
12562                    let after = queue.get(&waiting.id).unwrap();
12563                    assert_eq!(after.status, before.status);
12564                    assert_eq!(after.blocked_by, before.blocked_by);
12565                    assert_eq!(after.hold_reason, before.hold_reason);
12566                    assert_eq!(after.instruction, waiting.instruction);
12567                    if question {
12568                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
12569                    }
12570                    assert!(
12571                        queue.next_runnable().is_none(),
12572                        "dependency completion is not consent"
12573                    );
12574                }
12575            }
12576        }
12577    }
12578
12579    #[test]
12580    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
12581        let dir = tempfile::tempdir().unwrap();
12582        let queue = Queue::at(dir.path().join("queue"));
12583        let questions = ask::Questions::at(dir.path().join("questions"));
12584
12585        let mut dep = task();
12586        dep.id = "20260101-000001-dep0".to_owned();
12587        dep.succeed(CompletionContext::new(
12588            CompletionActor::DaemonSettle,
12589            None,
12590            dir.path(),
12591            &dep,
12592        ));
12593        queue.put(&mut dep).unwrap();
12594
12595        let mut still_going = task();
12596        still_going.id = "20260101-000002-dep1".to_owned();
12597        queue.put(&mut still_going).unwrap();
12598
12599        let mut blocked = task();
12600        blocked.id = "20260101-000003-main".to_owned();
12601        blocked.block(
12602            vec![dep.id.clone(), still_going.id.clone()],
12603            Some("waits on both".to_owned()),
12604        );
12605        queue.put(&mut blocked).unwrap();
12606
12607        resolve_blockers(&queue, &questions);
12608
12609        let after = queue.get(&blocked.id).unwrap();
12610        assert_eq!(
12611            after.status,
12612            TaskStatus::Blocked,
12613            "one dependency is still outstanding"
12614        );
12615        assert_eq!(after.blocked_by, [still_going.id.clone()]);
12616    }
12617
12618    #[test]
12619    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
12620        let dir = tempfile::tempdir().unwrap();
12621        let queue = Queue::at(dir.path().join("queue"));
12622        let questions = ask::Questions::at(dir.path().join("questions"));
12623
12624        let mut q = crate::ask::Question::new(
12625            "20260101-000001-main".to_owned(),
12626            crate::conduct::NODE.to_owned(),
12627            "conduct".to_owned(),
12628            "Which backend?".to_owned(),
12629            String::new(),
12630            Vec::new(),
12631        );
12632        questions.put(&mut q).unwrap();
12633        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
12634            .unwrap();
12635        questions.put(&mut q).unwrap();
12636
12637        let mut blocked = task();
12638        blocked.id = "20260101-000001-main".to_owned();
12639        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
12640        queue.put(&mut blocked).unwrap();
12641
12642        resolve_blockers(&queue, &questions);
12643
12644        let after = queue.get(&blocked.id).unwrap();
12645        assert_eq!(
12646            after.status,
12647            TaskStatus::Queued,
12648            "the only blocker resolved"
12649        );
12650        assert_eq!(after.answers.len(), 1);
12651        assert_eq!(after.answers[0].question, "Which backend?");
12652        assert_eq!(after.answers[0].answer, "SQLite");
12653
12654        // And the run this task starts next is told about it.
12655        let instruction = instruction_for(&after);
12656        assert!(instruction.contains("Which backend?"));
12657        assert!(instruction.contains("SQLite"));
12658    }
12659
12660    #[test]
12661    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
12662        let dir = tempfile::tempdir().unwrap();
12663        let queue = Queue::at(dir.path().join("queue"));
12664        let questions = ask::Questions::at(dir.path().join("questions"));
12665
12666        let mut q = crate::ask::Question::new(
12667            "20260101-000001-main".to_owned(),
12668            crate::conduct::NODE.to_owned(),
12669            "conduct".to_owned(),
12670            "Is the setup done?".to_owned(),
12671            String::new(),
12672            Vec::new(),
12673        );
12674        q.abandon("no answer within 60s of asking");
12675        questions.put(&mut q).unwrap();
12676
12677        let mut blocked = task();
12678        blocked.id = "20260101-000001-main".to_owned();
12679        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
12680        queue.put(&mut blocked).unwrap();
12681
12682        resolve_blockers(&queue, &questions);
12683
12684        let after = queue.get(&blocked.id).unwrap();
12685        assert_eq!(
12686            after.status,
12687            TaskStatus::Held,
12688            "never left blocked on nothing"
12689        );
12690        assert!(!after.operator_held(), "a machine hold, for triage");
12691        assert!(
12692            after
12693                .hold_reason
12694                .as_deref()
12695                .unwrap_or_default()
12696                .contains("went unanswered")
12697        );
12698    }
12699
12700    #[test]
12701    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
12702        // Reproduces the reported bug (task 3958): a task held out of
12703        // attempts, blocked on a `crate::conduct` follow-up question, must
12704        // come back `held` once that question is answered - never `queued`,
12705        // whatever the answer said - or it silently re-enters the
12706        // competition queue with its attempts already exhausted.
12707        let dir = tempfile::tempdir().unwrap();
12708        let queue = Queue::at(dir.path().join("queue"));
12709        let questions = ask::Questions::at(dir.path().join("questions"));
12710
12711        let mut q = crate::ask::Question::new(
12712            "20260101-000001-main".to_owned(),
12713            crate::conduct::NODE.to_owned(),
12714            "conduct".to_owned(),
12715            "How should this be handled?".to_owned(),
12716            String::new(),
12717            Vec::new(),
12718        );
12719        questions.put(&mut q).unwrap();
12720        q.answer(crate::ask::Answer::Text(
12721            "leave it held, a human will look at it later".to_owned(),
12722        ))
12723        .unwrap();
12724        questions.put(&mut q).unwrap();
12725
12726        let mut held = task();
12727        held.id = "20260101-000001-main".to_owned();
12728        held.hold_machine(Some("out of attempts".to_owned()));
12729        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
12730        queue.put(&mut held).unwrap();
12731
12732        resolve_blockers(&queue, &questions);
12733
12734        let after = queue.get(&held.id).unwrap();
12735        assert_eq!(after.status, TaskStatus::Held);
12736        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
12737        assert_eq!(
12738            after.answers[0].answer,
12739            "leave it held, a human will look at it later"
12740        );
12741    }
12742
12743    #[test]
12744    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
12745        let dir = tempfile::tempdir().unwrap();
12746        let queue = Queue::at(dir.path().join("queue"));
12747        let questions = ask::Questions::at(dir.path().join("questions"));
12748        let mut dep = task();
12749        dep.id = "20260101-000001-gone".to_owned();
12750        queue.put(&mut dep).unwrap();
12751        let mut blocked = task();
12752        blocked.id = "20260101-000003-main".to_owned();
12753        blocked.block(vec![dep.id.clone()], None);
12754        queue.put(&mut blocked).unwrap();
12755
12756        // Claimed, so `remove` cannot rewrite it and the resolver must.
12757        let claim = queue.claim(&blocked.id).unwrap();
12758        queue.remove(&dep.id, false, &questions).unwrap();
12759        drop(claim);
12760        resolve_blockers(&queue, &questions);
12761
12762        let after = queue.get(&blocked.id).unwrap();
12763        assert_eq!(after.status, TaskStatus::Queued);
12764        assert!(after.blocked_by.is_empty());
12765    }
12766
12767    #[test]
12768    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
12769        // Reproduces the reported bug: a task blocked on a task id that was
12770        // removed (`magi task rm`, or deleted by hand) can never see that id
12771        // reach `Done`, so the ordinary per-id loop has nothing to notice and
12772        // would otherwise leave the task `blocked` forever with no way for an
12773        // operator to find out why.
12774        let dir = tempfile::tempdir().unwrap();
12775        let queue = Queue::at(dir.path().join("queue"));
12776        let questions = ask::Questions::at(dir.path().join("questions"));
12777
12778        let mut still_going = task();
12779        still_going.id = "20260101-000002-dep1".to_owned();
12780        queue.put(&mut still_going).unwrap();
12781
12782        let mut blocked = task();
12783        blocked.id = "20260101-000003-main".to_owned();
12784        blocked.block(
12785            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
12786            Some("waits on both".to_owned()),
12787        );
12788        queue.put(&mut blocked).unwrap();
12789
12790        resolve_blockers(&queue, &questions);
12791
12792        let after = queue.get(&blocked.id).unwrap();
12793        assert_eq!(
12794            after.status,
12795            TaskStatus::Held,
12796            "a missing dependency must not leave the task blocked forever"
12797        );
12798        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
12799        assert!(after.blocked_by.is_empty());
12800        let reason = after.hold_reason.as_deref().unwrap_or_default();
12801        assert!(
12802            reason.contains("20260101-000001-gone"),
12803            "the missing id must be named so an operator can tell what happened: {reason}"
12804        );
12805        assert!(
12806            reason.contains(&still_going.id),
12807            "the still-valid dependency must not silently vanish from the record: {reason}"
12808        );
12809    }
12810
12811    #[test]
12812    fn instruction_for_is_unchanged_without_any_answers() {
12813        let t = task();
12814        assert_eq!(instruction_for(&t), t.instruction);
12815    }
12816
12817    #[test]
12818    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
12819        let dir = tempfile::tempdir().unwrap();
12820        let q = Queue::at(dir.path().join("queue"));
12821        let src = dir.path().join("shot.png");
12822        std::fs::write(&src, "x").unwrap();
12823        let mut t = task();
12824        q.attach(&mut t, &[src]).unwrap();
12825        let paths = task_attachments(&q, &t).unwrap();
12826        assert_eq!(paths.len(), 1);
12827        assert!(paths[0].is_absolute() && paths[0].is_file());
12828        std::fs::remove_file(&paths[0]).unwrap();
12829        let err = task_attachments(&q, &t).unwrap_err().to_string();
12830        assert!(err.contains("shot.png"), "{err}");
12831    }
12832
12833    #[tokio::test]
12834    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
12835        let dir = tempfile::tempdir().unwrap();
12836        let queue_path = dir.path().join("queue");
12837        let queue = Queue::at(queue_path.clone());
12838        let mut t = task();
12839        t.source = Source::Agent {
12840            run: "originating-chat".into(),
12841            node: crate::queue::CHAT_NODE.into(),
12842        };
12843        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
12844            stage: "config-fetch",
12845            target: "origin/main".into(),
12846        });
12847        record_config_failure(&mut t, &fetch);
12848        t.hold_machine(Some(format!("{fetch:#}")));
12849        let fetch_key = t.chat_notice_due().unwrap();
12850        t.chat_notices.push(fetch_key.clone());
12851        queue.put(&mut t).unwrap();
12852
12853        let queue = Queue::at(queue_path);
12854        let mut t = queue.get(&t.id).unwrap();
12855        let a = dir.path().join("a.toml");
12856        let b = dir.path().join("b.toml");
12857        for (path, text, new_cause) in [
12858            (&a, "[graph", true),
12859            (&a, "[verify", false),
12860            (&a, "[graph]\nimplementers = 'invalid-type'", true),
12861            (&b, "[graph]\nimplementers = 'invalid-type'", true),
12862        ] {
12863            t.release_operator("test", None);
12864            std::fs::write(path, text).unwrap();
12865            let error = Config::discover_fetched(dir.path(), Some(path))
12866                .await
12867                .unwrap_err();
12868            record_config_failure(&mut t, &error);
12869            t.hold_machine(Some(format!("{error:#}")));
12870            let due = t.chat_notice_due();
12871            assert_eq!(due.is_some(), new_cause, "{error:#}");
12872            if let Some(key) = due {
12873                assert_ne!(key, fetch_key);
12874                t.chat_notices.push(key);
12875            }
12876        }
12877        t.succeed(CompletionContext::new(
12878            CompletionActor::DaemonSettle,
12879            None,
12880            dir.path(),
12881            &t,
12882        ));
12883        assert_eq!(
12884            t.chat_notice_due(),
12885            Some(format!(
12886                "done:{}",
12887                t.completion_history.last().unwrap().occurrence
12888            ))
12889        );
12890    }
12891
12892    #[test]
12893    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
12894        let dir = tempfile::tempdir().unwrap();
12895        let queue_path = dir.path().join("queue");
12896        let queue = Queue::at(queue_path.clone());
12897        let mut t = task();
12898        t.source = crate::queue::Source::Agent {
12899            run: "originating-chat".into(),
12900            node: crate::queue::CHAT_NODE.into(),
12901        };
12902        let a = dir.path().join("a.png");
12903        let b = dir.path().join("b.png");
12904        std::fs::write(&a, "a").unwrap();
12905        std::fs::write(&b, "b").unwrap();
12906        queue.attach(&mut t, &[a, b]).unwrap();
12907        let paths = task_attachments(&queue, &t).unwrap();
12908        for path in &paths {
12909            std::fs::remove_file(path).unwrap();
12910        }
12911        let missing = task_attachments(&queue, &t).unwrap_err();
12912        t.attempts += 1;
12913        let reason = missing.to_string();
12914        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12915        let first = t.chat_notice_due().expect("first attachment notice");
12916        t.chat_notices.push(first.clone());
12917        queue.put(&mut t).unwrap();
12918
12919        let queue = Queue::at(queue_path.clone());
12920        let mut t = queue.get(&t.id).unwrap();
12921        assert!(t.chat_notice_due().is_none(), "restart does not replay");
12922        t.release_operator("test", None);
12923        t.attempts += 1;
12924        let missing = task_attachments(&queue, &t).unwrap_err();
12925        t.fail_startup_target(
12926            "startup-attachments",
12927            missing.name,
12928            "same missing attachment with regenerated wording",
12929            1,
12930        );
12931        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
12932
12933        std::fs::write(&paths[0], "restored").unwrap();
12934        t.release_operator("test", None);
12935        t.attempts += 1;
12936        let missing = task_attachments(&queue, &t).unwrap_err();
12937        let reason = missing.to_string();
12938        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12939        let second = t
12940            .chat_notice_due()
12941            .expect("different attachment must notify");
12942        assert_ne!(first, second);
12943        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
12944    }
12945
12946    #[test]
12947    fn resumed_instruction_is_unchanged_without_any_answers() {
12948        let t = task();
12949        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
12950    }
12951
12952    #[test]
12953    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
12954        let mut t = task();
12955        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12956        // The run's own instruction on disk predates the answer: it is the
12957        // plain original text `Runner::start` saved before the operator was
12958        // ever asked anything.
12959        let old = t.instruction.clone();
12960
12961        let refreshed = resumed_instruction(&old, &t);
12962        assert!(refreshed.starts_with(&old), "the original text is kept");
12963        assert!(refreshed.contains("Which backend?"));
12964        assert!(refreshed.contains("SQLite"));
12965    }
12966
12967    #[test]
12968    fn resumed_instruction_keeps_an_original_answers_heading() {
12969        let mut t = task();
12970        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
12971        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12972
12973        let refreshed = resumed_instruction(&t.instruction, &t);
12974
12975        assert!(
12976            refreshed.starts_with(&t.instruction),
12977            "an answers heading in the original instruction is not the appended block"
12978        );
12979        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
12980        assert!(refreshed.contains("Which backend?"));
12981        assert!(refreshed.contains("SQLite"));
12982
12983        let repeated = resumed_instruction(&refreshed, &t);
12984        assert_eq!(
12985            repeated, refreshed,
12986            "only the final appended block is refreshed"
12987        );
12988    }
12989
12990    #[test]
12991    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
12992        let mut t = task();
12993        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12994
12995        // A first resume appends the block; a second resume of the same run,
12996        // with no new answer in between, must reproduce exactly the same
12997        // text rather than appending the block a second time.
12998        let once = resumed_instruction(&t.instruction, &t);
12999        let twice = resumed_instruction(&once, &t);
13000        assert_eq!(once, twice);
13001        assert_eq!(once.matches("Which backend?").count(), 1);
13002
13003        // A later answer replaces the block wholesale rather than growing it.
13004        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
13005        let refreshed = resumed_instruction(&once, &t);
13006        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
13007        assert!(refreshed.contains("Which backend?"));
13008        assert!(refreshed.contains("Which cache?"));
13009    }
13010
13011    #[test]
13012    fn prepare_instruction_covers_all_three_starters() {
13013        let mut t = task();
13014        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13015
13016        // Start: a fresh run gets the task text plus every answer so far —
13017        // exactly `instruction_for`.
13018        assert_eq!(
13019            prepare_instruction(&Starter::Start, None, &t),
13020            Some(instruction_for(&t))
13021        );
13022
13023        // Resume: the run's prior instruction is refreshed with the answer,
13024        // not discarded and not left stale.
13025        let old = t.instruction.clone();
13026        assert_eq!(
13027            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
13028            Some(resumed_instruction(&old, &t))
13029        );
13030
13031        // Review: a review-only pass builds its own instruction from the
13032        // branch's history in `crate::graph`, with no task statement at all -
13033        // this boundary must leave it alone.
13034        assert_eq!(
13035            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
13036            None
13037        );
13038    }
13039
13040    #[test]
13041    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
13042        assert_eq!(
13043            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
13044            Starter::Review("magi/eba2/A".to_owned())
13045        );
13046    }
13047
13048    #[test]
13049    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
13050        assert_eq!(
13051            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
13052            Starter::Start,
13053            "a vanished review branch must not fall back to resuming the old run either"
13054        );
13055    }
13056
13057    #[test]
13058    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
13059        let mut t = task();
13060        t.start("old-run".to_owned());
13061        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
13062        t.release();
13063        let branch = t.review_branch.take();
13064        assert_eq!(
13065            choose_starter(branch.as_deref(), true, Some("old-run")),
13066            Starter::Review("magi/eba2/A".to_owned()),
13067            "a review wins over resuming the old run"
13068        );
13069    }
13070
13071    #[test]
13072    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
13073        assert_eq!(
13074            choose_starter(None, false, Some("some-run")),
13075            Starter::Resume("some-run".to_owned())
13076        );
13077        assert_eq!(choose_starter(None, false, None), Starter::Start);
13078    }
13079
13080    #[test]
13081    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
13082        let mut released = task();
13083        released.start("stalled-run".to_owned());
13084        released.requeue();
13085        let unfinished = (!released.fresh_start)
13086            .then(|| Some("stalled-run".to_owned()))
13087            .flatten();
13088        assert_eq!(
13089            choose_starter(None, false, unfinished.as_deref()),
13090            Starter::Start,
13091            "release keeps run history but must not resume it"
13092        );
13093        assert_eq!(released.runs, ["stalled-run"]);
13094    }
13095
13096    #[test]
13097    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
13098        let dir = tempfile::tempdir().unwrap();
13099        let queue = Queue::at(dir.path().join("queue"));
13100        let mut state = run_state(RunStatus::Blocked);
13101        state.merge_decision = Some(crate::merge_decision::Decision {
13102            question: "hold-inquiry".into(),
13103            target: crate::merge_decision::Target {
13104                pr: "https://example.test/pull/1".into(),
13105                head: "reviewed-head".into(),
13106                language: "en".into(),
13107            },
13108            choice: land::HOLD.into(),
13109            closed: false,
13110            replacement_run: None,
13111            replacement_pr: None,
13112        });
13113        let mut t = task();
13114        t.start(state.id.clone());
13115        settle_and_diagnose(
13116            &mut t,
13117            Verdict {
13118                status: RunStatus::Blocked,
13119                left_pr: true,
13120                quota_hit: false,
13121                parked: false,
13122                no_viable_candidates: false,
13123            },
13124            "held",
13125            2,
13126            &state,
13127        );
13128        queue.put(&mut t).unwrap();
13129        t.release_operator("chat", None);
13130        t.edit("revised".into(), "revised instruction".into())
13131            .unwrap();
13132        queue.put(&mut t).unwrap();
13133        drop(state);
13134        assert_eq!(
13135            queue
13136                .get(&t.id)
13137                .unwrap()
13138                .decision_effects
13139                .get("hold-inquiry"),
13140            Some(&format!("decision: {}", land::HOLD))
13141        );
13142    }
13143
13144    fn stopped_public_run(status: RunStatus) -> RunState {
13145        let mut state = run_state(status);
13146        state.driver_exited = true;
13147        state.config.graph.land = true;
13148        state.config.graph.review_rounds = 1;
13149        state.reviews = vec![review_round(1)];
13150        state.merge = Some(crate::run::MergeOutcome {
13151            mode: MergeMode::Pr,
13152            ok: false,
13153            detail: "landing stopped".into(),
13154            empty: false,
13155        });
13156        state.pr = Some(crate::run::PrRecord {
13157            url: "https://example.test/pull/1".into(),
13158            number: 1,
13159            state: "open".into(),
13160            checks: "red".into(),
13161            round: 1,
13162            rounds: 1,
13163            red_at_merge: Vec::new(),
13164        });
13165        state
13166    }
13167
13168    #[test]
13169    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
13170        for status in [RunStatus::Blocked, RunStatus::Gating] {
13171            let home = tempfile::tempdir().unwrap();
13172            let mut state = stopped_public_run(status);
13173            state.save_under(home.path()).unwrap();
13174            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
13175            assert!(!exhausted_review_budget(&state));
13176            let mut task = held_task_with(&state.id);
13177            task.release();
13178            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13179            assert_eq!(
13180                choose_starter(None, false, unfinished.as_deref()),
13181                Starter::Resume(state.id.clone())
13182            );
13183            let question = action_question(&state.id, resume_action(&state.id));
13184            assert_eq!(
13185                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13186                    state.clone()
13187                )),
13188                ActionDecision::Resume(state.id.clone())
13189            );
13190            // The control-plane command uses this same preflight before pinning.
13191            assert_eq!(
13192                crate::resume::validate(home.path(), &state.id).unwrap().id,
13193                state.id
13194            );
13195            let queue = Queue::at(home.path().join("queue"));
13196            let mut controlled = Task::new(
13197                "resume land".into(),
13198                state.instruction.clone(),
13199                state.repo.clone(),
13200                Source::Agent {
13201                    run: "talk".into(),
13202                    node: crate::queue::CHAT_NODE.into(),
13203                },
13204            );
13205            controlled.runs.push(state.id.clone());
13206            controlled.hold_machine(Some("land stopped".into()));
13207            queue.put(&mut controlled).unwrap();
13208            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13209            assert_eq!(resumed.status, TaskStatus::Queued);
13210            assert_eq!(
13211                resumed.resume_override.unwrap().pinned_run,
13212                Some(state.id.clone())
13213            );
13214            assert_eq!(resumed.attempts, 0);
13215        }
13216    }
13217
13218    #[test]
13219    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
13220        for review_rounds in [0, 1] {
13221            let home = tempfile::tempdir().unwrap();
13222            let mut state = run_state(RunStatus::Blocked);
13223            state.config.graph.review_rounds = review_rounds;
13224            if review_rounds > 0 {
13225                let mut review = review_round(1);
13226                review.clean = true;
13227                state.reviews = vec![review];
13228            }
13229            state.gate_ran = true;
13230            state.gate = vec![crate::run::CommandOutcome {
13231                command: "verify".into(),
13232                code: Some(1),
13233                output_tail: "gate failed after repair budget exhausted".into(),
13234                duration_ms: 0,
13235                resource_blocked: false,
13236            }];
13237            state.save_under(home.path()).unwrap();
13238            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13239            assert!(exhausted_review_budget(&state));
13240            let mut task = held_task_with(&state.id);
13241            task.release();
13242            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
13243            let question = action_question(&state.id, resume_action(&state.id));
13244            assert_ne!(
13245                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13246                    state.clone()
13247                )),
13248                ActionDecision::Resume(state.id.clone())
13249            );
13250            let error = crate::resume::validate(home.path(), &state.id)
13251                .unwrap_err()
13252                .to_string();
13253            assert!(!error.contains("review budget exhausted"), "{error}");
13254            assert!(
13255                error.contains(if review_rounds == 0 {
13256                    "review is disabled"
13257                } else {
13258                    "gate already ran"
13259                }),
13260                "{error}"
13261            );
13262
13263            // An unexecuted gate still has work to do with or without reviews.
13264            state.gate_ran = false;
13265            state.gate.clear();
13266            assert!(!exhausted_review_budget(&state));
13267            assert_eq!(
13268                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
13269                Some(state.id)
13270            );
13271        }
13272    }
13273
13274    #[test]
13275    fn resource_blocked_verification_resumes_the_same_run() {
13276        for (kind, stage) in [
13277            ("cache", "clean"),
13278            ("coordination", "clean"),
13279            ("cache", "review-e2e"),
13280            ("coordination", "no-reviews"),
13281            ("coordination", "handoff"),
13282        ] {
13283            let home = tempfile::tempdir().unwrap();
13284            let mut state = run_state(RunStatus::Blocked);
13285            state.config.graph.review_rounds = 1;
13286            let mut review = review_round(1);
13287            review.clean = true;
13288            state.reviews = vec![review];
13289            if stage == "review-e2e" {
13290                let review = &mut state.reviews[0];
13291                review.clean = false;
13292                review.blocking = 1;
13293                review.e2e = vec![crate::run::CommandOutcome {
13294                    command: "verify".into(),
13295                    code: None,
13296                    output_tail: "resource wait expired".into(),
13297                    duration_ms: 0,
13298                    resource_blocked: true,
13299                }];
13300            } else if stage == "no-reviews" {
13301                state.config.graph.review_rounds = 0;
13302                state.reviews.clear();
13303            } else if stage == "handoff" {
13304                // A completed final verification can hand off to the gate
13305                // even when the review still carries contested findings.
13306                let review = &mut state.reviews[0];
13307                review.clean = false;
13308                review.blocking = 1;
13309                review.e2e = vec![crate::run::CommandOutcome {
13310                    command: "verify".into(),
13311                    code: Some(0),
13312                    output_tail: String::new(),
13313                    duration_ms: 0,
13314                    resource_blocked: false,
13315                }];
13316            }
13317            state.gate_ran = false;
13318            state.resource_block = Some(crate::run::ResourceBlock {
13319                cause: crate::run::ResourceBlockCause::Other,
13320                node: if stage == "review-e2e" {
13321                    "review"
13322                } else {
13323                    "gate"
13324                }
13325                .into(),
13326                kind: kind.into(),
13327                detail: "resource wait expired".into(),
13328                at: jiff::Timestamp::now(),
13329            });
13330            state.save_under(home.path()).unwrap();
13331            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13332            assert!(!exhausted_review_budget(&state));
13333            let mut task = held_task_with(&state.id);
13334            task.release();
13335            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13336            assert_eq!(
13337                choose_starter(None, false, unfinished.as_deref()),
13338                Starter::Resume(state.id.clone())
13339            );
13340            let question = action_question(&state.id, resume_action(&state.id));
13341            assert_eq!(
13342                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13343                    state.clone()
13344                )),
13345                ActionDecision::Resume(state.id.clone())
13346            );
13347            assert_eq!(
13348                crate::resume::validate(home.path(), &state.id).unwrap().id,
13349                state.id
13350            );
13351            let queue = Queue::at(home.path().join("queue"));
13352            let mut controlled = Task::new(
13353                "resume verification".into(),
13354                state.instruction.clone(),
13355                state.repo.clone(),
13356                Source::Agent {
13357                    run: "talk".into(),
13358                    node: crate::queue::CHAT_NODE.into(),
13359                },
13360            );
13361            controlled.runs.push(state.id.clone());
13362            controlled.hold_machine(Some("verification resource unavailable".into()));
13363            queue.put(&mut controlled).unwrap();
13364            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13365            assert_eq!(resumed.status, TaskStatus::Queued);
13366            assert_eq!(
13367                resumed.resume_override.unwrap().pinned_run,
13368                Some(state.id.clone())
13369            );
13370            assert_eq!(resumed.attempts, 0);
13371
13372            // A genuinely unresolved final review still exhausts the budget.
13373            state.config.graph.review_rounds = 1;
13374            let mut unresolved = review_round(1);
13375            unresolved.blocking = 1;
13376            state.reviews = vec![unresolved];
13377            state.resource_block = None;
13378            state.save_under(home.path()).unwrap();
13379            assert!(exhausted_review_budget(&state));
13380            assert!(crate::resume::validate(home.path(), &state.id).is_err());
13381        }
13382    }
13383
13384    #[tokio::test]
13385    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
13386        if !crate::standalone_test(
13387            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
13388        ) {
13389            return;
13390        }
13391        let home = tempfile::tempdir().unwrap();
13392        let mut owner = stopped_public_run(RunStatus::Blocked);
13393        owner.save_under(home.path()).unwrap();
13394        let history = vec![owner.id.clone()];
13395        let repo = owner.repo.clone();
13396        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
13397        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
13398        let initial =
13399            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
13400        assert!(
13401            initial.is_pending(),
13402            "a busy record must not hold or resume the task"
13403        );
13404        owner.retired_to = Some("20260101-000001-bbbb".into());
13405        owner.save_under(home.path()).unwrap();
13406        drop(lock);
13407        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
13408            .await
13409            .expect("ownership lock released")
13410            .expect("read settled owner");
13411        assert!(
13412            result.is_none(),
13413            "the retired owner must not be resumed from a stale read"
13414        );
13415    }
13416
13417    #[tokio::test]
13418    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
13419        if !crate::standalone_test(
13420            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
13421        ) {
13422            return;
13423        }
13424        let home = tempfile::tempdir().unwrap();
13425        let mut owner = stopped_public_run(RunStatus::Blocked);
13426        let repo = tempfile::tempdir().unwrap();
13427        crate::git::git(repo.path(), &["init"]).await.unwrap();
13428        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
13429        owner.id = "20260101-000000-aaaa".into();
13430        owner.save_under(home.path()).unwrap();
13431        let mut successor = run_state(RunStatus::Blocked);
13432        successor.id = "20260101-000001-bbbb".into();
13433        successor.save_under(home.path()).unwrap();
13434        let runs = vec![owner.id.clone(), successor.id.clone()];
13435        assert_eq!(
13436            public_resume_owner(home.path(), &runs, &owner.repo)
13437                .await
13438                .unwrap()
13439                .unwrap()
13440                .id,
13441            owner.id
13442        );
13443        let subdir = owner.repo.join("nested");
13444        std::fs::create_dir(&subdir).unwrap();
13445        assert_eq!(
13446            public_resume_owner(home.path(), &runs, &subdir)
13447                .await
13448                .unwrap()
13449                .unwrap()
13450                .id,
13451            owner.id
13452        );
13453        #[cfg(unix)]
13454        {
13455            let alias = home.path().join("repo-alias");
13456            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
13457            assert_eq!(
13458                public_resume_owner(home.path(), &runs, &alias.join("nested"))
13459                    .await
13460                    .unwrap()
13461                    .unwrap()
13462                    .id,
13463                owner.id
13464            );
13465        }
13466        let different = tempfile::tempdir().unwrap();
13467        crate::git::git(different.path(), &["init"]).await.unwrap();
13468        assert!(
13469            public_resume_owner(home.path(), &runs, different.path())
13470                .await
13471                .is_err()
13472        );
13473        std::fs::remove_file(
13474            home.path()
13475                .join("runs")
13476                .join(&successor.id)
13477                .join("run.json"),
13478        )
13479        .unwrap();
13480        assert!(
13481            public_resume_owner(home.path(), &runs, &owner.repo)
13482                .await
13483                .is_err()
13484        );
13485    }
13486
13487    #[test]
13488    fn an_ordinary_release_keeps_a_resumable_run_available() {
13489        let mut released = task();
13490        released.start("stalled-run".to_owned());
13491        released.release();
13492        let unfinished = (!released.fresh_start)
13493            .then(|| Some("stalled-run".to_owned()))
13494            .flatten();
13495        assert_eq!(
13496            choose_starter(None, false, unfinished.as_deref()),
13497            Starter::Resume("stalled-run".to_owned()),
13498            "manual release must preserve the normal resume path"
13499        );
13500    }
13501
13502    #[test]
13503    fn resume_refusals_explain_admission_without_changing_task_or_run() {
13504        use crate::handover::{ResumeRefusal, resume_refusal_under};
13505        let home = tempfile::tempdir().unwrap();
13506        let mut exhausted = run_state(RunStatus::Blocked);
13507        exhausted.driver_exited = true;
13508        exhausted.config.graph.review_rounds = 3;
13509        exhausted.reviews = (1..=3).map(review_round).collect();
13510        for refusal in [
13511            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
13512            ResumeRefusal::Status(RunStatus::Ready),
13513            ResumeRefusal::Released("20261022-000000-aaaa".into()),
13514            ResumeRefusal::Retired("retirement-successor".into()),
13515            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
13516        ] {
13517            let mut state = exhausted.clone();
13518            let expected = match refusal {
13519                ResumeRefusal::Status(_) => {
13520                    state.status = RunStatus::Ready;
13521                    "status `ready`"
13522                }
13523                ResumeRefusal::Released(ref target) => {
13524                    state.released_to = Some(target.clone());
13525                    "execution was released"
13526                }
13527                ResumeRefusal::Retired(ref target) => {
13528                    state.retired_to = Some(target.clone());
13529                    "execution was retired"
13530                }
13531                ResumeRefusal::OwnershipTransferred(ref target) => {
13532                    state.pr_taken_over_by = Some(target.clone());
13533                    "PR ownership was transferred"
13534                }
13535                _ => "review budget exhausted (3/3 rounds used)",
13536            };
13537            assert_eq!(
13538                resume_refusal_under(&state, Some(home.path())),
13539                Some(refusal.clone())
13540            );
13541            assert_eq!(
13542                refusal.successor(),
13543                state
13544                    .released_to
13545                    .as_deref()
13546                    .or(state.retired_to.as_deref())
13547                    .or(state.pr_taken_over_by.as_deref())
13548            );
13549            state.save_under(home.path()).unwrap();
13550            let queue = Queue::at(home.path().join("queue"));
13551            let mut task = Task::new(
13552                "retained implementation".into(),
13553                state.instruction.clone(),
13554                state.repo.clone(),
13555                Source::Agent {
13556                    run: "talk".into(),
13557                    node: crate::queue::CHAT_NODE.into(),
13558                },
13559            );
13560            task.runs.push(state.id.clone());
13561            task.hold_machine(Some("stopped".into()));
13562            queue.put(&mut task).unwrap();
13563            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
13564            let before_run = serde_json::to_value(&state).unwrap();
13565            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
13566                .unwrap_err()
13567                .to_string();
13568            assert!(error.contains(expected), "{error}");
13569            assert!(!error.contains("only a stalled or blocked"), "{error}");
13570            if matches!(refusal, ResumeRefusal::Status(_)) {
13571                assert!(
13572                    error.contains("is final; there is nothing left to resume"),
13573                    "{error}"
13574                );
13575            }
13576            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
13577                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
13578                assert!(error.contains("review-only successor with a new review budget"));
13579                assert!(error.contains("does not resume this run"));
13580            }
13581            for target in [
13582                &state.released_to,
13583                &state.retired_to,
13584                &state.pr_taken_over_by,
13585            ]
13586            .into_iter()
13587            .flatten()
13588            {
13589                let short = if state.retired_to.as_ref() == Some(target) {
13590                    target.as_str()
13591                } else {
13592                    crate::run::short_of(target)
13593                };
13594                assert!(
13595                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
13596                    "{error}"
13597                );
13598                if short != target {
13599                    assert!(!error.contains(target), "full successor id leaked: {error}");
13600                }
13601            }
13602            assert_eq!(
13603                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
13604                before_task
13605            );
13606            assert_eq!(
13607                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
13608                    .unwrap(),
13609                before_run
13610            );
13611            let question = action_question(&state.id, resume_action(&state.id));
13612            for phrases in [&PHRASES_EN, &PHRASES_JA] {
13613                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
13614                    RunState::load_under(id, home.path())
13615                });
13616                let ActionDecision::Refuse(detail) = decision else {
13617                    panic!(
13618                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
13619                        state.id,
13620                        home.path().display()
13621                    );
13622                };
13623                assert!(detail.contains(expected), "{detail}");
13624            }
13625        }
13626        // Preserve predicate ordering, while keeping every recorded destination visible.
13627        exhausted.status = RunStatus::Ready;
13628        exhausted.released_to = Some("released".into());
13629        exhausted.retired_to = Some("retired".into());
13630        exhausted.pr_taken_over_by = Some("owner".into());
13631        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
13632        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
13633        let detail = reason.diagnostic(&exhausted);
13634        for target in ["released", "retired", "owner"] {
13635            assert!(detail.contains(&format!("magi show {target}")));
13636        }
13637    }
13638
13639    #[test]
13640    fn resume_action_ignores_question_checkpoints_in_another_home() {
13641        crate::run::pin_test_home();
13642        let home = tempfile::tempdir().unwrap();
13643        let mut state = run_state(RunStatus::Blocked);
13644        // The private directory reserves this fixture's identity even while
13645        // other tests write questions into the process-wide store.
13646        state.id = format!(
13647            "resume-context-{}",
13648            home.path().file_name().unwrap().to_str().unwrap()
13649        );
13650        state.driver_exited = true;
13651        state.config.graph.review_rounds = 1;
13652        state.reviews = vec![review_round(1)];
13653        state.save_under(home.path()).unwrap();
13654        let task = held_task_with(&state.id);
13655        let answer = action_question(&state.id, resume_action(&state.id));
13656        let mut checkpoint = approval_question(&state.id);
13657        let foreign = Questions::open();
13658        foreign.put(&mut checkpoint).unwrap();
13659        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
13660        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13661            RunState::load_under(id, home.path())
13662        });
13663        let matching: Vec<_> = foreign
13664            .list()
13665            .into_iter()
13666            .filter(|q| q.run == state.id && q.status.open())
13667            .collect();
13668        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
13669        assert!(
13670            matches!(decision, ActionDecision::Refuse(_)),
13671            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
13672            state.id,
13673            home.path().display(),
13674            crate::run::test_home().display()
13675        );
13676        assert_eq!(
13677            refusal,
13678            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
13679        );
13680        let local = Questions::at(home.path().join("questions"));
13681        for status in [
13682            ask::QuestionStatus::Open,
13683            ask::QuestionStatus::Answered,
13684            ask::QuestionStatus::Abandoned,
13685        ] {
13686            let mut question = checkpoint.clone();
13687            match status {
13688                ask::QuestionStatus::Open => {}
13689                ask::QuestionStatus::Answered => {
13690                    question
13691                        .answer(ask::Answer::Choice(question.choices[0].clone()))
13692                        .unwrap();
13693                }
13694                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
13695            }
13696            local.put(&mut question).unwrap();
13697            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13698                RunState::load_under(id, home.path())
13699            });
13700            if status.open() {
13701                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
13702            } else {
13703                assert!(
13704                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
13705                    "status={status:?}, decision={decision:?}"
13706                );
13707            }
13708        }
13709    }
13710
13711    #[test]
13712    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
13713        let home = tempfile::tempdir().unwrap();
13714        let mut state = run_state(RunStatus::Stalled);
13715        state.id = format!(
13716            "resume-driver-{}",
13717            home.path().file_name().unwrap().to_str().unwrap()
13718        );
13719        state.driver_claimed = Some(false);
13720        state.save_under(home.path()).unwrap();
13721        let task = held_task_with(&state.id);
13722        let question = action_question(&state.id, resume_action(&state.id));
13723        let decide = || {
13724            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
13725                RunState::load_under(id, home.path())
13726            })
13727        };
13728        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
13729        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
13730        assert_eq!(
13731            decide(),
13732            ActionDecision::Refuse("run already has a live driver".into())
13733        );
13734        drop(lease);
13735        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
13736    }
13737
13738    #[test]
13739    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
13740        let home = tempfile::tempdir().unwrap();
13741        let mut state = run_state(RunStatus::Blocked);
13742        state.driver_exited = true;
13743        state.config.graph.review_rounds = 1;
13744        state.reviews = vec![review_round(1)];
13745        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
13746        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
13747            let mut saved = state.clone();
13748            match checkpoint {
13749                "publication" => saved.pr_publication_pending = true,
13750                "approval" => {
13751                    saved.land_approval = Some(crate::run::LandApproval {
13752                        question: "approval".into(),
13753                        head: "head".into(),
13754                    })
13755                }
13756                "armed" => saved.land_armed_head = Some("head".into()),
13757                "landing" => saved.status = RunStatus::Landing,
13758                _ => {
13759                    let mut question = ask::Question::new(
13760                        saved.id.clone(),
13761                        "review".into(),
13762                        "review-1".into(),
13763                        "continue?".into(),
13764                        String::new(),
13765                        vec!["continue".into()],
13766                    );
13767                    ask::Questions::at(home.path().join("questions"))
13768                        .put(&mut question)
13769                        .unwrap();
13770                }
13771            }
13772            saved.save_under(home.path()).unwrap();
13773            assert!(
13774                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
13775                "{checkpoint}"
13776            );
13777            assert!(
13778                crate::resume::validate(home.path(), &saved.id).is_ok(),
13779                "{checkpoint}"
13780            );
13781        }
13782    }
13783
13784    #[test]
13785    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
13786        let mut state = run_state(RunStatus::Blocked);
13787        state.config.graph.review_rounds = 3;
13788        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
13789        assert!(exhausted_review_budget(&state));
13790
13791        // One round still unused: resuming can still ask a reviewer something.
13792        state.reviews.pop();
13793        assert!(!exhausted_review_budget(&state));
13794
13795        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
13796        // count: only a `Blocked` run re-enters the review loop on resume.
13797        let mut stalled = run_state(RunStatus::Stalled);
13798        stalled.config.graph.review_rounds = 1;
13799        stalled.reviews = vec![review_round(1)];
13800        assert!(!exhausted_review_budget(&stalled));
13801    }
13802
13803    fn review_round(round: usize) -> crate::run::ReviewRound {
13804        crate::run::ReviewRound {
13805            round,
13806            head: "deadbeef".to_owned(),
13807            verified_head: None,
13808            verified_at: None,
13809            reviews: Vec::new(),
13810            e2e: Vec::new(),
13811            verify_retried: false,
13812            e2e_deferred: false,
13813            e2e_defer_reason: None,
13814            fix: None,
13815            blocking: 0,
13816            answered: 1,
13817            expected: 1,
13818            clean: false,
13819            progressed: true,
13820            vote_split: false,
13821            reconsideration: Vec::new(),
13822            verdict: None,
13823        }
13824    }
13825
13826    #[test]
13827    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
13828        let mut run = RunState::new(
13829            PathBuf::from("/repo"),
13830            "main".to_owned(),
13831            "abc1234def".to_owned(),
13832            "add retries".to_owned(),
13833            Config::default(),
13834        );
13835        run.status = RunStatus::Judging;
13836        run.parked = true;
13837        let mut task = Task::new(
13838            "add retries".to_owned(),
13839            "add retries".to_owned(),
13840            PathBuf::from("/repo"),
13841            crate::queue::Source::Human,
13842        );
13843        task.status = TaskStatus::Failed;
13844        task.runs = vec![run.id.clone()];
13845        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
13846        assert!(with(&task, &run), "parked after judging is the case");
13847        let mut parked_task = task.clone();
13848        parked_task.status = TaskStatus::Parked;
13849        assert!(with(&parked_task, &run), "the Parked status is the case");
13850
13851        let mut not_parked = run.clone();
13852        not_parked.parked = false;
13853        not_parked.status = RunStatus::Stalled;
13854        assert!(!with(&task, &not_parked), "a stall is the conductor's");
13855
13856        let mut fresh = task.clone();
13857        fresh.fresh_start = true;
13858        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
13859
13860        let mut review = task.clone();
13861        review.review_branch = Some("magi/x/A".to_owned());
13862        assert!(!with(&review, &run), "review is ranked before resume");
13863
13864        let mut held = task.clone();
13865        held.status = TaskStatus::Held;
13866        assert!(!with(&held, &run), "a hold stays visible to the conductor");
13867
13868        let mut released = run.clone();
13869        released.released_to = Some("20260901-000000-new1".to_owned());
13870        assert!(!with(&task, &released), "nothing left to resume into");
13871
13872        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
13873            "unreadable"
13874        )));
13875    }
13876
13877    #[test]
13878    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
13879        let mut released = RunState::new(
13880            PathBuf::from("/repo"),
13881            "main".to_owned(),
13882            "abc1234def".to_owned(),
13883            "add retries".to_owned(),
13884            Config::default(),
13885        );
13886        released.status = RunStatus::Blocked;
13887        assert_eq!(
13888            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13889            Some(released.id.clone())
13890        );
13891        released.released_to = Some("20260901-000000-new1".to_owned());
13892        assert_eq!(
13893            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13894            None,
13895            "there is nothing left to resume it into"
13896        );
13897    }
13898
13899    #[test]
13900    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
13901        // Mirrors the failure this exists to close: a task's last run ended
13902        // `Blocked` with the review budget spent, `crate::conduct` chose
13903        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
13904        // evidence), and without this check `attempt` would go on treating
13905        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
13906        // review loop iterates zero times over an already-spent budget, so
13907        // the resumed run settles right back to `Blocked` having asked nobody
13908        // anything, and `Requeue`'s promised fresh competition never happens.
13909        let mut exhausted = RunState::new(
13910            PathBuf::from("/repo"),
13911            "main".to_owned(),
13912            "abc1234def".to_owned(),
13913            "add retries".to_owned(),
13914            Config::default(),
13915        );
13916        exhausted.status = RunStatus::Blocked;
13917        exhausted.config.graph.review_rounds = 1;
13918        exhausted.reviews = vec![review_round(1)];
13919
13920        assert_eq!(
13921            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
13922            None,
13923            "an exhausted `Blocked` run must not be offered as resumable"
13924        );
13925
13926        // A `Blocked` run with rounds still unused is genuinely worth
13927        // resuming, and must still be found.
13928        let mut has_budget_left = RunState::new(
13929            PathBuf::from("/repo"),
13930            "main".to_owned(),
13931            "abc1234def".to_owned(),
13932            "add retries".to_owned(),
13933            Config::default(),
13934        );
13935        has_budget_left.status = RunStatus::Blocked;
13936        has_budget_left.config.graph.review_rounds = 3;
13937        has_budget_left.reviews = vec![review_round(1)];
13938
13939        assert_eq!(
13940            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
13941                Ok(has_budget_left.clone())
13942            }),
13943            Some(has_budget_left.id.clone())
13944        );
13945    }
13946
13947    #[test]
13948    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
13949        let mut run = RunState::new(
13950            PathBuf::from("/repo"),
13951            "main".to_owned(),
13952            "abc1234def".to_owned(),
13953            "add retries".to_owned(),
13954            Config::default(),
13955        );
13956        run.status = RunStatus::Blocked;
13957        run.config.graph.review_rounds = 1;
13958        run.reviews = vec![review_round(1)];
13959        run.pr_publication_pending = true;
13960        assert_eq!(
13961            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
13962            Some(run.id.clone()),
13963            "a spent review budget must not turn a failed publication into a re-competition"
13964        );
13965    }
13966
13967    #[test]
13968    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
13969        let mut task = Task::new(
13970            "recover work".into(),
13971            "recover work".into(),
13972            PathBuf::from("/repo"),
13973            crate::queue::Source::Human,
13974        );
13975        let mut history = std::collections::BTreeMap::new();
13976        for index in 0..8 {
13977            let mut run = run_state(RunStatus::Blocked);
13978            run.id = format!("20260101-000000-{index:04}");
13979            run.base_commit = format!("upstream-{index}");
13980            // Seven empty newer attempts must not erase the old recovery owner.
13981            if index > 0 {
13982                run.candidates.clear();
13983            }
13984            task.runs.extend([run.id.clone(), run.id.clone()]);
13985            history.insert(run.id.clone(), run);
13986            task.requeue();
13987        }
13988        let check = |task: &Task, starter: &Starter, limit| {
13989            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
13990        };
13991        assert!(
13992            check(&task, &Starter::Start, 8)
13993                .unwrap()
13994                .contains("8 unretired")
13995        );
13996        assert!(check(&task, &Starter::Start, 9).is_none());
13997        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
13998        task.release_operator("owner", None);
13999        assert_eq!(task.attempts, 0);
14000        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14001        assert!(check(&restored, &Starter::Start, 8).is_some());
14002        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
14003        assert!(check(&restored, &Starter::Start, 0).is_none());
14004    }
14005
14006    #[test]
14007    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
14008        let tmp = tempfile::tempdir().unwrap();
14009        let mut task = Task::new(
14010            "recover selected PR".into(),
14011            "preserve implementation".into(),
14012            tmp.path().join("repo"),
14013            crate::queue::Source::Human,
14014        );
14015        let mut failed = run_state(RunStatus::Failed);
14016        failed.id = "20260101-000000-fail".into();
14017        failed.candidates.clear();
14018        failed.prep_complete = Some(false);
14019        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
14020        failed.startup = Some(crate::run::Startup {
14021            kind: "pr-recovery".into(),
14022            branch: Some("selected-public-head".into()),
14023            stage: "worktree-setup".into(),
14024            complete: false,
14025            failure: Some("setup modified a tracked file and failed".into()),
14026        });
14027        // Setup may fail before a candidate is recorded; its dirty worktree
14028        // still needs protection and consumes the independent retained bound.
14029        let worktree = failed.worktree_root().join("under-review");
14030        std::fs::create_dir_all(&worktree).unwrap();
14031        let retained_edit = worktree.join("implementation");
14032        std::fs::write(&retained_edit, "retained setup edit").unwrap();
14033        task.record_startup_failure(crate::run::StartupFailure {
14034            run: failed.id.clone(),
14035            stage: "worktree-setup".into(),
14036        });
14037        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14038        assert!(task.runs.is_empty() && task.passes.is_empty());
14039        assert_eq!(task.attempts, 0);
14040        let starter = Starter::Review("selected-public-head".into());
14041        assert!(
14042            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
14043                .unwrap()
14044                .contains("1 unretired")
14045        );
14046        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
14047        assert!(
14048            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
14049                .unwrap()
14050                .contains("Cannot verify")
14051        );
14052        // Older or mixed writers can link the same reservation in both lists.
14053        let mut mixed = task.clone();
14054        mixed.runs.push(failed.id.clone());
14055        mixed
14056            .startup_failures
14057            .push(task.startup_failures[0].clone());
14058        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
14059        failed.retired_to = Some("verified-recovery-owner".into());
14060        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
14061        assert!(
14062            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
14063                panic!("resuming the existing owner must not allocate a new attempt")
14064            })
14065            .is_none()
14066        );
14067        assert_eq!(
14068            std::fs::read_to_string(retained_edit).unwrap(),
14069            "retained setup edit"
14070        );
14071        assert!(task.runs.is_empty() && task.passes.is_empty());
14072        assert_eq!(task.attempts, 0);
14073    }
14074
14075    #[test]
14076    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
14077        let mut task = Task::new(
14078            "recover work".into(),
14079            "recover work".into(),
14080            PathBuf::from("/repo"),
14081            crate::queue::Source::Human,
14082        );
14083        let mut run = run_state(RunStatus::Superseded);
14084        run.candidates.clear();
14085        task.runs.push(run.id.clone());
14086        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
14087        run.retired_to = Some("authority".into());
14088        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14089        run.retired_to = None;
14090        run.released_to = Some("authority".into());
14091        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14092        assert!(
14093            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
14094                .unwrap()
14095                .contains("Cannot verify")
14096        );
14097        // Resuming an existing owner needs no new inventory or worktree budget.
14098        assert!(
14099            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
14100                panic!("resume must not load historical attempts")
14101            })
14102            .is_none()
14103        );
14104    }
14105
14106    #[test]
14107    fn retired_resume_requires_a_valid_same_repository_authority() {
14108        let mut source = run_state(RunStatus::Blocked);
14109        let mut empty = run_state(RunStatus::Blocked);
14110        empty.retired_to = Some(source.id.clone());
14111        let runs = vec![source.id.clone(), empty.id.clone()];
14112        let resolve = |source: &RunState, empty: &RunState| {
14113            unfinished_run_with(&runs, "fixture", |id| {
14114                if id == source.id {
14115                    Ok(source.clone())
14116                } else if id == empty.id {
14117                    Ok(empty.clone())
14118                } else {
14119                    bail!("unreadable authority")
14120                }
14121            })
14122        };
14123        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
14124        assert_eq!(
14125            choose_starter(None, false, resolve(&source, &empty).as_deref()),
14126            Starter::Resume(source.id.clone())
14127        );
14128        source.retired_to = Some(empty.id.clone());
14129        assert!(
14130            resolve(&source, &empty).is_none(),
14131            "cycles do not revive obsolete runs"
14132        );
14133        source.retired_to = None;
14134        source.repo = PathBuf::from("/another-repository");
14135        assert!(resolve(&source, &empty).is_none());
14136        source.repo = empty.repo.clone();
14137        source.released_to = Some("later".into());
14138        assert!(resolve(&source, &empty).is_none());
14139        empty.retired_to = Some("unlisted-run".into());
14140        assert!(resolve(&source, &empty).is_none());
14141    }
14142
14143    #[test]
14144    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
14145        // A task whose history holds an *older* run that still looks
14146        // resumable (say, a competition `Runner::review` was started
14147        // alongside after that older run went `Stalled`) and a *newest* run
14148        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
14149        // on this task must mean a fresh competition — falling back to the
14150        // stale, superseded `Stalled` run instead would resurrect history
14151        // nothing asked to revisit and silently defeat the requeue.
14152        let mut older_stalled = RunState::new(
14153            PathBuf::from("/repo"),
14154            "main".to_owned(),
14155            "abc1234def".to_owned(),
14156            "add retries".to_owned(),
14157            Config::default(),
14158        );
14159        older_stalled.status = RunStatus::Stalled;
14160
14161        let mut newest_exhausted = RunState::new(
14162            PathBuf::from("/repo"),
14163            "main".to_owned(),
14164            "abc1234def".to_owned(),
14165            "add retries".to_owned(),
14166            Config::default(),
14167        );
14168        newest_exhausted.status = RunStatus::Blocked;
14169        newest_exhausted.config.graph.review_rounds = 1;
14170        newest_exhausted.reviews = vec![review_round(1)];
14171
14172        assert_eq!(
14173            unfinished_run_with(
14174                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
14175                "t",
14176                |_| Ok(newest_exhausted.clone())
14177            ),
14178            None,
14179            "the newest run is exhausted, so nothing here is worth resuming - \
14180             least of all the older, already-superseded run"
14181        );
14182    }
14183
14184    #[test]
14185    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
14186        assert_eq!(
14187            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
14188                Err(anyhow::anyhow!("fixture is absent"))
14189            }),
14190            None
14191        );
14192    }
14193
14194    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
14195        let mut q = ask::Question::new(
14196            run.to_owned(),
14197            "implement".to_owned(),
14198            "impl-A".to_owned(),
14199            "continue?".to_owned(),
14200            String::new(),
14201            vec!["resume で続行する".to_owned(), "other".to_owned()],
14202        );
14203        q.actions.insert("resume で続行する".to_owned(), action);
14204        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
14205            .unwrap();
14206        q
14207    }
14208
14209    fn held_task_with(run: &str) -> Task {
14210        let mut t = task();
14211        t.runs = vec![run.to_owned()];
14212        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
14213        t
14214    }
14215
14216    fn resume_action(run: &str) -> ask::ChoiceAction {
14217        ask::ChoiceAction::Resume { run: run.into() }
14218    }
14219
14220    #[test]
14221    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
14222        let home = crate::run::test_home();
14223        for parked in [false, true] {
14224            let mut t = task();
14225            t.start("A".into());
14226            t.start("B".into());
14227            assert_eq!(t.runs, vec!["A", "B"]);
14228            t.start("A".into());
14229            let mut resumed = run_state(RunStatus::Blocked);
14230            resumed.id = "A".into();
14231            resumed.parked = parked;
14232            resumed.driver_exited = true;
14233            t.hold_machine(Some("resumed run stopped".into()));
14234            let q = action_question("A", resume_action("A"));
14235            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14236            assert_eq!(
14237                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
14238                    assert_eq!(id, "A");
14239                    Ok(resumed.clone())
14240                }),
14241                ActionDecision::Resume("A".into())
14242            );
14243            assert_eq!(
14244                action_standing(&t, &action_question("B", resume_action("B"))),
14245                ActionStanding::Stale
14246            );
14247            t.release_operator("cli", None);
14248            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
14249                assert_eq!(id, "A");
14250                Ok(resumed.clone())
14251            });
14252            assert_eq!(
14253                choose_starter(None, false, unfinished.as_deref()),
14254                Starter::Resume("A".into())
14255            );
14256            assert_eq!(t.runs, vec!["B", "A"]);
14257        }
14258    }
14259
14260    #[test]
14261    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
14262        let home = crate::run::test_home();
14263        let mut state = crate::land::tests::repair_state(true, true);
14264        state.status = RunStatus::Landing;
14265        state.parked = true;
14266        state.driver_exited = true;
14267        let mut q = ask::Question::new(
14268            state.id.clone(),
14269            land::APPROVAL_NODE.into(),
14270            "land".into(),
14271            "Merge?".into(),
14272            String::new(),
14273            vec![land::APPROVE.into(), land::HOLD.into()],
14274        );
14275        q.id = state.id.clone();
14276        state.land_approval = Some(crate::run::LandApproval {
14277            question: q.id.clone(),
14278            head: "current-head".into(),
14279        });
14280        assert!(land::upgrade_repair_choice(&mut q, &state));
14281        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14282        let mut task = held_task_with(&state.id);
14283        task.status = TaskStatus::Parked;
14284        assert_eq!(
14285            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14286            ActionDecision::Resume(state.id.clone())
14287        );
14288        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14289        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
14290        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
14291        assert_eq!(
14292            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14293            ActionDecision::Resume(state.id.clone()),
14294            "a repair answer newer than the manual hold resumes the existing owner"
14295        );
14296        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14297        for answered_at in [q.answered_at, None] {
14298            let mut older = q.clone();
14299            older.answered_at = answered_at;
14300            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
14301                panic!("a later manual hold must prevent dispatch")
14302            });
14303            let ActionDecision::Refuse(reason) = refused else {
14304                panic!("expected an actionable refusal, got {refused:?}");
14305            };
14306            assert!(reason.contains("later operator decision"));
14307            assert!(reason.contains(&format!("magi task release {}", task.id)));
14308        }
14309        task.operator_decided_at = None;
14310        let mut superseded = state.clone();
14311        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
14312        assert_eq!(
14313            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
14314            ActionDecision::Stale
14315        );
14316        for case in 1..4 {
14317            let mut changed = state.clone();
14318            match case {
14319                1 => changed.status = RunStatus::Blocked,
14320                2 => changed.released_to = Some("new-owner".into()),
14321                _ => changed.land_approval.as_mut().unwrap().head.clear(),
14322            }
14323            assert!(matches!(
14324                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
14325                ActionDecision::Refuse(_)
14326            ));
14327        }
14328        assert!(matches!(
14329            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
14330                "missing owner"
14331            )),
14332            ActionDecision::Refuse(_)
14333        ));
14334        task.runs.push("replacement".into());
14335        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14336        assert_eq!(
14337            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
14338                "old owner must not load"
14339            )),
14340            ActionDecision::Stale
14341        );
14342    }
14343
14344    #[test]
14345    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
14346        let mut state = crate::land::tests::repair_state(true, true);
14347        state.status = RunStatus::Landing;
14348        state.parked = true;
14349        state.driver_exited = true;
14350        let mut q = ask::Question::new(
14351            state.id.clone(),
14352            land::APPROVAL_NODE.into(),
14353            "land".into(),
14354            "Merge?".into(),
14355            String::new(),
14356            vec![land::APPROVE.into(), land::HOLD.into()],
14357        );
14358        q.id = state.id.clone();
14359        state.land_approval = Some(crate::run::LandApproval {
14360            question: q.id.clone(),
14361            head: "current-head".into(),
14362        });
14363        state.save().unwrap();
14364        land::upgrade_repair_choice(&mut q, &state);
14365        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14366        Questions::open().put(&mut q).unwrap();
14367        let tmp = tempfile::tempdir().unwrap();
14368        let queue = Queue::at(tmp.path().join("queue"));
14369        let mut task = held_task_with(&state.id);
14370        task.status = TaskStatus::Parked;
14371        queue.put(&mut task).unwrap();
14372        let empty = Arc::new(tokio::sync::Semaphore::new(0));
14373        let free = Arc::new(tokio::sync::Semaphore::new(1));
14374        assert!(matches!(
14375            claim_dispatch(&queue, &task, false, &empty, &free),
14376            Err(SkipReason::OrdinaryCapacity)
14377        ));
14378        assert!(matches!(
14379            claim_dispatch(&queue, &task, true, &free, &free),
14380            Err(SkipReason::CoolingDown)
14381        ));
14382        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
14383        assert!(claim.permit.is_some());
14384        assert!(matches!(
14385            claim_dispatch(&queue, &task, false, &free, &free),
14386            Err(SkipReason::ClaimUnavailable)
14387        ));
14388        drop(claim);
14389        Questions::open()
14390            .update(&q.id, |q| {
14391                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
14392                Ok(())
14393            })
14394            .unwrap();
14395        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
14396        assert!(claim.permit.is_none());
14397        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
14398    }
14399
14400    #[test]
14401    fn decide_action_resumes_only_the_latest_resumable_run() {
14402        let home = crate::run::test_home();
14403        let t = held_task_with("r1");
14404        let q = action_question("r1", resume_action("r1"));
14405        let load = |s: RunState| move |_: &str| Ok(s);
14406        assert_eq!(
14407            decide_action(
14408                &home,
14409                &t,
14410                &q,
14411                &PHRASES_EN,
14412                load(run_state(RunStatus::Blocked))
14413            ),
14414            ActionDecision::Resume("r1".into())
14415        );
14416        // Not the latest run of the task.
14417        let q_other = action_question("r1", resume_action("r0"));
14418        assert!(matches!(
14419            decide_action(
14420                &home,
14421                &t,
14422                &q_other,
14423                &PHRASES_EN,
14424                load(run_state(RunStatus::Blocked))
14425            ),
14426            ActionDecision::Refuse(_)
14427        ));
14428        // A finished run cannot make progress.
14429        assert!(matches!(
14430            decide_action(
14431                &home,
14432                &t,
14433                &q,
14434                &PHRASES_EN,
14435                load(run_state(RunStatus::Ready))
14436            ),
14437            ActionDecision::Refuse(_)
14438        ));
14439        // A released one either.
14440        let mut released = run_state(RunStatus::Blocked);
14441        released.released_to = Some("elsewhere".into());
14442        assert!(matches!(
14443            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
14444            ActionDecision::Refuse(_)
14445        ));
14446        // Unreadable state is a refusal, never a fresh competition.
14447        assert!(matches!(
14448            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
14449            ActionDecision::Refuse(_)
14450        ));
14451    }
14452
14453    #[test]
14454    fn decide_action_ignores_a_question_about_an_earlier_run() {
14455        let home = crate::run::test_home();
14456        let mut t = held_task_with("r1");
14457        t.runs.push("r2".to_owned());
14458        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14459        assert_eq!(
14460            decide_action(
14461                &home,
14462                &t,
14463                &action_question("r1", ask::ChoiceAction::Done),
14464                &PHRASES_EN,
14465                never
14466            ),
14467            ActionDecision::Stale
14468        );
14469    }
14470
14471    #[test]
14472    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
14473        let home = crate::run::test_home();
14474        let mut t = held_task_with("r1");
14475        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14476        assert_eq!(
14477            decide_action(
14478                &home,
14479                &t,
14480                &action_question("r1", ask::ChoiceAction::Requeue),
14481                &PHRASES_EN,
14482                never
14483            ),
14484            ActionDecision::Requeue
14485        );
14486        let done_q = action_question("r1", ask::ChoiceAction::Done);
14487        assert_eq!(
14488            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14489            ActionDecision::Done
14490        );
14491        t.mark_action_applied(&done_q.id);
14492        assert_eq!(
14493            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14494            ActionDecision::Skip
14495        );
14496
14497        // A plain answer (no action for that label) does nothing.
14498        let mut plain = action_question("r1", ask::ChoiceAction::Done);
14499        plain.actions.clear();
14500        assert_eq!(
14501            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
14502            ActionDecision::Skip
14503        );
14504        // A running task is left alone.
14505        let mut running = held_task_with("r1");
14506        running.status = TaskStatus::Running;
14507        assert_eq!(
14508            decide_action(
14509                &home,
14510                &running,
14511                &action_question("r1", ask::ChoiceAction::Done),
14512                &PHRASES_EN,
14513                never
14514            ),
14515            ActionDecision::Skip
14516        );
14517    }
14518
14519    #[test]
14520    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
14521        crate::run::pin_test_home();
14522        for legacy in [false, true] {
14523            let dir = tempfile::tempdir().unwrap();
14524            let queue = Queue::at(dir.path().join("queue"));
14525            let questions = Questions::at(dir.path().join("questions"));
14526            let run = "20260101-000000-hold";
14527            let mut task = held_task_with(run);
14528            task.status = TaskStatus::Parked;
14529            let mut q = ask::Question::new(
14530                run.into(),
14531                land::APPROVAL_NODE.into(),
14532                "land".into(),
14533                "Repair?".into(),
14534                String::new(),
14535                vec![land::REPAIR.into()],
14536            );
14537            q.actions.insert(land::REPAIR.into(), resume_action(run));
14538            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14539            // Deterministically order the answer before the actual manual hold.
14540            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14541            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
14542            questions.put(&mut q).unwrap();
14543            task.hold_manual(Some("Keep this PR paused".into()));
14544            if legacy {
14545                task.hold_source = None;
14546            }
14547            queue.put(&mut task).unwrap();
14548
14549            apply_task_choice_actions(&queue, &questions, dir.path());
14550            let after = queue.get(&task.id).unwrap();
14551            assert!(after.operator_held());
14552            assert_eq!(after.hold_source, task.hold_source);
14553            assert_eq!(after.operator_decided_at, task.operator_decided_at);
14554            assert_eq!(after.runs, task.runs);
14555            assert_eq!(after.instruction, task.instruction);
14556            assert!(after.resume_override.is_none());
14557            assert!(after.action_applied(&q.id));
14558            let reason = after.hold_reason.as_deref().unwrap();
14559            assert!(reason.starts_with("Keep this PR paused"));
14560            assert!(reason.contains("later operator decision"));
14561            assert!(reason.contains(&format!("magi task release {}", task.id)));
14562
14563            for recovery in [
14564                crate::conduct::Recovery::Review,
14565                crate::conduct::Recovery::Requeue,
14566            ] {
14567                crate::conduct::apply(
14568                    &queue,
14569                    &questions,
14570                    &crate::conduct::Verdict {
14571                        decisions: vec![crate::conduct::Decision {
14572                            id: task.id.clone(),
14573                            recovery: Some(recovery),
14574                            ..Default::default()
14575                        }],
14576                    },
14577                )
14578                .unwrap();
14579            }
14580            // Reconciliation is idempotent, and automatic recovery cannot
14581            // reopen this owner after it observes the rejected repair answer.
14582            apply_task_choice_actions(&queue, &questions, dir.path());
14583            let still_held = queue.get(&task.id).unwrap();
14584            assert!(still_held.operator_held());
14585            assert_eq!(still_held.hold_reason, after.hold_reason);
14586            assert_eq!(still_held.runs, task.runs);
14587            assert!(still_held.review_branch.is_none());
14588            assert!(!still_held.fresh_start);
14589            assert!(queue.next_runnable().is_none());
14590        }
14591    }
14592
14593    #[test]
14594    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
14595        for held in [false, true] {
14596            for retry in [false, true] {
14597                let dir = tempfile::tempdir().unwrap();
14598                let queue = Queue::at(dir.path().join("queue"));
14599                let questions = Questions::at(dir.path().join("questions"));
14600                let home = dir.path().join("home");
14601                let mut t = task();
14602                if held {
14603                    t.hold_machine(Some("driver state unknown".into()));
14604                }
14605                queue.put(&mut t).unwrap();
14606                let verdict = serde_json::from_value(serde_json::json!({
14607                    "decisions": [{
14608                        "id": t.id,
14609                        "question": "Driver state unknown; retry the checks or hold?",
14610                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
14611                        "actions": {
14612                            "daemon: recheck and retry": {"do": "requeue"},
14613                            "daemon: hold the task": {"do": "hold"}
14614                        }
14615                    }]
14616                }))
14617                .unwrap();
14618                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
14619                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14620                let mut q = questions.list().pop().unwrap();
14621                let choice = if retry {
14622                    "daemon: recheck and retry"
14623                } else {
14624                    "daemon: hold the task"
14625                };
14626                assert_eq!(q.actions.len(), 2);
14627                q.answer(ask::Answer::Choice(choice.into())).unwrap();
14628                questions.put(&mut q).unwrap();
14629
14630                // A Web answer does not remove the deputy's fresh lease.
14631                questions.beat(&q.id, ask::WaiterKind::Deputy);
14632                for _ in 0..2 {
14633                    resolve_blockers(&queue, &questions);
14634                    apply_task_choice_actions(&queue, &questions, &home);
14635                    let waiting = queue.get(&t.id).unwrap();
14636                    assert_eq!(waiting.status, TaskStatus::Blocked);
14637                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
14638                    assert!(waiting.answers.is_empty());
14639                    assert!(!waiting.action_applied(&q.id));
14640                    assert!(runnable(&queue).is_empty());
14641                    let free = Arc::new(tokio::sync::Semaphore::new(1));
14642                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
14643                }
14644                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14645
14646                // Releasing the blocker and applying the operation share one save.
14647                resolve_blockers(&queue, &questions);
14648                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14649                apply_task_choice_actions(&queue, &questions, &home);
14650                let after = queue.get(&t.id).unwrap();
14651                assert_eq!(
14652                    after.status,
14653                    if retry {
14654                        TaskStatus::Queued
14655                    } else {
14656                        TaskStatus::Held
14657                    }
14658                );
14659                assert!(after.action_applied(&q.id));
14660                assert_eq!(after.operator_held(), !retry);
14661                assert_eq!(after.answers.len(), 1);
14662
14663                // A later operator decision must not replay this answer.
14664                let mut changed = after;
14665                if retry {
14666                    changed.hold_manual(Some("later hold".into()));
14667                } else {
14668                    changed.release_operator("test", None);
14669                }
14670                let expected = changed.status;
14671                queue.put(&mut changed).unwrap();
14672                apply_task_choice_actions(&queue, &questions, &home);
14673                assert_eq!(queue.get(&t.id).unwrap().status, expected);
14674            }
14675        }
14676    }
14677
14678    #[test]
14679    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
14680        let dir = tempfile::tempdir().unwrap();
14681        let queue = Queue::at(dir.path().join("queue"));
14682        let questions = Questions::at(dir.path().join("questions"));
14683        let home = dir.path().join("home");
14684        let mut state = run_state(RunStatus::Blocked);
14685        state.id = "20260101-000000-act1".to_owned();
14686        state.save_under(&home).unwrap();
14687
14688        let mut t = held_task_with(&state.id);
14689        queue.put(&mut t).unwrap();
14690        let mut q = action_question(&state.id, resume_action(&state.id));
14691        questions.put(&mut q).unwrap();
14692
14693        apply_task_choice_actions(&queue, &questions, &home);
14694        let after = queue.get(&t.id).unwrap();
14695        assert_eq!(after.status, TaskStatus::Queued);
14696        assert!(!after.fresh_start);
14697        assert!(after.action_applied(&q.id));
14698        let pin = after.resume_override.clone().unwrap();
14699        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
14700        assert!(pin.forced);
14701
14702        // Held again later: the same answer does not release it a second time.
14703        let mut again = queue.get(&t.id).unwrap();
14704        again.hold_machine(Some("later".into()));
14705        queue.put(&mut again).unwrap();
14706        apply_task_choice_actions(&queue, &questions, &home);
14707        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14708    }
14709
14710    #[test]
14711    fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
14712        let dir = tempfile::tempdir().unwrap();
14713        let home = dir.path();
14714        let queue = Queue::at(home.join("queue"));
14715        let questions = Questions::at(home.join("questions"));
14716        let mut state = run_state(RunStatus::Blocked);
14717        state.save_under(home).unwrap();
14718        let mut task = held_task_with(&state.id);
14719        queue.put(&mut task).unwrap();
14720        let mut question = action_question(&state.id, ask::ChoiceAction::Done);
14721        questions.put(&mut question).unwrap();
14722
14723        apply_task_choice_actions(&queue, &questions, home);
14724
14725        let after = queue.get(&task.id).unwrap();
14726        assert_eq!(after.status, TaskStatus::Held);
14727        assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
14728        assert_eq!(after.runs, task.runs);
14729        assert!(after.completion_history.is_empty());
14730        assert!(!after.decision_effects.contains_key(&question.id));
14731        assert_eq!(
14732            RunState::load_under(&state.id, home).unwrap().status,
14733            RunStatus::Blocked
14734        );
14735    }
14736
14737    #[test]
14738    fn a_delivered_answer_is_still_acted_on_exactly_once() {
14739        let dir = tempfile::tempdir().unwrap();
14740        let queue = Queue::at(dir.path().join("queue"));
14741        let questions = Questions::at(dir.path().join("questions"));
14742        let home = dir.path().join("home");
14743        let mut state = run_state(RunStatus::Blocked);
14744        state.id = "20260101-000000-act2".to_owned();
14745        state.save_under(&home).unwrap();
14746
14747        let mut t = held_task_with(&state.id);
14748        queue.put(&mut t).unwrap();
14749        let mut q = action_question(&state.id, resume_action(&state.id));
14750        q.answer_delivered = true;
14751        questions.put(&mut q).unwrap();
14752
14753        // Delivered, and the agent then died: the task is still held, so the
14754        // chosen action applies.
14755        apply_task_choice_actions(&queue, &questions, &home);
14756        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14757        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
14758
14759        // Held again: the same answer does nothing a second time.
14760        let mut again = queue.get(&t.id).unwrap();
14761        again.hold_machine(Some("later".into()));
14762        queue.put(&mut again).unwrap();
14763        apply_task_choice_actions(&queue, &questions, &home);
14764        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14765    }
14766
14767    #[test]
14768    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
14769        let dir = tempfile::tempdir().unwrap();
14770        let queue = Queue::at(dir.path().join("queue"));
14771        let questions = Questions::at(dir.path().join("questions"));
14772        let home = dir.path().join("home");
14773        let mut state = run_state(RunStatus::Blocked);
14774        state.id = "20260101-000000-act3".to_owned();
14775        state.save_under(&home).unwrap();
14776        let mut t = held_task_with(&state.id);
14777        queue.put(&mut t).unwrap();
14778        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
14779        questions.put(&mut q).unwrap();
14780
14781        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
14782        apply_task_choice_actions(&queue, &questions, &home);
14783        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14784
14785        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14786        apply_task_choice_actions(&queue, &questions, &home);
14787        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14788    }
14789
14790    #[test]
14791    fn action_standing_tells_the_reasons_apart() {
14792        let mut t = held_task_with("r1");
14793        let q = action_question("r1", ask::ChoiceAction::Requeue);
14794        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14795        let mut plain = q.clone();
14796        plain.actions.clear();
14797        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
14798
14799        // Applied wins over everything, even a running task.
14800        t.mark_action_applied(&q.id);
14801        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
14802
14803        // A newer attempt running: the old question is Stale, not Busy.
14804        let mut t = held_task_with("r1");
14805        t.start("r2".to_owned());
14806        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
14807        // The same question about the latest run just waits.
14808        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
14809        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14810        t.status = TaskStatus::Blocked;
14811        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14812
14813        // A conductor question is keyed by the task, never stale.
14814        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
14815        c.node = crate::conduct::NODE.to_owned();
14816        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
14817        assert!(!ActionStanding::Busy.daemon_owns());
14818    }
14819
14820    #[test]
14821    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
14822        let dir = tempfile::tempdir().unwrap();
14823        let queue = Queue::at(dir.path().join("queue"));
14824        let questions = Questions::at(dir.path().join("questions"));
14825        let home = dir.path().join("home");
14826        // Execution finished before task settlement; Done is not a discard.
14827        let mut state = run_state(RunStatus::Ready);
14828        state.id = "20260101-000000-act4".to_owned();
14829        state.save_under(&home).unwrap();
14830        let mut t = held_task_with(&state.id);
14831        t.status = TaskStatus::Running;
14832        queue.put(&mut t).unwrap();
14833        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
14834        q.cwd = Some(dir.path().display().to_string());
14835        questions.put(&mut q).unwrap();
14836
14837        // While the task runs the daemon will not act, so the waiter still
14838        // delivers the word to the dead asker's seat ...
14839        let running = queue.get(&t.id).unwrap();
14840        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
14841        assert!(matches!(
14842            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
14843            crate::waiter::Action::Deliver(_)
14844        ));
14845        // ... and the daemon waits while the task runs, then applies once.
14846        apply_task_choice_actions(&queue, &questions, &home);
14847        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14848        let mut back = queue.get(&t.id).unwrap();
14849        back.hold_machine(Some("later".into()));
14850        queue.put(&mut back).unwrap();
14851        apply_task_choice_actions(&queue, &questions, &home);
14852        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
14853        let mut again = queue.get(&t.id).unwrap();
14854        again.hold_machine(Some("again".into()));
14855        queue.put(&mut again).unwrap();
14856        apply_task_choice_actions(&queue, &questions, &home);
14857        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14858    }
14859}