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
2658#[doc(hidden)]
2659pub struct TaskWorkerLease {
2660    pub job: crate::worker::Job,
2661    dir: PathBuf,
2662    lease: Option<crate::worker::Lease>,
2663}
2664
2665impl TaskWorkerLease {
2666    pub fn release_lease(&mut self) {
2667        self.lease = None;
2668    }
2669}
2670
2671impl Drop for TaskWorkerLease {
2672    fn drop(&mut self) {
2673        self.release_lease();
2674        let _ = std::fs::remove_dir_all(&self.dir);
2675    }
2676}
2677
2678/// Reserve a task worker without launching a process, for integration tests.
2679#[doc(hidden)]
2680pub fn live_task_fixture(home: &Path, task: &str) -> Result<TaskWorkerLease> {
2681    let request = TaskWorker {
2682        opts: Opts::default(),
2683        queue: home.join("queue"),
2684        task: task.to_owned(),
2685        lane: PermitKind::default(),
2686        standalone: true,
2687    };
2688    let (job, lease) = crate::worker::running_fixture(
2689        home,
2690        &format!("task:{task}"),
2691        serde_json::to_value(request)?,
2692    )?;
2693    Ok(TaskWorkerLease {
2694        dir: home.join("workers").join("jobs").join(&job.id),
2695        job,
2696        lease: Some(lease),
2697    })
2698}
2699
2700fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2701    Ok(crate::worker::active(home)?
2702        .into_iter()
2703        .filter(|job| job.kind == "task")
2704        .collect())
2705}
2706
2707fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2708    task_jobs(home)?
2709        .into_iter()
2710        .filter_map(
2711            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2712                Ok(request) if !request.standalone => Some(Ok(job)),
2713                Ok(_) => None,
2714                Err(error) => Some(Err(error.into())),
2715            },
2716        )
2717        .collect()
2718}
2719
2720/// Whether an independent scheduler can be controlled without its web parent.
2721#[must_use]
2722pub fn managed(home: &Path) -> bool {
2723    match crate::worker::active(home) {
2724        Err(error) => {
2725            tracing::error!("cannot determine scheduler ownership: {error:#}");
2726            true
2727        }
2728        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2729        Ok(_) => {
2730            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2731                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2732        }
2733    }
2734}
2735
2736/// Start a detached, singleton scheduler using this executable generation.
2737pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2738    anyhow::ensure!(
2739        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2740        "the scheduler is stopping; wait for retirement before starting it again"
2741    );
2742    crate::worker::spawn(
2743        home,
2744        "scheduler",
2745        "scheduler",
2746        serde_json::to_value(opts.absolute()?)?,
2747    )
2748    .await
2749}
2750
2751fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2752    home.join("worker-parks").join(format!("{}.json", job.id))
2753}
2754
2755fn request_task_park(
2756    home: &Path,
2757    job: &crate::worker::Job,
2758    cause: crate::run::ParkCause,
2759) -> Result<()> {
2760    let path = park_request_path(home, job);
2761    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2762    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2763    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2764}
2765
2766/// Stop dispatch immediately; only an explicit park reaches existing workers.
2767pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2768    if control == crate::worker::Control::Park {
2769        for job in owned_task_jobs(home)? {
2770            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2771        }
2772    }
2773    crate::worker::request(home, "scheduler", control)
2774}
2775
2776/// Resolve what a restart would replace without signalling the scheduler.
2777pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
2778    if let Some(job) = crate::worker::active(home)?
2779        .into_iter()
2780        .find(|job| job.kind == "scheduler")
2781    {
2782        return serde_json::from_value(job.payload)
2783            .context("read detached scheduler options")
2784            .map(Some);
2785    }
2786    if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2787        && crate::worker::try_lease(home, "scheduler")?.is_none()
2788    {
2789        let path = home.join("scheduler-options.json");
2790        let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2791        return serde_json::from_slice(&body)
2792            .context("decode detached scheduler options")
2793            .map(Some);
2794    }
2795    Ok(None)
2796}
2797
2798/// Replace the scheduler, leaving all active task and conversation jobs alone.
2799pub async fn restart_detached(home: &Path) -> Result<()> {
2800    let Some(opts) = scheduler_restart_options(home)? else {
2801        return Ok(());
2802    };
2803    request_control(home, crate::worker::Control::Stop)?;
2804    loop {
2805        let reserved = crate::worker::active(home)?
2806            .iter()
2807            .any(|job| job.kind == "scheduler");
2808        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2809            break;
2810        }
2811        tokio::time::sleep(Duration::from_millis(100)).await;
2812    }
2813    spawn_detached(home, &opts).await?;
2814    Ok(())
2815}
2816
2817/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2818pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2819    let opts: Opts = serde_json::from_value(payload)?;
2820    let _ = home;
2821    serve_until(opts, Stop::new()).await
2822}
2823
2824/// Execute and settle one task with the queue claim owned by this process.
2825pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2826    let request: TaskWorker = serde_json::from_value(payload)?;
2827    let queue = Queue::at(request.queue);
2828    let key = format!("task:{}", request.task);
2829    let job = task_jobs(home)?
2830        .into_iter()
2831        .find(|job| job.key == key)
2832        .context("task worker reservation is missing")?;
2833    let park_path = park_request_path(home, &job);
2834    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2835    // our durable reservation. Never execute before that ownership hand-off.
2836    let _claim = loop {
2837        match queue.claim(&request.task) {
2838            Ok(claim) => break claim,
2839            // Only contention (the claim file exists) is worth waiting out; an
2840            // I/O failure must end this worker instead of pinning its lane.
2841            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2842                return Err(e.context("claim the task for its worker"));
2843            }
2844            Err(_) => {
2845                sweep_stale_claims(&queue, STALE_CLAIM);
2846                tokio::time::sleep(Duration::from_millis(50)).await;
2847            }
2848        }
2849    };
2850    let mut task = queue.get(&request.task)?;
2851    if !task.status.runnable()
2852        || (!request.standalone
2853            && request.lane
2854                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2855    {
2856        return Ok(());
2857    }
2858    let stop = Stop::new();
2859    let watcher = {
2860        let home = home.to_path_buf();
2861        let stop = stop.clone();
2862        let park_path = park_path.clone();
2863        tokio::spawn(async move {
2864            loop {
2865                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2866                    let cause = std::fs::read(&park_path)
2867                        .ok()
2868                        .and_then(|body| serde_json::from_slice(&body).ok())
2869                        .unwrap_or(crate::run::ParkCause::Operator);
2870                    stop.park(cause);
2871                    return;
2872                }
2873                tokio::time::sleep(Duration::from_millis(200)).await;
2874            }
2875        })
2876    };
2877    let quota = if request.standalone {
2878        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2879    } else {
2880        let status = Arc::new(Mutex::new(Status::new()));
2881        Box::pin(attempt(
2882            &request.opts,
2883            &queue,
2884            &status,
2885            &stop,
2886            crate::graph::Pause::new(),
2887            &mut task,
2888        ))
2889        .await
2890    };
2891    watcher.abort();
2892    let _ = std::fs::remove_file(park_path);
2893    persist_cooldown(home, &quota).await?;
2894    Ok(())
2895}
2896
2897/// Launch the standalone task worker with a claim-to-reservation handoff.
2898/// Returns only after the worker owns a durable execution reservation.
2899pub async fn spawn_claimed(
2900    home: &Path,
2901    opts: &Opts,
2902    queue: &Queue,
2903    task: &Task,
2904    claim: crate::queue::Claim,
2905) -> Result<crate::worker::Job> {
2906    let request = TaskWorker {
2907        opts: opts.absolute()?,
2908        queue: std::path::absolute(queue.root())?,
2909        task: task.id.clone(),
2910        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2911        standalone: true,
2912    };
2913    let job = crate::worker::spawn(
2914        home,
2915        "task",
2916        &format!("task:{}", task.id),
2917        serde_json::to_value(request)?,
2918    )
2919    .await?;
2920    drop(claim);
2921    Ok(job)
2922}
2923
2924/// Transfer a standalone caller's claim only after the detached worker is live,
2925/// then follow that worker to its final (non-automatically-retrying) outcome.
2926pub async fn run_detached_claimed(
2927    opts: &Opts,
2928    queue: &Queue,
2929    task: &mut Task,
2930    claim: crate::queue::Claim,
2931) -> Result<()> {
2932    let home = crate::run::home();
2933    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2934    loop {
2935        // Reconcile execution leases even without a scheduler. A dead worker
2936        // must become a reported failure, never an infinite persisted wait.
2937        crate::worker::active(&home)?;
2938        let current = crate::worker::get(&home, &job.id)?;
2939        if matches!(
2940            current.status,
2941            crate::worker::Status::Finished | crate::worker::Status::Failed
2942        ) {
2943            *task = queue.get(&task.id)?;
2944            anyhow::ensure!(
2945                current.status != crate::worker::Status::Failed,
2946                "task worker failed: {}",
2947                current.result.as_deref().unwrap_or("unknown failure")
2948            );
2949            return Ok(());
2950        }
2951        tokio::time::sleep(Duration::from_millis(200)).await;
2952    }
2953}
2954
2955async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2956    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2957        let _lease = loop {
2958            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2959                break lease;
2960            }
2961            tokio::time::sleep(Duration::from_millis(10)).await;
2962        };
2963        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2964            let path = home.join("task-quota-cooldown.json");
2965            let temporary = path.with_extension("json.tmp");
2966            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2967            std::fs::rename(temporary, path)?;
2968        }
2969    }
2970    Ok(())
2971}
2972
2973fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2974    match std::fs::read(home.join("task-quota-cooldown.json")) {
2975        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2976        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2977        Err(error) => Err(error.into()),
2978    }
2979}
2980
2981/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2982///
2983/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2984/// sets, so there is one loop body rather than two that drift apart the first
2985/// time the retry policy changes on only one of them.
2986pub async fn serve(opts: Opts) -> Result<()> {
2987    tracing::info!(
2988        "automatic update and restart requires magi web; standalone serve does not restart"
2989    );
2990    serve_until(opts, Stop::new()).await
2991}
2992
2993/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2994///
2995/// A stop retires dispatch promptly, including while a worker launch is being
2996/// acknowledged. Already reserved workers own their attempts independently and
2997/// finish with their started executable. Explicit park additionally forwards
2998/// durable park requests; neither scheduler retirement nor update does so.
2999///
3000/// While the queue is empty the stop is honoured within one wakeup rather than
3001/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
3002/// caller that taps stop does not sit through the remainder of a sleep.
3003pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
3004    let opts = opts.absolute()?;
3005    let home = crate::run::home();
3006    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
3007        .context("another scheduler already owns this home")?;
3008    if let Some(reading) = read_status(&home)
3009        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
3010    {
3011        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
3012    }
3013    if !crate::worker::active(&home)?
3014        .iter()
3015        .any(|job| job.kind == "scheduler")
3016    {
3017        crate::worker::clear_control(&home, "scheduler")?;
3018    }
3019    std::fs::write(
3020        home.join("scheduler-options.json"),
3021        serde_json::to_vec(&opts)?,
3022    )?;
3023    let control = {
3024        let home = home.clone();
3025        let stop = stop.clone();
3026        tokio::spawn(async move {
3027            loop {
3028                match crate::worker::control(&home, "scheduler").ok().flatten() {
3029                    Some(crate::worker::Control::Park) => {
3030                        let _ = request_control(&home, crate::worker::Control::Park);
3031                        stop.park(crate::run::ParkCause::Operator);
3032                        break;
3033                    }
3034                    Some(crate::worker::Control::Stop) => {
3035                        stop.stop();
3036                        break;
3037                    }
3038                    None => {}
3039                }
3040                tokio::time::sleep(Duration::from_millis(100)).await;
3041            }
3042        })
3043    };
3044    let signal = {
3045        let stop = stop.clone();
3046        tokio::spawn(async move {
3047            if tokio::signal::ctrl_c().await.is_ok() {
3048                stop.stop();
3049                tracing::info!("scheduler shutdown requested; independent workers continue");
3050            }
3051        })
3052    };
3053
3054    let worktrees_root = opts
3055        .worktrees_root
3056        .clone()
3057        .unwrap_or_else(crate::run::default_worktree_root);
3058    let outcome = drive(
3059        &opts,
3060        &Queue::open(),
3061        &status_path(),
3062        &crate::run::home(),
3063        &worktrees_root,
3064        &stop,
3065    )
3066    .await;
3067
3068    signal.abort();
3069    control.abort();
3070    outcome
3071}
3072
3073/// The loop proper: setup, poll, teardown, with the queue and the status file
3074/// supplied rather than discovered.
3075///
3076/// All three of `home`, `worktrees_root` and the queue/status paths are
3077/// parameters rather than resolved here, for the same reason:
3078/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
3079/// so a unit test that pinned it would fight every other test in the binary,
3080/// and a loop that resolved its own worktree bay could only be exercised
3081/// against the operator's real `~/wt/<repo>` - publishing over a live
3082/// daemon's status file, claiming tasks out of a live backlog, and, since
3083/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
3084/// whatever the operator actually has on disk.
3085async fn drive(
3086    opts: &Opts,
3087    queue: &Queue,
3088    status_file: &Path,
3089    home: &Path,
3090    worktrees_root: &Path,
3091    stop: &Stop,
3092) -> Result<()> {
3093    // The status file is a *snapshot*, not a stream of events: a reader only
3094    // ever wants the latest values, and every tick rewrites the whole file
3095    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
3096    // while an mpsc channel would force the loop to re-send unchanged fields on
3097    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
3098    // for no gain. The lock is only ever held across a field assignment, never
3099    // across an await.
3100    let recovery_cfg = prepare(&opts.repo, opts).ok();
3101    let daemon_cfg = recovery_cfg
3102        .as_ref()
3103        .map(|c| c.daemon.clone())
3104        .unwrap_or_default();
3105    let reconciled = crate::driver::reconcile(home);
3106    if !reconciled.is_empty() {
3107        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3108    }
3109    let mut initial_status = Status::new();
3110    let owned = owned_task_jobs(home)?;
3111    initial_status.current = current_work(home, Timestamp::now())
3112        .into_iter()
3113        .filter(|current| {
3114            owned
3115                .iter()
3116                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3117        })
3118        .collect();
3119    initial_status.idle = initial_status.current.is_empty();
3120    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3121        recovery_cfg.as_ref(),
3122        daemon_cfg.max_deputies,
3123    ));
3124    let status = Arc::new(Mutex::new(initial_status));
3125    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3126    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3127
3128    // Read once at startup, not per task: how many runs this loop drives at
3129    // once is a property of the machine running it, not of whichever
3130    // repository a given task happens to name - see
3131    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
3132    // fact in the same sense the agent roster is.
3133    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3134
3135    tracing::info!(
3136        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3137        queue.root().display(),
3138        opts.poll.as_secs(),
3139        opts.max_attempts,
3140        concurrency,
3141        if daemon_cfg.pause_for_interrupts {
3142            ", interrupts enabled"
3143        } else {
3144            ""
3145        }
3146    );
3147
3148    let outcome = tokio::select! {
3149        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3150            max_concurrent: concurrency,
3151            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3152            recovery_cfg,
3153        }) => outcome,
3154        () = async {
3155            while !stop.stopped() {
3156                tokio::time::sleep(Duration::from_millis(25)).await;
3157            }
3158        } => {
3159            if stop.parking() {
3160                request_control(home, crate::worker::Control::Park)?;
3161            }
3162            Ok(())
3163        }
3164    };
3165
3166    stop.busy.store(0, Ordering::SeqCst);
3167    beat.abort();
3168    clear_status_at(status_file);
3169    outcome
3170}
3171
3172/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3173/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3174pub(crate) fn release_watch_settings_from_config(
3175    home: &Path,
3176    repo: &Path,
3177    cfg: &Config,
3178) -> (Vec<PathBuf>, u64) {
3179    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3180        .into_iter()
3181        .map(|r| r.path)
3182        .collect();
3183    // Repositories the daemon has worked in, wherever they live: a task may
3184    // name one outside `[repos] roots`, and its release PR must be watched too.
3185    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3186        .list()
3187        .into_iter()
3188        .map(|t| t.repo)
3189        .collect();
3190    let runs = home.join("runs");
3191    for id in crate::run::list_ids_in(&runs) {
3192        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3193            .ok()
3194            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3195            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3196        known.extend(repo);
3197    }
3198    for k in known {
3199        let k = k.canonicalize().unwrap_or(k);
3200        if k.join(".git").exists() && !paths.contains(&k) {
3201            paths.push(k);
3202        }
3203    }
3204    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3205    if !paths.contains(&own) {
3206        paths.push(own);
3207    }
3208    (paths, cfg.daemon.release_stall_minutes)
3209}
3210
3211/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3212const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3213
3214/// Refresh the status file on a fixed tick.
3215///
3216/// Separate from the loop because a run takes tens of minutes: a status file
3217/// written only between tasks would look stale for the whole of every run, and
3218/// a reader would report the daemon dead exactly while it was busiest.
3219async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3220    loop {
3221        tokio::time::sleep(HEARTBEAT).await;
3222        let snapshot = {
3223            let mut guard = lock(&status);
3224            guard.updated_at = Timestamp::now();
3225            guard.clone()
3226        };
3227        if let Err(e) = write_status_to(&path, &snapshot) {
3228            // A failed heartbeat must not take the daemon down: the loop is the
3229            // product, the status file is only the window onto it.
3230            tracing::warn!("could not refresh the daemon status file: {e:#}");
3231        }
3232    }
3233}
3234
3235/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3236/// if so, whether that wait is over.
3237#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3238enum LandResume {
3239    /// The task's last run is not parked on a land approval; schedule it
3240    /// like any other candidate.
3241    NotLanding,
3242    /// Parked in `land`, waiting on a question nobody has answered yet.
3243    /// Left alone: attempting it now would only re-observe the same pull
3244    /// request and park again, spending a `gh` call on a decision that has
3245    /// not changed since the last time this was checked.
3246    StillWaiting,
3247    /// Parked in `land`, and the question is settled - answered or
3248    /// abandoned. Resuming this is the one kind of candidate that must not
3249    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3250    Ready,
3251}
3252
3253/// Classify a runnable candidate by whether it is parked on a land-merge
3254/// approval. Read-only - no claim taken, nothing written - so it is cheap
3255/// enough to call on every candidate, every poll.
3256fn land_resume_state(task: &Task) -> LandResume {
3257    if task.sync_only.is_some() {
3258        return LandResume::NotLanding;
3259    }
3260    let Some(run_id) = task.execution_runs().last() else {
3261        return LandResume::NotLanding;
3262    };
3263    let Ok(state) = RunState::load(run_id) else {
3264        return LandResume::NotLanding;
3265    };
3266    if !state.parked {
3267        return LandResume::NotLanding;
3268    }
3269    if state.status == RunStatus::Landing
3270        && state.land_approval.as_ref().is_some_and(|binding| {
3271            ask::Questions::open()
3272                .get_for_effects(&binding.question)
3273                .is_ok_and(|q| {
3274                    q.run == state.id
3275                        && q.resolution()
3276                            .as_deref()
3277                            .is_some_and(crate::merge_decision::stops)
3278                })
3279        })
3280    {
3281        return LandResume::Ready;
3282    }
3283    if !implementers_match(task, &state) {
3284        return LandResume::NotLanding;
3285    }
3286    // Parked in `land` on the merge approval, or at `merge` on the owner's
3287    // word about a title/body the posting gate withheld. Told apart by the
3288    // run's own record, not by a status both can share.
3289    let node = if state.status == RunStatus::Landing {
3290        land::APPROVAL_NODE
3291    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3292        crate::github_text::ASK_NODE
3293    } else {
3294        return LandResume::NotLanding;
3295    };
3296    let store = ask::Questions::open();
3297    let waiting = store
3298        .list_for_effects()
3299        .into_iter()
3300        .filter(|q| &q.run == run_id && q.node == node)
3301        .max_by(|a, b| a.id.cmp(&b.id));
3302    let Some(mut q) = waiting else {
3303        return LandResume::Ready;
3304    };
3305    if !q.status.open() {
3306        // Repair spends agent resources and must obey concurrency and quota
3307        // waits; only a merge/hold decision may use the decision-only lane.
3308        if q.resolution().as_deref() == Some(land::REPAIR) {
3309            return if state.liveness(false) == Liveness::Live {
3310                LandResume::StillWaiting
3311            } else {
3312                LandResume::NotLanding
3313            };
3314        }
3315        return LandResume::Ready;
3316    }
3317    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3318    // nobody ever answered; land's approval bypasses that wait entirely (see
3319    // `land::approval_gate`), so the same deadline has to be enforced here
3320    // instead, or `graph.answer_timeout` silently stops meaning anything for
3321    // a land approval and a run can sit `StillWaiting` forever with nobody
3322    // told to look at it.
3323    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3324    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3325    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3326        q.abandon(format!(
3327            "no answer within {}s of asking",
3328            timeout.as_secs().max(1)
3329        ));
3330        // If this can't be persisted, do not treat the wait as settled on a
3331        // guess: fall through and try again next poll.
3332        if store.put(&mut q).is_ok() {
3333            return LandResume::Ready;
3334        }
3335    }
3336    LandResume::StillWaiting
3337}
3338
3339/// How often the loop rechecks for new work while something it already
3340/// started is still running, rather than sleeping out the whole
3341/// [`Opts::poll`] interval.
3342///
3343/// Short on purpose: this is what lets a land-merge approval that comes back
3344/// while another task is mid-competition be noticed and resumed within a
3345/// fraction of a second, not within the next multi-second poll.
3346const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3347
3348/// How often [`poll`] rechecks the shared build cache against its cap at a
3349/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3350/// waiting for the queue to run dry.
3351///
3352/// A queue that never empties means the `janitor` call at the bottom of this
3353/// loop's fully-idle branch can go unreached for as long as the backlog
3354/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3355/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3356/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3357/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3358/// backlog of short tasks does not pay for that walk on every poll.
3359const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3360
3361/// State of [`poll`]'s own interrupt-scheduling sequence - see
3362/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3363/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3364/// both kept free of `Task`'s non-identity fields on purpose: every decision
3365/// here turns only on task ids and which ones are in flight, so the "never
3366/// more than one run at once" and "exactly one resume" invariants can be
3367/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3368/// queue - which is exactly the coverage this feature's first two attempts
3369/// were missing.
3370///
3371/// Persisted after every transition, so scheduler replacement preserves the
3372/// interrupt's exclusive turn and the interrupted task's priority resume.
3373#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3374enum Interrupt {
3375    /// No interrupt sequence in progress. Ordinary dispatch applies.
3376    Idle,
3377    /// `interrupt_task` is runnable and exactly one other run is in flight;
3378    /// `parked` names that one task's id. Dispatch is withheld from
3379    /// everyone, including `interrupt_task` itself, until it has left
3380    /// flight - only then is `interrupt_task` let through.
3381    ///
3382    /// `parked` is a `Vec` rather than a bare id for symmetry with
3383    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3384    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3385    /// when exactly one run is in flight, so it is guaranteed to hold
3386    /// exactly one entry in practice - see that branch's own doc for why
3387    /// more than one is deliberately never attempted.
3388    Parking {
3389        parked: Vec<String>,
3390        interrupt_task: String,
3391    },
3392    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3393    /// withheld from everyone until it leaves flight - merged, failed, held,
3394    /// it makes no difference - at which point the sequence moves to
3395    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3396    /// going straight to `Idle` would hand `parked` back to ordinary
3397    /// priority-order dispatch, where a higher-priority task filed in the
3398    /// meantime could start ahead of it.
3399    Running {
3400        parked: Vec<String>,
3401        interrupt_task: String,
3402    },
3403    /// `interrupt_task` left flight; `parked` still names the one run this
3404    /// sequence owes a resume. Dispatch is withheld from everyone except
3405    /// that task - see [`interrupt_gate`] - so the resume this feature
3406    /// promises is never raced by, or run alongside, an unrelated candidate.
3407    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3408    /// own doc on abandonment - the moment it is no longer runnable at all.
3409    Resuming { parked: Vec<String> },
3410}
3411
3412/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3413/// and `runnable` are read-only snapshots of this tick's reality, and the
3414/// only side effect the caller still owes the world is asking whichever
3415/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3416/// site.
3417///
3418/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3419/// accepted rather than a narrower type because that is what [`poll`] already
3420/// has on hand from [`runnable`], and building a second, smaller list on
3421/// every tick just to satisfy this signature would cost more than it proves.
3422///
3423/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3424/// back to a task they are waiting on no longer being [`runnable`] - held,
3425/// blocked, deleted, or finished by some other means entirely, all of which
3426/// an operator can do to a task sitting in the queue with no claim on it at
3427/// all, at any moment, interrupt sequence or not. Without this check the
3428/// sequence would wait forever for a dispatch that can never come, and
3429/// `interrupt_gate` would withhold every other task in the queue right along
3430/// with it - a single `magi task hold` on the wrong id turning into a
3431/// daemon that never dispatches anything again.
3432fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3433    match state {
3434        Interrupt::Idle => {
3435            // Not just "something to interrupt": exactly one thing. More
3436            // than one run in flight only happens above the default
3437            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3438            // one resume, never run alongside anything else" only because
3439            // it is only ever seeded with exactly one id - see
3440            // `Interrupt::Resuming`'s own doc on why releasing more than one
3441            // parked id back to ordinary dispatch cannot be made safe
3442            // against that same setting's own extra concurrency slots.
3443            // Waiting here for the herd to settle to one is the
3444            // simplification this feature's own constraints ask for rather
3445            // than a second concurrency model to reconcile with the first.
3446            if in_flight.len() != 1 {
3447                return Interrupt::Idle;
3448            }
3449            match runnable.iter().find(|t| t.interrupt) {
3450                Some(t) => Interrupt::Parking {
3451                    parked: in_flight.to_vec(),
3452                    interrupt_task: t.id.clone(),
3453                },
3454                None => Interrupt::Idle,
3455            }
3456        }
3457        Interrupt::Parking {
3458            parked,
3459            interrupt_task,
3460        } => {
3461            if in_flight.iter().any(|id| parked.contains(id)) {
3462                // Still waiting for what was in flight to actually stop.
3463                Interrupt::Parking {
3464                    parked,
3465                    interrupt_task,
3466                }
3467            } else if in_flight.contains(&interrupt_task) {
3468                Interrupt::Running {
3469                    parked,
3470                    interrupt_task,
3471                }
3472            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3473                // The parked run(s) are gone, but the interrupt task has not
3474                // been dispatched yet on this tick - `interrupt_gate` is
3475                // what lets it through next.
3476                Interrupt::Parking {
3477                    parked,
3478                    interrupt_task,
3479                }
3480            } else {
3481                // The interrupt task itself is no longer runnable - see this
3482                // function's own doc on abandonment. The parked run(s) still
3483                // get their guaranteed resume; there is simply no interrupt
3484                // to run ahead of them any longer.
3485                Interrupt::Resuming { parked }
3486            }
3487        }
3488        Interrupt::Running {
3489            parked,
3490            interrupt_task,
3491        } => {
3492            if in_flight.contains(&interrupt_task) {
3493                Interrupt::Running {
3494                    parked,
3495                    interrupt_task,
3496                }
3497            } else {
3498                // The interrupt task's own run reached a terminal status,
3499                // whichever one - this is the *only* trigger that moves the
3500                // sequence on, driven straight off the same in-flight
3501                // bookkeeping `poll` already reaps every tick, not a second,
3502                // independent poll of anything.
3503                Interrupt::Resuming { parked }
3504            }
3505        }
3506        Interrupt::Resuming { parked } => {
3507            if in_flight.iter().any(|id| parked.contains(id)) {
3508                // One of the parked runs has been dispatched - the resume
3509                // this sequence owed is fulfilled. Whatever else is left in
3510                // `parked` (ordinarily nothing, at the default concurrency
3511                // of one) rejoins ordinary priority-order dispatch, same as
3512                // any other runnable task.
3513                Interrupt::Idle
3514            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3515                Interrupt::Resuming { parked }
3516            } else {
3517                // Abandonment (see this function's own doc): nothing left in
3518                // `parked` is even runnable any longer.
3519                Interrupt::Idle
3520            }
3521        }
3522    }
3523}
3524
3525/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3526/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3527/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3528/// indistinguishable from any other runnable task - exactly the "off does
3529/// nothing" this feature promises.
3530fn advance_interrupt_tick(
3531    enabled: bool,
3532    state: Interrupt,
3533    in_flight: &[String],
3534    runnable: &[Task],
3535) -> Interrupt {
3536    if !enabled {
3537        return Interrupt::Idle;
3538    }
3539    advance_interrupt(state, in_flight, runnable)
3540}
3541
3542/// Which of this tick's runnable candidates the interrupt sequence actually
3543/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3544/// each half is assertable on its own: this is the half that keeps a
3545/// competition and an interrupt from ever running at the same moment.
3546fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3547    match state {
3548        Interrupt::Idle => candidates,
3549        Interrupt::Parking {
3550            parked,
3551            interrupt_task,
3552        } => {
3553            if in_flight.iter().any(|id| parked.contains(id)) {
3554                Vec::new()
3555            } else {
3556                candidates
3557                    .into_iter()
3558                    .filter(|t| &t.id == interrupt_task)
3559                    .collect()
3560            }
3561        }
3562        Interrupt::Running { .. } => Vec::new(),
3563        // At most one: even if `parked` names more than one id (more than
3564        // one run was in flight when the sequence began, only possible
3565        // above the default `max_concurrent_runs = 1`), only the first match
3566        // is offered. Capping this to a single candidate - not merely to
3567        // `parked`'s own ids - is what makes "exactly one resume, never two
3568        // dispatched together" true regardless of how many ordinary slots
3569        // happen to be free this tick.
3570        Interrupt::Resuming { parked } => candidates
3571            .into_iter()
3572            .find(|t| parked.contains(&t.id))
3573            .into_iter()
3574            .collect(),
3575    }
3576}
3577
3578/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3579/// bundled into one parameter so `poll`'s own signature stays readable -
3580/// see [`drive`]'s call site for where these are actually read.
3581struct DispatchLimits {
3582    /// How many *ordinary* candidates run at once. See
3583    /// [`crate::config::Daemon::max_concurrent_runs`].
3584    max_concurrent: usize,
3585    /// See [`crate::config::Daemon::pause_for_interrupts`].
3586    pause_for_interrupts: bool,
3587    recovery_cfg: Option<Config>,
3588}
3589
3590/// Which semaphore, if any, dispatching a candidate should draw its permit
3591/// from.
3592///
3593/// Pure and separate from [`poll`]'s loop body for the same reason
3594/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3595/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3596/// exactly the policy this feature adds, and a policy only exercisable by
3597/// running the whole loop is a policy nobody checks.
3598#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3599enum PermitKind {
3600    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3601    /// Checked first - a task can be both a land resume and marked
3602    /// [`Task::urgent`], and the resume's own "must not queue behind
3603    /// anything" guarantee takes precedence.
3604    None,
3605    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3606    /// (never in addition to trying) the ordinary pool. This is what lets
3607    /// an urgent task dispatch while every ordinary slot is already checked
3608    /// out, and what stops a second urgent task from opening a third run: it
3609    /// waits on this same one-slot semaphore rather than falling through to
3610    /// the ordinary one.
3611    Urgent,
3612    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3613    /// above.
3614    #[default]
3615    Ordinary,
3616}
3617
3618/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3619/// own boolean, already computed by the caller from [`land_resume_state`].
3620fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3621    if priority {
3622        PermitKind::None
3623    } else if urgent {
3624        PermitKind::Urgent
3625    } else {
3626        PermitKind::Ordinary
3627    }
3628}
3629
3630fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3631    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3632        (0usize, 0usize),
3633        |(ordinary, urgent), request| match request.lane {
3634            PermitKind::Ordinary => (ordinary + 1, urgent),
3635            PermitKind::Urgent => (ordinary, urgent + 1),
3636            PermitKind::None => (ordinary, urgent),
3637        },
3638    );
3639    (
3640        limit.saturating_sub(ordinary),
3641        1usize.saturating_sub(urgent),
3642    )
3643}
3644
3645/// Why a runnable candidate was not dispatched. This does not alter policy.
3646#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3647enum SkipReason {
3648    ClaimUnavailable,
3649    RereadFailed,
3650    NoLongerRunnable,
3651    WaitingOnLanding,
3652    CoolingDown,
3653    OrdinaryCapacity,
3654    UrgentCapacity,
3655    InterruptGate,
3656}
3657
3658impl SkipReason {
3659    fn key(self) -> &'static str {
3660        match self {
3661            Self::ClaimUnavailable => "claim_unavailable",
3662            Self::RereadFailed => "reread_failed",
3663            Self::NoLongerRunnable => "no_longer_runnable",
3664            Self::WaitingOnLanding => "waiting_on_landing",
3665            Self::CoolingDown => "cooling_down",
3666            Self::OrdinaryCapacity => "ordinary_capacity",
3667            Self::UrgentCapacity => "urgent_capacity",
3668            Self::InterruptGate => "interrupt_gate",
3669        }
3670    }
3671
3672    fn describe(self) -> &'static str {
3673        match self {
3674            Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3675            Self::RereadFailed => "could not re-read it",
3676            Self::NoLongerRunnable => "no longer runnable",
3677            Self::WaitingOnLanding => "waiting on landing",
3678            Self::CoolingDown => "quota cooldown",
3679            Self::OrdinaryCapacity => "no free ordinary slot",
3680            Self::UrgentCapacity => "urgent slot busy",
3681            Self::InterruptGate => "withheld by the interrupt sequence",
3682        }
3683    }
3684}
3685
3686/// A reason count from a completed dispatch scan.
3687#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3688pub struct DispatchReasonCount {
3689    /// Stable string key, so readers can preserve future reasons.
3690    pub reason: String,
3691    /// Candidates skipped for this reason.
3692    pub count: usize,
3693}
3694
3695/// Observations from a completed scan, not a fresh queue estimate.
3696#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3697pub struct DispatchWait {
3698    /// Runnable candidates before the interrupt gate.
3699    pub runnable: usize,
3700    /// Counts in descending order, with stable reason order for ties.
3701    pub reasons: Vec<DispatchReasonCount>,
3702}
3703
3704type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3705
3706fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3707    if runnable == 0 {
3708        return None;
3709    }
3710    let mut counts = std::collections::BTreeMap::new();
3711    for (_, reason) in skips {
3712        *counts.entry(*reason).or_insert(0usize) += 1;
3713    }
3714    let mut counts: Vec<_> = counts.into_iter().collect();
3715    counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3716    Some(DispatchWait {
3717        runnable,
3718        reasons: counts
3719            .into_iter()
3720            .map(|(reason, count)| DispatchReasonCount {
3721                reason: reason.key().to_owned(),
3722                count,
3723            })
3724            .collect(),
3725    })
3726}
3727
3728fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3729    before
3730        .iter()
3731        .filter(|id| !after.iter().any(|task| &task.id == *id))
3732        .map(|id| (id.clone(), SkipReason::InterruptGate))
3733        .collect()
3734}
3735
3736fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3737    if *previous == current {
3738        return false;
3739    }
3740    *previous = current;
3741    true
3742}
3743
3744struct DispatchClaim {
3745    task: Task,
3746    claim: crate::queue::Claim,
3747    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3748}
3749
3750/// Claim and re-read before choosing a lane: a queue listing may predate an
3751/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3752fn claim_dispatch(
3753    queue: &Queue,
3754    candidate: &Task,
3755    cooling_down: bool,
3756    ordinary: &Arc<tokio::sync::Semaphore>,
3757    urgent: &Arc<tokio::sync::Semaphore>,
3758) -> std::result::Result<DispatchClaim, SkipReason> {
3759    let claim = queue
3760        .claim(&candidate.id)
3761        .map_err(|_| SkipReason::ClaimUnavailable)?;
3762    let task = match queue.get(&candidate.id) {
3763        Ok(t) if t.status.runnable() => t,
3764        Ok(_) => return Err(SkipReason::NoLongerRunnable),
3765        Err(e) => {
3766            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3767            return Err(SkipReason::RereadFailed);
3768        }
3769    };
3770    let resume = land_resume_state(&task);
3771    if resume == LandResume::StillWaiting {
3772        return Err(SkipReason::WaitingOnLanding);
3773    }
3774    let priority = resume == LandResume::Ready;
3775    if !priority && cooling_down {
3776        return Err(SkipReason::CoolingDown);
3777    }
3778    // Never borrow an ordinary slot when the single urgent slot is busy.
3779    // Keep scanning other candidates when either pool has no free slot.
3780    let permit = match permit_kind(priority, task.urgent) {
3781        PermitKind::None => None,
3782        PermitKind::Urgent => Some(
3783            Arc::clone(urgent)
3784                .try_acquire_owned()
3785                .map_err(|_| SkipReason::UrgentCapacity)?,
3786        ),
3787        PermitKind::Ordinary => Some(
3788            Arc::clone(ordinary)
3789                .try_acquire_owned()
3790                .map_err(|_| SkipReason::OrdinaryCapacity)?,
3791        ),
3792    };
3793    // Persist the dispatch order under the claim, before config discovery or
3794    // coordination waits can reorder concurrent starts.
3795    let stamp = Timestamp::now();
3796    let mut task = task;
3797    task.dispatched_at = Some(stamp);
3798    if let Err(e) = queue.modify(&task.id, |t| {
3799        t.dispatched_at = Some(stamp);
3800        true
3801    }) {
3802        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3803    }
3804    Ok(DispatchClaim {
3805        task,
3806        claim,
3807        permit,
3808    })
3809}
3810
3811/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3812/// teardown and cannot skip the teardown on an early return.
3813///
3814/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3815/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3816/// land approval that has since been answered is dispatched outside that
3817/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3818/// the whole point of parking there is that it must not queue behind
3819/// whatever else the loop happens to be running, even at the default of one.
3820/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3821/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3822/// these exemptions is still subject to the interrupt gate below, urgent
3823/// included: a land-resume or urgent candidate is exactly as much "something
3824/// else running" as an ordinary one from the interrupt sequence's point of
3825/// view, and letting either slip through while a run is being parked, or
3826/// while the interrupt task itself has the floor, is precisely the second
3827/// run 75dd's own "at most one run, ever, at once" guarantee must never
3828/// allow - see [`Interrupt`]'s own doc.
3829#[derive(Serialize, Deserialize)]
3830struct ServiceWorker {
3831    opts: Opts,
3832    queue: PathBuf,
3833    worktrees_root: PathBuf,
3834    operation: String,
3835}
3836
3837fn load_conductor(home: &Path) -> Result<Conductor> {
3838    match std::fs::read(home.join("conductor-state.json")) {
3839        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3840        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3841        Err(error) => Err(error.into()),
3842    }
3843}
3844
3845fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3846    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3847        .into_iter()
3848        .map(|c| c.task)
3849        .collect();
3850    let stalled = stalled_tasks(queue, home, Timestamp::now());
3851    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3852    let finished = finished_tasks(queue)
3853        .into_iter()
3854        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3855        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3856        .collect();
3857    let queued = queued_tasks(queue)
3858        .into_iter()
3859        .filter(|t| !live.contains(&t.id))
3860        .collect();
3861    (queued, stalled, finished)
3862}
3863
3864// Separate latest dispatch and worker receipts expose version handoff and skips
3865// without erasing the last completed scan or treating observations as authority.
3866fn retention_service_receipt(
3867    home: &Path,
3868    operation: &str,
3869    phase: &str,
3870    outcome: &str,
3871    detail: &str,
3872    cfg: Option<&Config>,
3873) {
3874    if !matches!(operation, "housekeeping" | "disk-pressure") {
3875        return;
3876    }
3877    let receipt = serde_json::json!({"checked_at": Timestamp::now(),
3878        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
3879        "operation": operation, "outcome": outcome, "detail": detail,
3880        "auto_fold": cfg.map(|c| c.disk.auto_fold),
3881        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
3882    if let Err(error) = crate::fold_evidence::atomic_write(
3883        &home.join(format!("source-eviction-{operation}-{phase}.json")),
3884        &serde_json::to_vec(&receipt).expect("service receipt"),
3885    ) {
3886        tracing::warn!("retention service receipt failed: {error:#}");
3887    }
3888}
3889
3890async fn start_service(
3891    home: &Path,
3892    opts: &Opts,
3893    queue: &Queue,
3894    worktrees_root: &Path,
3895    operation: &str,
3896    cfg: Option<&Config>,
3897    busy: bool,
3898) -> Result<()> {
3899    // Fetch policy is live configuration, unlike question recovery capacity.
3900    // Reload before both cadence and eligibility, including disabled -> enabled.
3901    let fetch_cfg = if operation == "fetch" {
3902        match prepare(&opts.repo, opts) {
3903            Ok(cfg) => Some(cfg),
3904            Err(error) => {
3905                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3906                return Ok(());
3907            }
3908        }
3909    } else {
3910        None
3911    };
3912    let cfg = fetch_cfg.as_ref().or(cfg);
3913    let ticks = home.join("service-ticks");
3914    std::fs::create_dir_all(&ticks)?;
3915    let receipt = ticks.join(format!("daemon-{operation}"));
3916    let last = std::fs::read(&receipt)
3917        .ok()
3918        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3919    let interval = match operation {
3920        "disk-pressure" => 30,
3921        "chat-goals" => 60,
3922        "cache" => CACHE_CHECK_INTERVAL_SECS,
3923        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3924        _ => opts.poll.as_secs().max(1),
3925    };
3926    let now = Timestamp::now();
3927    if !cache_check_due(last, now, interval) {
3928        retention_service_receipt(
3929            home,
3930            operation,
3931            "dispatch",
3932            "skipped",
3933            "cadence not due",
3934            cfg,
3935        );
3936        return Ok(());
3937    }
3938    let key = format!("service:daemon-{operation}");
3939    if crate::worker::active(home)?
3940        .iter()
3941        .any(|job| job.key == key)
3942    {
3943        retention_service_receipt(
3944            home,
3945            operation,
3946            "dispatch",
3947            "skipped",
3948            "service worker already active",
3949            cfg,
3950        );
3951        return Ok(());
3952    }
3953    let eligible = match operation {
3954        "conductor" => {
3955            let (queued, stalled, finished) = conductor_work(queue, home);
3956            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3957                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3958        }
3959        "maintenance" => {
3960            queue.list().iter().any(|task| {
3961                crate::triage::disk_wait_eligible(task)
3962                    && task
3963                        .disk_checked_at
3964                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
3965            }) || Questions::at(home.join("questions"))
3966                .list_for_effects()
3967                .iter()
3968                .any(|q| {
3969                    q.chosen_action().is_some_and(|action| action.maintenance())
3970                        && !home
3971                            .join("choice-actions")
3972                            .join(format!("{}.json", q.id))
3973                            .exists()
3974                })
3975        }
3976        "housekeeping" => !busy && runnable(queue).is_empty(),
3977        "cache" => {
3978            !busy
3979                && !runnable(queue).is_empty()
3980                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3981        }
3982        "disk-pressure" => busy,
3983        "fetch" => {
3984            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3985        }
3986        "chat-goals" => crate::talk::Talks::at(home.join("talks"))
3987            .list()
3988            .iter()
3989            .any(|talk| {
3990                talk.status.open()
3991                    && talk.pending.is_empty()
3992                    && talk.pending_attachments.is_empty()
3993                    && talk.goals.iter().any(|goal| goal.active())
3994            }),
3995        _ => false,
3996    };
3997    if !eligible {
3998        retention_service_receipt(
3999            home,
4000            operation,
4001            "dispatch",
4002            "skipped",
4003            if operation == "housekeeping" {
4004                "active work or runnable task queue"
4005            } else {
4006                "no active work; idle housekeeping owns scan"
4007            },
4008            cfg,
4009        );
4010        return Ok(());
4011    }
4012    retention_service_receipt(
4013        home,
4014        operation,
4015        "dispatch",
4016        "launching",
4017        "eligible and cadence due",
4018        cfg,
4019    );
4020    let request = ServiceWorker {
4021        opts: opts.absolute()?,
4022        queue: std::path::absolute(queue.root())?,
4023        worktrees_root: std::path::absolute(worktrees_root)?,
4024        operation: operation.to_owned(),
4025    };
4026    if let Err(error) =
4027        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
4028    {
4029        retention_service_receipt(
4030            home,
4031            operation,
4032            "dispatch",
4033            "error",
4034            &format!("worker launch: {error:#}"),
4035            cfg,
4036        );
4037        tracing::warn!(operation, "could not launch daemon service: {error:#}");
4038    }
4039    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
4040    Ok(())
4041}
4042
4043/// Finite maintenance jobs survive scheduler replacement without duplicating
4044/// agent calls or cancelling an operation between its effect and receipt.
4045pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
4046    let request: ServiceWorker = serde_json::from_value(payload)?;
4047    let opts = &request.opts;
4048    let queue = Queue::at(request.queue);
4049    let questions = Questions::at(home.join("questions"));
4050    match request.operation.as_str() {
4051        "chat-goals" => {
4052            let talks = crate::talk::Talks::at(home.join("talks"));
4053            crate::chat_goal_runtime::sweep(&talks, false).await;
4054        }
4055        "maintenance" => {
4056            apply_maintenance_choices(&queue, &questions, home).await;
4057            triage::monitor_disk_waits(
4058                &queue,
4059                &questions,
4060                opts.config.as_deref(),
4061                Timestamp::now(),
4062            );
4063        }
4064        "conductor" => {
4065            let path = home.join("conductor-state.json");
4066            let mut conductor = load_conductor(home)?;
4067            let (queued, stalled, finished) = conductor_work(&queue, home);
4068            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4069                && conductor.worth_a_look(&queue, &stalled, &finished)
4070            {
4071                let cfg = prepare(&opts.repo, opts)?;
4072                conductor
4073                    .maybe_run(
4074                        &cfg,
4075                        &opts.repo,
4076                        &queue,
4077                        &questions,
4078                        home,
4079                        &queued,
4080                        &stalled,
4081                        &finished,
4082                        opts.max_attempts,
4083                    )
4084                    .await;
4085                let temporary = path.with_extension("json.tmp");
4086                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
4087                std::fs::rename(temporary, path)?;
4088            }
4089        }
4090        "fetch" => {
4091            let cfg = prepare(&opts.repo, opts)?;
4092            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
4093                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
4094                tracing::debug!("fetch origins: {outcome:?}");
4095            }
4096        }
4097        "cache" => {
4098            if task_jobs(home)?.is_empty() {
4099                let mut checked = None;
4100                maybe_prune_cache_between_runs(
4101                    &opts.repo,
4102                    opts,
4103                    home,
4104                    &Stop::new(),
4105                    &mut checked,
4106                    Timestamp::now(),
4107                )
4108                .await;
4109            }
4110        }
4111        "disk-pressure" => {
4112            if let Ok(cfg) = prepare(&opts.repo, opts) {
4113                retention_service_receipt(
4114                    home,
4115                    "disk-pressure",
4116                    "worker",
4117                    "running",
4118                    "retention sweep",
4119                    Some(&cfg),
4120                );
4121                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4122                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
4123                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
4124                }
4125                if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
4126                    tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
4127                }
4128                for current in current_work(home, Timestamp::now()) {
4129                    if let Ok(state) = RunState::load_under(&current.run, home)
4130                        && let Some(reason) = disk_gate(&state.repo, &state.config)
4131                    {
4132                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
4133                            job.key.strip_prefix("task:") == Some(current.task.as_str())
4134                        }) {
4135                            request_task_park(
4136                                home,
4137                                &job,
4138                                crate::run::ParkCause::Interrupt {
4139                                    reason: reason.clone(),
4140                                },
4141                            )?;
4142                        }
4143                        notices::raise_in(
4144                            home,
4145                            Notice::warn(
4146                                "disk:pressure",
4147                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
4148                            ),
4149                        );
4150                    }
4151                }
4152            } else {
4153                retention_service_receipt(
4154                    home,
4155                    "disk-pressure",
4156                    "worker",
4157                    "error",
4158                    "configuration could not be loaded",
4159                    None,
4160                );
4161            }
4162        }
4163        "housekeeping" => {
4164            if task_jobs(home)?.is_empty() {
4165                match prepare(&opts.repo, opts) {
4166                    Ok(cfg) => {
4167                        retention_service_receipt(
4168                            home,
4169                            "housekeeping",
4170                            "worker",
4171                            "running",
4172                            "retention sweep",
4173                            Some(&cfg),
4174                        );
4175                        crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4176                    }
4177                    Err(error) => retention_service_receipt(
4178                        home,
4179                        "housekeeping",
4180                        "worker",
4181                        "error",
4182                        &format!("configuration: {error:#}"),
4183                        None,
4184                    ),
4185                }
4186                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
4187                resweep_superseded_attempts(&queue, home);
4188                triage_held(&queue, home, opts).await;
4189            } else {
4190                retention_service_receipt(
4191                    home,
4192                    "housekeeping",
4193                    "worker",
4194                    "skipped",
4195                    "task worker became active",
4196                    None,
4197                );
4198            }
4199        }
4200        operation => bail!("unknown daemon service {operation}"),
4201    }
4202    Ok(())
4203}
4204
4205/// Only a different request under the same key is a dispatch handoff race.
4206/// Our own unacknowledged reservation is a startup failure, not competing work:
4207/// stop dispatch without fencing it, so an already detached child may still run.
4208fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
4209    let key = format!("task:{}", request.task);
4210    let payload = serde_json::to_value(request)?;
4211    if crate::worker::active(home)?
4212        .iter()
4213        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
4214    {
4215        tracing::warn!(
4216            "task {} acquired a competing worker reservation: {error:#}",
4217            crate::run::short_of(&request.task)
4218        );
4219        return Ok(());
4220    }
4221    tracing::error!("task worker startup stopped dispatch: {error:#}");
4222    notices::raise_in(
4223        home,
4224        Notice::error(
4225            "loop:worker-startup",
4226            // Startup diagnostics may contain private child-process details;
4227            // keep them in the local error/log rather than the chat or notifier.
4228            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),
4229        ).link(Link::Task { id: request.task.clone() }),
4230    );
4231    Err(error).with_context(|| {
4232        format!(
4233            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
4234            crate::run::short_of(&request.task)
4235        )
4236    })
4237}
4238
4239async fn poll(
4240    opts: &Opts,
4241    queue: &Queue,
4242    status: &Arc<Mutex<Status>>,
4243    home: &Path,
4244    worktrees_root: &Path,
4245    stop: &Stop,
4246    limits: DispatchLimits,
4247) -> Result<()> {
4248    let mut attempted = Vec::new();
4249    let mut settling_once_services = false;
4250    let interrupt_path = home.join("scheduler-interrupt.json");
4251    let mut interrupt = match std::fs::read(&interrupt_path) {
4252        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
4253        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
4254        Err(error) => return Err(error.into()),
4255    };
4256    let mut previous = std::collections::BTreeSet::<String>::new();
4257    let mut previous_skips = DispatchSkips::new();
4258    while !stop.stopped() {
4259        let jobs: Vec<_> = crate::worker::active(home)?
4260            .into_iter()
4261            .filter(|job| job.kind == "task")
4262            .collect();
4263        let requests: Vec<_> = jobs
4264            .iter()
4265            .map(|job| {
4266                serde_json::from_value::<TaskWorker>(job.payload.clone())
4267                    .with_context(|| format!("read live task worker {}", job.id))
4268            })
4269            .collect::<Result<_>>()?;
4270        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4271        let owned: std::collections::BTreeSet<_> = requests
4272            .iter()
4273            .filter(|r| !r.standalone)
4274            .map(|r| r.task.clone())
4275            .collect();
4276        let current: Vec<_> = requests
4277            .iter()
4278            .zip(&jobs)
4279            .filter(|(request, _)| !request.standalone)
4280            .map(|(request, job)| Current {
4281                worker: Some(job.id.clone()),
4282                task: request.task.clone(),
4283                run: queue
4284                    .get(&request.task)
4285                    .ok()
4286                    .and_then(|task| task.execution_runs().last().cloned())
4287                    .unwrap_or_default(),
4288            })
4289            .collect();
4290        {
4291            let mut snapshot = lock(status);
4292            snapshot.polls += 1;
4293            snapshot.completed += previous.difference(&owned).count();
4294            snapshot.current = current;
4295            snapshot.idle = owned.is_empty();
4296            snapshot.dispatch_wait = None;
4297        }
4298        previous = owned.clone();
4299        stop.busy.store(owned.len(), Ordering::SeqCst);
4300
4301        // Slots are reconstructed from durable reservations and OS-held worker
4302        // leases, not this scheduler's lifetime or mutable task urgency.
4303        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4304        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4305        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4306        let mut permits = Vec::new();
4307        sweep_stale_claims(queue, STALE_CLAIM);
4308        reclaim_orphaned_running(queue, opts.max_attempts, &live);
4309        reclaim_abandoned_runs(home, Timestamp::now());
4310        let questions = Questions::at(home.join("questions"));
4311
4312        // Deterministic: no model, run before the conductor sees anything so
4313        // its input reflects the queue's current, already-resolved state.
4314        crate::task_chat::sweep(
4315            queue,
4316            &crate::talk::Talks::at(home.join("talks")),
4317            &questions,
4318            home,
4319        );
4320        if let Err(error) = crate::task_inquiry::Outbox::at(home)
4321            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4322        {
4323            tracing::warn!("task inquiry delivery remains pending: {error:#}");
4324        }
4325        repair_choice_offers(&questions);
4326        resolve_blockers(queue, &questions);
4327        apply_task_choice_actions(queue, &questions, home);
4328        triage::apply_answers(queue, &questions);
4329        reconcile_task_questions(queue, &questions);
4330        let talks = crate::talk::Talks::at(home.join("talks"));
4331        crate::chat_notify::sweep(queue, &talks, home);
4332        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4333        crate::chat_watch::sweep(home, &talks);
4334        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4335            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4336        }
4337        let mut turns = tokio::task::JoinSet::new();
4338        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4339        // start_turns dispatches detached turns; no paid work lives in this set.
4340        while turns.join_next().await.is_some() {}
4341
4342        crate::consult::start_services(
4343            home,
4344            &opts.repo,
4345            limits.recovery_cfg.as_ref(),
4346            opts.config.as_deref(),
4347        )
4348        .await?;
4349        for operation in [
4350            "conductor",
4351            "maintenance",
4352            "housekeeping",
4353            "disk-pressure",
4354            "cache",
4355            "fetch",
4356            "chat-goals",
4357        ] {
4358            // Once an idle --once drain starts settling services, subsequent
4359            // scans only consume their effects. An expired cadence receipt
4360            // must not start another service and keep the drain alive.
4361            if settling_once_services {
4362                break;
4363            }
4364            if operation == "chat-goals" && stop.parking() {
4365                continue;
4366            }
4367            start_service(
4368                home,
4369                opts,
4370                queue,
4371                worktrees_root,
4372                operation,
4373                limits.recovery_cfg.as_ref(),
4374                !live.is_empty(),
4375            )
4376            .await?;
4377        }
4378        let latest = crate::worker::active(home)?;
4379        if latest.iter().any(|job| job.key == "service:daemon-cache")
4380            || latest
4381                .iter()
4382                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4383        {
4384            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4385            continue;
4386        }
4387        let candidates: Vec<Task> = runnable(queue)
4388            .into_iter()
4389            .filter(|task| !live.contains(&task.id))
4390            .filter(|task| !opts.once || !attempted.contains(&task.id))
4391            .collect();
4392        let in_flight: Vec<_> = owned.iter().cloned().collect();
4393        let prior_interrupt = std::mem::discriminant(&interrupt);
4394        interrupt = advance_interrupt_tick(
4395            limits.pause_for_interrupts,
4396            interrupt,
4397            &in_flight,
4398            &candidates,
4399        );
4400        // Same-variant transitions preserve their identities. Only an actual
4401        // transition needs a durable write, atomically before sending controls.
4402        if prior_interrupt != std::mem::discriminant(&interrupt) {
4403            let temporary = interrupt_path.with_extension("json.tmp");
4404            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4405            std::fs::rename(temporary, &interrupt_path)?;
4406        }
4407        if let Interrupt::Parking {
4408            parked,
4409            interrupt_task,
4410        } = &interrupt
4411        {
4412            for job in jobs.iter().filter(|job| {
4413                parked
4414                    .iter()
4415                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4416            }) {
4417                if crate::worker::control(home, &job.key)?.is_none() {
4418                    request_task_park(
4419                        home,
4420                        job,
4421                        crate::run::ParkCause::Interrupt {
4422                            reason: format!(
4423                                "task {} asked to run first",
4424                                crate::run::short_of(interrupt_task)
4425                            ),
4426                        },
4427                    )?;
4428                }
4429            }
4430        }
4431        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
4432        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4433        let mut skips = interrupt_skips(&candidate_ids, &candidates);
4434        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4435        let mut started = false;
4436        let mut resync = false;
4437        for candidate in candidates {
4438            if stop.stopped() {
4439                break;
4440            }
4441            let DispatchClaim {
4442                task,
4443                claim,
4444                permit,
4445            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
4446                Ok(claim) => claim,
4447                Err(reason) => {
4448                    skips.insert((candidate.id, reason));
4449                    continue;
4450                }
4451            };
4452            if crate::worker::active(home)?
4453                .iter()
4454                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4455            {
4456                drop(claim);
4457                resync = true;
4458                break;
4459            }
4460            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4461            let request = TaskWorker {
4462                opts: opts.absolute()?,
4463                queue: std::path::absolute(queue.root())?,
4464                task: task.id.clone(),
4465                lane,
4466                standalone: false,
4467            };
4468            // Keep the claim until spawn acknowledges the worker's durable
4469            // reservation. The worker then claims and re-reads before attempt.
4470            if let Err(error) = crate::worker::spawn(
4471                home,
4472                "task",
4473                &format!("task:{}", task.id),
4474                serde_json::to_value(&request)?,
4475            )
4476            .await
4477            {
4478                task_worker_spawn_error(home, &request, error)?;
4479                drop(claim);
4480                resync = true;
4481                break;
4482            }
4483            drop(claim);
4484            permits.extend(permit);
4485            attempted.push(task.id);
4486            started = true;
4487        }
4488        if !resync && !stop.stopped() {
4489            if !started {
4490                lock(status).dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
4491            }
4492            if changed_dispatch_skips(&mut previous_skips, skips) {
4493                if previous_skips.is_empty() {
4494                    tracing::info!("dispatch skips cleared");
4495                }
4496                for (task, reason) in &previous_skips {
4497                    tracing::info!(
4498                        task,
4499                        reason = reason.key(),
4500                        "task {} skipped: {}",
4501                        crate::run::short_of(task),
4502                        reason.describe()
4503                    );
4504                }
4505            }
4506        }
4507        if started || resync {
4508            continue;
4509        }
4510        if owned.is_empty() && opts.once {
4511            settling_once_services = true;
4512            // These finite services can own queue claims or publish answers.
4513            // A skipped claim is not an idle queue until they have finished;
4514            // scan again afterwards so their changes are actually scheduled.
4515            if crate::worker::active(home)?.iter().any(|job| {
4516                job.kind == "daemon-service"
4517                    && matches!(
4518                        job.key.as_str(),
4519                        "service:daemon-housekeeping"
4520                            | "service:daemon-conductor"
4521                            | "service:daemon-maintenance"
4522                    )
4523            }) {
4524                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4525                continue;
4526            }
4527            break;
4528        }
4529        stop.idle(if live.is_empty() {
4530            opts.poll
4531        } else {
4532            RECHECK_WHILE_BUSY.min(opts.poll)
4533        })
4534        .await;
4535    }
4536    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4537    // every queue claim and Runner driver lease through outcome settlement.
4538    stop.busy.store(0, Ordering::SeqCst);
4539    lock(status).dispatch_wait = None;
4540    Ok(())
4541}
4542
4543/// A maintenance pass may briefly own the same record while a worker starts.
4544/// Wait without blocking the executor or charging an agent attempt, then read
4545/// ownership again under the acquired lock. Other I/O failures still fail closed.
4546async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4547    let busy = |error: &anyhow::Error| {
4548        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4549            error.kind() == std::io::ErrorKind::WouldBlock
4550                || cfg!(windows) && error.raw_os_error() == Some(33)
4551        })
4552    };
4553    match crate::pr_head::owner_lock(home, id) {
4554        Ok(lock) => return Ok(lock),
4555        Err(error) if busy(&error) => {}
4556        Err(error) => return Err(error),
4557    }
4558    let wait = RunState::load_under(id, home)?
4559        .config
4560        .graph
4561        .timeout_resource_wait;
4562    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4563}
4564
4565/// Historical successors do not revoke a still-resumable public owner. Scan
4566/// under the same lock as publication/driver claims, and fail closed on unknown
4567/// history before spending another attempt.
4568async fn public_resume_owner(
4569    home: &Path,
4570    runs: &[String],
4571    repo: &Path,
4572) -> Result<Option<RunState>> {
4573    let mut owner = None;
4574    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4575        let _lock = resume_owner_lock(home, id).await?;
4576        let state = RunState::load_under(id, home)?;
4577        if state.released()
4578            || state.retired_to.is_some()
4579            || state.pr_taken_over_by.is_some()
4580            || !crate::handover::landing_checkpoint(&state)
4581        {
4582            continue;
4583        }
4584        anyhow::ensure!(
4585            crate::git::toplevel(&state.repo).await?.canonicalize()?
4586                == crate::git::toplevel(repo).await?.canonicalize()?,
4587            "public owner repository differs; inspect run lineage"
4588        );
4589        anyhow::ensure!(
4590            owner.is_none(),
4591            "multiple retained public owners; inspect run lineage"
4592        );
4593        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4594            anyhow::bail!(reason.diagnostic(&state));
4595        }
4596        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4597        anyhow::ensure!(
4598            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4599            "public owner's driver is live or unknown; wait before retrying"
4600        );
4601        owner = Some(state);
4602    }
4603    Ok(owner)
4604}
4605
4606/// Run one claimed task to a terminal status and record the outcome.
4607///
4608/// Every transition is flushed to the queue as it happens, so the state on disk
4609/// is what actually occurred rather than what this process still intends to
4610/// write.
4611async fn attempt(
4612    opts: &Opts,
4613    queue: &Queue,
4614    status: &Arc<Mutex<Status>>,
4615    stop: &Stop,
4616    interrupt_pause: crate::graph::Pause,
4617    task: &mut Task,
4618) -> Vec<QuotaLoss> {
4619    if let Some(request) = task.sync_only.clone() {
4620        Box::pin(attempt_sync_only(
4621            queue,
4622            status,
4623            stop,
4624            interrupt_pause,
4625            task,
4626            request,
4627        ))
4628        .await;
4629        return Vec::new();
4630    }
4631    let repo = repo_for(task, &opts.repo);
4632    tracing::info!(
4633        "task {} — {} (repo {})",
4634        task.short(),
4635        task.title,
4636        repo.display()
4637    );
4638
4639    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4640        Ok(owner) => owner,
4641        Err(e) => {
4642            task.hold_machine(Some(format!(
4643                "Cannot verify existing public owner: {e:#}; no attempt started."
4644            )));
4645            record(queue, task);
4646            return Vec::new();
4647        }
4648    };
4649    let resume_runs = public_owner
4650        .as_ref()
4651        .map(|s| vec![s.id.clone()])
4652        .unwrap_or_else(|| task.execution_runs().to_vec());
4653
4654    // A stop spends no agent resources and uses the saved landing owner.
4655    // Current roster edits, missing attachments or a failed config fetch must
4656    // never turn it into a new implementation, or prevent a PR from closing.
4657    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4658        && previous
4659            .merge_decision
4660            .as_ref()
4661            .is_some_and(|decision| !decision.closed)
4662        && previous.status != RunStatus::Landing
4663        && !crate::merge_decision::resumable_hold(&previous)
4664    {
4665        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)));
4666        record(queue, task);
4667        return Vec::new();
4668    }
4669    let stop_owner = resume_runs
4670        .last()
4671        .and_then(|id| RunState::load(id).ok())
4672        .filter(|state| {
4673            crate::merge_decision::resumable_hold(state)
4674                || state.status == RunStatus::Landing
4675                    && state.land_approval.as_ref().is_some_and(|binding| {
4676                        Questions::open()
4677                            .get_for_effects(&binding.question)
4678                            .is_ok_and(|q| {
4679                                q.run == state.id
4680                                    && q.resolution()
4681                                        .as_deref()
4682                                        .is_some_and(crate::merge_decision::stops)
4683                            })
4684                    })
4685        });
4686    if let Some(owner) = stop_owner {
4687        let mut runner = match Runner::resume(&owner.id) {
4688            Ok(runner) => runner,
4689            Err(e) => {
4690                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4691                record(queue, task);
4692                return Vec::new();
4693            }
4694        };
4695        runner.on_pause(stop.pause());
4696        runner.watch_interrupt(interrupt_pause);
4697        let quota_before = runner.state.quota.clone();
4698        let before_start = task.clone();
4699        task.start(owner.id.clone());
4700        if let Err(error) = queue.put(task) {
4701            *task = before_start;
4702            let error = runner.fail_startup("task-start", error);
4703            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4704                task.record_startup_failure(failure.clone());
4705            }
4706            task.hold_manual(Some(format!(
4707                "Could not persist task start; no agents dispatched: {error:#}"
4708            )));
4709            record(queue, task);
4710            return Vec::new();
4711        }
4712        lock(status).current.push(Current {
4713            worker: None,
4714            task: task.id.clone(),
4715            run: owner.id,
4716        });
4717        runner.state.carry_dispatched_resumes(task);
4718        runner.state.next_pass_task_entry = true;
4719        let result = runner.execute().await;
4720        return finish_attempt(
4721            opts.max_attempts,
4722            queue,
4723            task,
4724            &runner.state,
4725            &quota_before,
4726            result,
4727        );
4728    }
4729
4730    if let Some(owner) = &public_owner
4731        && (task.fresh_start || !may_resume_run(owner, task))
4732    {
4733        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)));
4734        record(queue, task);
4735        return Vec::new();
4736    }
4737
4738    if let Some(state) = task
4739        .execution_runs()
4740        .last()
4741        .and_then(|id| RunState::load(id).ok())
4742        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4743    {
4744        task.hold_machine(Some(reason));
4745        record(queue, task);
4746        return Vec::new();
4747    }
4748
4749    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4750        && !task.fresh_start
4751        && task.pr_recovery.is_none()
4752    {
4753        // Authorization still takes the owner lock and execution lease and
4754        // rechecks liveness, retained HEAD and ownership before saving.
4755        let authorized = if crate::repair_budget::conflict_pending(task, &held) {
4756            true
4757        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4758            let home = queue.root().parent().expect("queue has a home");
4759            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4760                Ok(()) => true,
4761                Err(error) => {
4762                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4763                    false
4764                }
4765            }
4766        } else {
4767            false
4768        };
4769        if !authorized {
4770            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())));
4771            // Retain the existing stop identity when an old release reached the queue.
4772            task.base_sync_notice(&held);
4773            task.resume_override = None;
4774            record(queue, task);
4775            return Vec::new();
4776        }
4777    }
4778    let unfinished = (!task.fresh_start)
4779        .then(|| unfinished_run(&resume_runs, task.short()))
4780        .flatten()
4781        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4782    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4783    if task.repair_grants.last().is_some_and(|receipt| {
4784        task.execution_runs().last() == Some(&receipt.request.run)
4785            && task.operator_decided_at == receipt.decision
4786            && previous
4787                .as_ref()
4788                .is_none_or(|run| run.id != receipt.request.run)
4789    }) {
4790        task.hold_unrequested_retry(Some(
4791            "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(),
4792        ));
4793        record(queue, task);
4794        return Vec::new();
4795    }
4796    if let Some(id) = &task.disk_resume_run
4797        && unfinished.as_ref() != Some(id)
4798    {
4799        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()));
4800        record(queue, task);
4801        return Vec::new();
4802    }
4803
4804    if !task.fresh_start
4805        && task.pr_recovery.is_none()
4806        && task.review_branch.is_none()
4807        && task.resume_override.is_none()
4808        && previous
4809            .as_ref()
4810            .is_some_and(|run| run.retired_to.is_some())
4811        && unfinished.is_none()
4812    {
4813        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()));
4814        record(queue, task);
4815        return Vec::new();
4816    }
4817
4818    let saved_recovery = previous.as_ref().filter(|run| {
4819        task.replacement.is_none()
4820            && task.pr_recovery.as_ref().is_some_and(|selected| {
4821                selected
4822                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4823                    .is_ok()
4824                    && selected_starter(selected, Some(run), unfinished.as_deref())
4825                        == Starter::Resume(run.id.clone())
4826            })
4827    });
4828
4829    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4830    // failure here is the network's or the operator's, not the task's: hold
4831    // without spending an attempt, never fall back to a possibly stale copy.
4832    let explicit = match &task.overrides {
4833        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4834        Some(_) => opts.config.as_deref(),
4835        None => opts.config.as_deref(),
4836    };
4837    let (mut config, layers) = if let Some(run) = saved_recovery {
4838        // A matching resume owns its resolved configuration and evidence;
4839        // current layers and inherited overrides only configure new work.
4840        let mut saved = run.clone();
4841        if let Err(e) = saved.configure_recovery_resume() {
4842            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4843            record(queue, task);
4844            return Vec::new();
4845        }
4846        (saved.config, Vec::new())
4847    } else {
4848        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4849            Ok(loaded) => loaded,
4850            Err(e) => {
4851                let reason = format!("[config] {e:#}");
4852                record_config_failure(task, &e);
4853                task.last_error = Some(reason.clone());
4854                task.hold_machine(Some(reason));
4855                record(queue, task);
4856                return Vec::new();
4857            }
4858        };
4859        if let Err(e) = apply_options(&mut config, opts, task) {
4860            task.hold_manual(Some(format!(
4861                "[config] {e:#}; correct the merge override before releasing the task"
4862            )));
4863            record(queue, task);
4864            return Vec::new();
4865        }
4866        if let Some(selected) = &task.pr_recovery
4867            && let Err(e) = selected.configure(&mut config)
4868        {
4869            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4870            record(queue, task);
4871            return Vec::new();
4872        }
4873        (config, layers)
4874    };
4875    let config_evidence = crate::pr_recovery::ConfigEvidence {
4876        layers,
4877        overrides: task.overrides.clone(),
4878        daemon_merge: task
4879            .overrides
4880            .as_ref()
4881            .is_none_or(|o| o.inherit_daemon_options)
4882            .then(|| opts.merge.clone())
4883            .flatten(),
4884    };
4885    apply_task_implementers(&mut config, task);
4886    if let Some(replacement) = &task.replacement {
4887        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4888            old.liveness(false) == Liveness::Dead
4889                && old.merge_decision.as_ref().is_some_and(|d| {
4890                    d.closed
4891                        && d.question == replacement.question
4892                        && d.replacement_run.as_ref().is_none_or(|run| {
4893                            task.execution_runs().last() == Some(run)
4894                                && RunState::load(run).is_ok_and(|current| {
4895                                    current.replaces.as_ref().is_some_and(|pin| {
4896                                        pin.question == replacement.question
4897                                            && pin.agent == replacement.agent
4898                                    })
4899                                })
4900                        })
4901                })
4902        });
4903        if !safe {
4904            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()));
4905            record(queue, task);
4906            return Vec::new();
4907        }
4908        match config.agent(&replacement.agent) {
4909            Ok(agent) if crate::agent::installed(agent) => {}
4910            _ => {
4911                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)));
4912                record(queue, task);
4913                return Vec::new();
4914            }
4915        }
4916        config.graph.implementers = 1;
4917        config.graph.land_approval = true;
4918        config.merge.mode = MergeMode::Pr;
4919        config.graph.selected_implementer = Some(replacement.agent.clone());
4920    }
4921    let p = phrases(&config.graph.language);
4922    let start_failed = p.could_not_start;
4923    // Resolve once for both admission and settlement. The inputs are the
4924    // task's explicit sources (never prose), plus an explicit review source's
4925    // current head; review-only runs may rebase later, and neither fact can
4926    // refund a failed automatic generation.
4927    if let Ok(base) =
4928        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4929            .await
4930        && let Ok(head) =
4931            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4932    {
4933        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4934        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4935            let source = crate::git::rev_parse(&repo, branch)
4936                .await
4937                .unwrap_or_default();
4938            inputs.push_str(&format!(";review:{branch}:{source}"));
4939        }
4940        if let Some(reason) = task
4941            .recovery_exhausted(
4942                &head,
4943                &inputs,
4944                task.attempt_limit
4945                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4946            )
4947            .filter(|_| {
4948                !task.repair_grants.last().is_some_and(|receipt| {
4949                    RunState::load(&receipt.request.run)
4950                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4951                })
4952            })
4953        {
4954            task.hold_recovery_budget(
4955                reason,
4956                crate::queue::RecoveryAdmission { base: head, inputs },
4957            );
4958            record(queue, task);
4959            return Vec::new();
4960        }
4961        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4962    }
4963
4964    // A resumable run of this task is carried on, never re-competed. The
4965    // candidates are built and paid for, and a fresh competition races a
4966    // second implementation against them.
4967    //
4968    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4969    // started 3cbf on the same task a moment later, duplicating two and a
4970    // half hours of agent work. Then b25f stalled on a judge that timed out
4971    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4972    // was to blame for - and 4043 started **one second** later, buying three
4973    // fresh implementations to reach the same panel. `RunStatus::resumable`
4974    // rather than `!done()` is what catches the second case: a stall is
4975    // terminal, and its cheap recovery re-asks only the absent seats.
4976    //
4977    // A load failure is warned about rather than silently read as "not
4978    // resumable": the alternative is exactly what let a schema mismatch on
4979    // run `eba2` fall through to a full re-competition with nobody told why.
4980    // `crate::conduct` is what actually offers a better answer than
4981    // `Runner::start` here (see `Recovery::Review`), once this task's next
4982    // failure shows it up as `held`/`failed` with the run state unreadable.
4983    // Keep a retained review selection intact until disk admission succeeds.
4984    let consume_review = !previous
4985        .as_ref()
4986        .is_some_and(|state| crate::repair_budget::pending(task, state));
4987    let review_branch = consume_review
4988        .then(|| review_branch_for(task, previous.as_ref()))
4989        .flatten();
4990    let branch_exists = match review_branch {
4991        Some(branch) => crate::git::branch_exists(&repo, branch)
4992            .await
4993            .unwrap_or(false),
4994        None => false,
4995    };
4996    // An explicit `magi review <branch>` is reviewed whatever happens to the
4997    // branch unless an explicit implementer change requires fresh work. An
4998    // unfinished run of the same task still wins, so a retry resumes.
4999    let proposed = review_retry_starter(
5000        task,
5001        previous.as_ref(),
5002        review_branch,
5003        branch_exists,
5004        unfinished.as_deref(),
5005    );
5006    let retry_selected = task.replacement.is_some()
5007        && task.resumption.is_some()
5008        && !task.fresh_start
5009        && previous.as_ref().is_some_and(|run| {
5010            run.replaces.is_some()
5011                && ((run.status == RunStatus::Failed && run.viable().is_empty())
5012                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
5013        });
5014    let stop_pin = task
5015        .resume_override
5016        .as_ref()
5017        .filter(|pin| {
5018            Questions::open()
5019                .get_for_effects(&pin.question_id)
5020                .is_ok_and(|q| {
5021                    q.node == land::APPROVAL_NODE
5022                        && q.resolution()
5023                            .as_deref()
5024                            .is_some_and(crate::merge_decision::stops)
5025                })
5026        })
5027        .and_then(|pin| pin.pinned_run.clone());
5028    let granted_run = task.repair_grants.last().and_then(|receipt| {
5029        let state = RunState::load(&receipt.request.run).ok()?;
5030        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
5031    });
5032    let starter = if let Some(run) = granted_run {
5033        Starter::Resume(run)
5034    } else if let Some(owner) = &public_owner {
5035        Starter::Resume(owner.id.clone())
5036    } else if let Some(run) = stop_pin {
5037        // Stop actions resume their exact owner even after seat-count edits;
5038        // they must never fall through to implementation or a takeover.
5039        Starter::Resume(run)
5040    } else if retry_selected {
5041        Starter::Resume(previous.as_ref().unwrap().id.clone())
5042    } else if let Some(selected) = &task.pr_recovery {
5043        if selected
5044            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5045            .is_ok()
5046        {
5047            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
5048        } else {
5049            Starter::Review(selected.branch.clone())
5050        }
5051    } else {
5052        starter_with_implementers(task, previous.as_ref(), proposed)
5053    };
5054    // A retained execution still writes to its saved output volume. A newer
5055    // repository policy only selects the volume for a fresh run.
5056    let disk_reason = match &starter {
5057        Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
5058            || {
5059                RunState::load(id)
5060                    .ok()
5061                    .and_then(|run| disk_gate(&run.repo, &run.config))
5062            },
5063            |run| disk_gate(&run.repo, &run.config),
5064        ),
5065        _ => disk_gate(&repo, &config),
5066    };
5067    if let Some(reason) = disk_reason {
5068        task.notice_cause("disk-space", None, None);
5069        task.last_error = Some(reason.clone());
5070        let disk_checked_at = task.disk_checked_at;
5071        task.hold_machine(Some(reason.clone()));
5072        if matches!(starter, Starter::Resume(_)) {
5073            task.mark_disk_capacity();
5074        } else {
5075            task.mark_startup_disk_capacity();
5076        }
5077        task.disk_checked_at = disk_checked_at;
5078        record(queue, task);
5079        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
5080        notices::raise(
5081            Notice::warn(
5082                &format!("disk:{}", repo.display()),
5083                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
5084            )
5085            .link(Link::Task {
5086                id: task.id.clone(),
5087            }),
5088        );
5089        return Vec::new();
5090    }
5091    let review_branch = if consume_review {
5092        let valid = review_branch.is_some();
5093        task.review_instruction = None;
5094        task.review_branch.take().filter(|_| valid)
5095    } else {
5096        None
5097    };
5098    // An explicit resume pin must never degrade into a new competition or
5099    // takeover, including when its run stops being eligible after the answer.
5100    if let Some(pin) = &task.resume_override
5101        && let Some(run) = &pin.pinned_run
5102        && starter != Starter::Resume(run.clone())
5103    {
5104        let run = run.clone();
5105        task.notice_cause("resume-owner", Some(&run), None);
5106        task.hold_machine(Some(format!(
5107            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
5108            task.id
5109        )));
5110        record(queue, task);
5111        return Vec::new();
5112    }
5113    // Automatic disk recovery resumes its retained run or stops: a changed
5114    // seat count or review branch must not turn it into a new competition.
5115    // No attempt is spent here.
5116    if let Some(run) = &task.disk_resume_run
5117        && starter != Starter::Resume(run.clone())
5118    {
5119        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()));
5120        record(queue, task);
5121        return Vec::new();
5122    }
5123    if task.replacement.is_some()
5124        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
5125        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
5126    {
5127        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()));
5128        record(queue, task);
5129        return Vec::new();
5130    }
5131    if let Some(reason) = retained_attempt_hold(
5132        task,
5133        &starter,
5134        config.disk.retained_attempt_limit,
5135        RunState::load,
5136    ) {
5137        // The review choice was consumed above. Preserve it across this hold
5138        // so a later release cannot silently become a fresh implementation.
5139        if let Starter::Review(branch) = &starter {
5140            task.review_branch = Some(branch.clone());
5141        }
5142        task.hold_unrequested_retry(Some(reason));
5143        record(queue, task);
5144        return Vec::new();
5145    }
5146    // Absolute paths of the files the task was filed with, re-read from the
5147    // task now so a file attached while it was held reaches a resumed run
5148    // too. A stored name whose file has gone is an error before any agent is
5149    // paid for, never a silent omission the implementer cannot notice.
5150    let attachments = match task_attachments(queue, task) {
5151        Ok(a) => a,
5152        Err(e) => {
5153            task.attempts += 1;
5154            task.fail_startup_target(
5155                "startup-attachments",
5156                e.name.clone(),
5157                format!("{start_failed}{e:#}"),
5158                opts.max_attempts,
5159            );
5160            record(queue, task);
5161            return Vec::new();
5162        }
5163    };
5164    let startup_pause = stop.pause();
5165    let startup_interrupt = interrupt_pause.clone();
5166    let wait = crate::repo_lock::WaitPolicy::new(
5167        Duration::from_secs(config.graph.timeout_resource_wait),
5168        move || startup_pause.parked() || startup_interrupt.parked(),
5169    );
5170    // Startup includes review takeover and recovery. Do not embed its large
5171    // future in both the wait scope and the surrounding attempt stack frame.
5172    let started = wait.scope(Box::pin(async { match &starter {
5173        Starter::Review(_) if task.pr_recovery.is_some() => {
5174            let selected = task.pr_recovery.clone().expect("selected recovery");
5175            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
5176                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
5177                    .await
5178                    .map(|mut r| {
5179                        r.state.attachments = attachments.clone();
5180                        r
5181                    }),
5182                Err(e) => Err(e),
5183            }
5184        }
5185        Starter::Review(branch) => {
5186            tracing::info!(
5187                "task {} reopens `{branch}` as a review-only pass",
5188                task.short()
5189            );
5190            // Every earlier attempt is superseded by the one being minted
5191            // now, so a branch one of them still holds may be taken over.
5192            let takeover = crate::handover::Takeover {
5193                earlier: task.earlier_attempts().to_vec(),
5194                home: crate::run::home(),
5195                choice: take_divergence_answer(branch, &config.merge.remote, task),
5196                task_instruction: Some(instruction_for(task)),
5197            };
5198            Runner::review_taking_over(
5199                &repo,
5200                branch,
5201                config,
5202                Some(takeover),
5203                crate::run::Origin::queue(&task.id),
5204            )
5205            .await
5206        }
5207        Starter::Resume(id) => {
5208            tracing::info!("resuming run {id} rather than competing again");
5209            Runner::resume(id).and_then(|mut r| {
5210                if retry_selected {
5211                    // The explicit queue release retries this same pinned
5212                    // implementation, preserving the attempt and worktrees.
5213                    for candidate in &mut r.state.candidates {
5214                        candidate.failed = None;
5215                        candidate.empty = false;
5216                        candidate.commits = 0;
5217                    }
5218                    r.state.status = RunStatus::Implementing;
5219                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
5220                }
5221                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
5222                    r.state.sources = task.sources.clone();
5223                }
5224                if r.state.prep_failure.is_some() {
5225                    let approval = task
5226                        .resumption
5227                        .as_ref()
5228                        .context("preparation retry requires an explicit task release")?;
5229                    r.retry_preparation(approval.at)?;
5230                }
5231                if let Some(instruction) =
5232                    prepare_instruction(&starter, Some(&r.state.instruction), task)
5233                {
5234                    r.state.instruction = instruction;
5235                }
5236                r.state.attachments = attachments.clone();
5237                if task.replacement.is_some() {
5238                    r.state.config.merge.mode = MergeMode::Pr;
5239                    r.state.config.graph.land_approval = true;
5240                }
5241                // Replacements publish a new PR and ask again. Selected PR
5242                // recoveries keep their saved disposition; ordinary runs can
5243                // retain the task's merge override.
5244                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
5245                    .overrides
5246                    .as_ref()
5247                    .and_then(|o| o.merge.as_deref())
5248                    .and_then(|m| merge_mode(m).ok())
5249                {
5250                    r.state.config.merge.mode = mode;
5251                }
5252                Ok(r)
5253            })
5254        }
5255        Starter::Start => {
5256            if let Some(branch) = &review_branch {
5257                tracing::warn!(
5258                    "conductor chose review for task {} but branch `{branch}` no longer \
5259                     exists; requeuing as a fresh competition instead",
5260                    task.short()
5261                );
5262            }
5263            let instruction = prepare_instruction(&starter, None, task)
5264                .unwrap_or_else(|| task.instruction.clone());
5265            Runner::start_naming(
5266                &repo,
5267                instruction,
5268                &task.title,
5269                config,
5270                crate::run::Origin::queue(&task.id),
5271            )
5272            .await
5273            .map(|mut r| {
5274                r.state.attachments = attachments.clone();
5275                r.state.sources = task.sources.clone();
5276                r
5277            })
5278        }
5279    }})).await;
5280    if let Err(error) = &started
5281        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
5282    {
5283        task.record_startup_failure(failure.clone());
5284    }
5285    let mut runner = match started {
5286        Ok(r) => r,
5287        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
5288            let detail = format!("{e:#}");
5289            task.last_error = Some(detail.clone());
5290            if e.is::<crate::build_target::AdmissionDiskWait>()
5291                && let Starter::Review(branch) = &starter
5292                && review_branch.is_some()
5293            {
5294                task.review_branch = Some(branch.clone());
5295                task.review_instruction = Some(task.instruction.clone());
5296            }
5297            if stop.parking() || interrupt_pause.parked() {
5298                let attempts = task.attempts;
5299                task.park(e.to_string());
5300                // Startup has not spent an attempt to refund.
5301                task.attempts = attempts;
5302            } else if e.is::<crate::build_target::AdmissionDiskWait>() {
5303                let disk_checked_at = task.disk_checked_at;
5304                task.hold_machine(Some(detail));
5305                task.mark_startup_disk_capacity();
5306                task.disk_checked_at = disk_checked_at;
5307            } else {
5308                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
5309            }
5310            record(queue, task);
5311            return Vec::new();
5312        }
5313        // A branch an earlier attempt still holds and magi will not release
5314        // by itself is the operator's call, not a failed attempt: hold the
5315        // task with the reason, spend nothing, and say so on the bell.
5316        Err(e) if task.pr_recovery.is_some() => {
5317            task.startup_notice_cause("startup-public-head");
5318            task.attempts += 1;
5319            task.last_error = Some(format!("{start_failed}{e:#}"));
5320            task.hold_unrequested_retry(Some(format!(
5321                "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."
5322            )));
5323            record(queue, task);
5324            return Vec::new();
5325        }
5326        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
5327            let detail = match e.downcast_ref::<crate::handover::Refused>() {
5328                Some(r) => (p.handover_refused)(r),
5329                None => format!("{e:#}"),
5330            };
5331            task.startup_notice_cause("startup-handover");
5332            let reason = format!("{start_failed}{detail}");
5333            task.last_error = Some(reason.clone());
5334            // Consumed above by `take`; keep it so the released task retries
5335            // as a review of this same branch.
5336            let branch = match &starter {
5337                Starter::Review(branch) => Some(branch.clone()),
5338                _ => None,
5339            };
5340            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
5341            // one page; the guidance rides in the reason, fixed per state so a
5342            // re-put never changes the wording and relights it.
5343            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5344            record(queue, task);
5345            tracing::warn!(
5346                "holding {} for a branch it cannot take over: {e:#}",
5347                task.short()
5348            );
5349            return Vec::new();
5350        }
5351        // A branch that differs between here and the remote in ways magi
5352        // cannot prove are the same change is a decision for the owner, not a
5353        // failed attempt: ask with both sides laid out, spend no attempt, and
5354        // let the answer requeue the task.
5355        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5356            let d = e
5357                .downcast_ref::<crate::reconcile::Diverged>()
5358                .expect("checked by the guard");
5359            let mut q = ask::Question::new(
5360                task.id.clone(),
5361                crate::reconcile::NODE.to_owned(),
5362                crate::reconcile::SEAT.to_owned(),
5363                d.summary(),
5364                d.detail(),
5365                d.choices(),
5366            );
5367            match Questions::open().put(&mut q) {
5368                Ok(()) => {
5369                    task.last_error = Some(format!("{e:#}"));
5370                    // Consumed above by `take`; the answer has to reach a review
5371                    // of this same branch, so keep pointing the task at it.
5372                    task.review_branch = Some(d.branch.clone());
5373                    task.review_instruction = Some(task.instruction.clone());
5374                    task.block(vec![q.id.clone()], Some(d.summary()));
5375                }
5376                Err(put) => {
5377                    tracing::warn!("could not file the divergence question: {put:#}");
5378                    task.attempts += 1;
5379                    task.fail_startup(
5380                        "startup-question-store",
5381                        format!("{start_failed}{e:#}"),
5382                        opts.max_attempts,
5383                    );
5384                }
5385            }
5386            record(queue, task);
5387            return Vec::new();
5388        }
5389        Err(e) => {
5390            // The answer was stale and nothing was applied: keep pointing at
5391            // the branch so the next attempt asks again against its new tips.
5392            // Nothing went wrong with the task, so no attempt is spent: a
5393            // budget one short of its limit must not hold it instead of
5394            // letting the question be asked again.
5395            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5396                && let Starter::Review(branch) = &starter
5397            {
5398                task.review_branch = Some(branch.clone());
5399                task.review_instruction = Some(task.instruction.clone());
5400                task.last_error = Some(format!("{start_failed}{e:#}"));
5401                task.status = crate::queue::TaskStatus::Failed;
5402                record(queue, task);
5403                return Vec::new();
5404            }
5405            task.attempts += 1;
5406            task.last_error = Some(format!("{start_failed}{e:#}"));
5407            task.startup_notice_cause("startup-source");
5408            task.hold_unrequested_retry(Some(format!(
5409                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5410            )));
5411            record(queue, task);
5412            return Vec::new();
5413        }
5414    };
5415    if !matches!(starter, Starter::Resume(_))
5416        && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
5417    {
5418        runner
5419            .state
5420            .event("build-cache", format!("{mode} selected by {source}"));
5421    }
5422    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5423        runner.state.recovery_config = Some(config_evidence);
5424    }
5425    if let Some(replacement) = &task.replacement {
5426        if matches!(starter, Starter::Start) {
5427            runner.state.instruction.push_str(&format!(
5428                "\n\n# Replacement review context\n{}",
5429                replacement.context
5430            ));
5431        }
5432        runner.state.replaces = Some(replacement.clone());
5433        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5434        if let Ok(mut old) = RunState::load(&replacement.run)
5435            && let Some(d) = &mut old.merge_decision
5436        {
5437            d.replacement_run = Some(runner.state.id.clone());
5438            old.event(
5439                "replacement",
5440                format!(
5441                    "replacement run {} owns the next attempt; old PR remains closed",
5442                    runner.state.id
5443                ),
5444            );
5445            if let Err(e) = old.save() {
5446                let error = runner.fail_startup("replacement-history", e);
5447                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5448                    task.record_startup_failure(failure.clone());
5449                }
5450                task.hold_manual(Some(format!(
5451                    "Could not link replacement history: {error:#}; no agents dispatched"
5452                )));
5453                record(queue, task);
5454                return Vec::new();
5455            }
5456        }
5457    }
5458    runner.state.task_instruction = Some(task.instruction.clone());
5459    // The follow-up depth is fixed now, while the task certainly exists:
5460    // deleting it later must not reset the cap (`crate::followup`).
5461    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5462    if runner.state.origin_chat.is_none() {
5463        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5464    }
5465    // A stop that means "park" reaches the graph through this handle.
5466    runner.on_pause(stop.pause());
5467    // `poll`'s interrupt scheduler reaches this one run - and no other -
5468    // through this handle. See `Pause`'s own doc for why these are never
5469    // the same one.
5470    runner.watch_interrupt(interrupt_pause);
5471
5472    // `start` has minted the run, so the task can now point at it. Persisting
5473    // `Running` before `execute` is what makes a crash mid-run legible.
5474    let run = runner.state.id.clone();
5475    let before_start = task.clone();
5476    task.start(run.clone());
5477    if let Err(error) = queue.put(task) {
5478        *task = before_start;
5479        let error = runner.fail_startup("task-start", error);
5480        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5481            task.record_startup_failure(failure.clone());
5482        }
5483        task.hold_manual(Some(format!(
5484            "Could not persist task start; no agents dispatched: {error:#}"
5485        )));
5486        record(queue, task);
5487        return Vec::new();
5488    }
5489    if task.status != TaskStatus::Running {
5490        // Queue::put kept a newer hold or continuation instead of this start.
5491        return Vec::new();
5492    }
5493    lock(status).current.push(Current {
5494        worker: None,
5495        task: task.id.clone(),
5496        run,
5497    });
5498
5499    // `RunState::quota` is the run's whole history across every resume, so
5500    // only what this execution added may arm the cooldown or earn a refund.
5501    let quota_before = runner.state.quota.clone();
5502    runner.state.carry_dispatched_resumes(task);
5503    runner.state.next_pass_task_entry = true;
5504    let result = runner.execute().await;
5505    finish_attempt(
5506        opts.max_attempts,
5507        queue,
5508        task,
5509        &runner.state,
5510        &quota_before,
5511        result,
5512    )
5513}
5514
5515async fn attempt_sync_only(
5516    queue: &Queue,
5517    status: &Arc<Mutex<Status>>,
5518    stop: &Stop,
5519    interrupt: crate::graph::Pause,
5520    task: &mut Task,
5521    request: crate::base_sync_only::Request,
5522) {
5523    let result = async {
5524        anyhow::ensure!(
5525            task.status == TaskStatus::Queued
5526                && task.execution_runs().last() == Some(&request.run)
5527                && task.resume_override.as_ref().is_some_and(
5528                    |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
5529                ),
5530            "sync-base-only request no longer owns the exact queued run"
5531        );
5532        let mut runner = Runner::resume(&request.run)?;
5533        anyhow::ensure!(
5534            public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
5535                .await?
5536                .is_none(),
5537            "the task still has a public execution owner"
5538        );
5539        anyhow::ensure!(
5540            !stop.parking() && !interrupt.parked(),
5541            "paused before base synchronization"
5542        );
5543        let original = task.clone();
5544        task.start(request.run.clone());
5545        task.attempts = original.attempts;
5546        if let Err(error) = queue.put(task) {
5547            *task = original;
5548            return Err(error);
5549        }
5550        if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
5551            return Ok(());
5552        }
5553        lock(status).current.push(Current {
5554            worker: None,
5555            task: task.id.clone(),
5556            run: request.run.clone(),
5557        });
5558        runner.on_pause(stop.pause());
5559        runner.watch_interrupt(interrupt);
5560        runner.execute_sync_only(request.clone()).await
5561    }
5562    .await;
5563    if task.sync_only.as_ref() == Some(&request) {
5564        let saved = RunState::load(&request.run).ok();
5565        let detail = result.err().map(|error| {
5566            format!("Base synchronization only: {error:#}; verification was not allowed")
5567        });
5568        crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
5569        record(queue, task);
5570    }
5571}
5572
5573/// Settle `task` after its run executed: the verdict, the diagnosis, the
5574/// supersession of earlier attempts and the save. Shared by the loop and by
5575/// `magi run --resume`, so an attempt is counted one way wherever it ran.
5576/// Returns the quota losses this execution added to the run.
5577pub fn finish_attempt(
5578    max_attempts: usize,
5579    queue: &Queue,
5580    task: &mut Task,
5581    state: &RunState,
5582    quota_before: &[QuotaLoss],
5583    result: Result<()>,
5584) -> Vec<QuotaLoss> {
5585    let detail = match result {
5586        Ok(()) => describe(state),
5587        Err(e) => format!("{e:#}"),
5588    };
5589    let fresh = losses_this_attempt(quota_before, &state.quota);
5590    let verdict = Verdict {
5591        status: state.status,
5592        // A run that opened a pull request handed its work over, whatever the
5593        // gate then decided about merging it.
5594        left_pr: state.pr.is_some(),
5595        // Only a rate limit earns the task its attempt back - and only one
5596        // suffered now: a refund justified by a previous session's loss is
5597        // the same mistake as re-arming the cooldown from it. A stalled run
5598        // resumed without hitting quota again therefore spends its attempt,
5599        // like any other failure of the task's own.
5600        quota_hit: !fresh.is_empty(),
5601        // A run that parked was asked to stop; that is not a failure and must
5602        // not spend an attempt, or replacing the binary a few times would
5603        // exhaust a task's budget without an agent ever misbehaving.
5604        parked: state.parked,
5605        // A quota loss that left nothing viable is the same machine fact as a
5606        // `Stalled` quota loss; see `settle`'s doc table.
5607        no_viable_candidates: state.viable().is_empty(),
5608    };
5609    if let Some(replacement) = &state.replaces
5610        && let Some(pr) = &state.pr
5611        && let Ok(mut old) = RunState::load(&replacement.run)
5612        && let Some(d) = &mut old.merge_decision
5613    {
5614        d.replacement_pr = Some(pr.url.clone());
5615        let _ = old.save();
5616    }
5617    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5618    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5619        task.hold_unrequested_retry(Some(format!(
5620            "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.",
5621            task.short()
5622        )));
5623    }
5624    if task.status == TaskStatus::Done {
5625        supersede_prior_runs(task, &crate::run::home());
5626    }
5627    record(queue, task);
5628    tracing::info!(
5629        "task {} is {} after run {} ({})",
5630        task.short(),
5631        task.status.as_str(),
5632        state.short(),
5633        label(state.status)
5634    );
5635    fresh
5636}
5637
5638/// A task a hand-started run leaves runnable (failed with attempts to spare,
5639/// or requeued) is **held**: nobody asked for a retry, and a loop starting
5640/// later must not spend agent calls on it. `magi task release` retries.
5641pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5642    // Parked work (including legacy Failed records with a parked run) is a
5643    // checkpoint or owner handoff, not an unrequested retry.
5644    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5645        && !awaiting_resume_with(task, RunState::load)
5646        // A run parked on the owner's word about a withheld PR title/body
5647        // resumes via `land_resume_state`, including review-only tasks that
5648        // `awaiting_resume_with` does not consider.
5649        && withheld_text_wait(task).is_none()
5650        && !(task.fresh_start && task.replacement.is_some())
5651    {
5652        let why = task.last_error.clone().map_or_else(
5653            || "the run did not finish".to_owned(),
5654            |e| format!("the run did not finish: {e}"),
5655        );
5656        task.hold_unrequested_retry(Some(format!(
5657            "{why}. It was started by hand, so it is not retried \
5658             automatically; `magi task release` retries it."
5659        )));
5660        record(queue, task);
5661    }
5662}
5663
5664/// Whether an attempt at a task whose newest run is `run` would resume that
5665/// run rather than start a fresh competition. `magi run --resume` hands a run
5666/// to a live loop only when this holds.
5667#[must_use]
5668pub fn loop_would_resume(run: &str) -> bool {
5669    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5670}
5671
5672/// A loop in another process that is alive right now: a fresh heartbeat in
5673/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
5674/// carries the pid it published (`None` inside when it published none - a
5675/// fresh heartbeat is still evidence of a live loop).
5676///
5677/// The one judgement of "is somebody else serving this queue", shared by the
5678/// web UI's refusal to start a second loop and by `magi run` / `magi review`
5679/// deciding whether to hand a task to the loop. A claim file proves nothing
5680/// here: whether a claim succeeds says nothing about whether its owner lives.
5681#[must_use]
5682pub fn foreign_loop(
5683    reading: Option<&Reading>,
5684    now: Timestamp,
5685    own_pid: u32,
5686) -> Option<Option<u32>> {
5687    let reading = reading.filter(|r| r.running(now))?;
5688    match reading.pid {
5689        Some(pid) if pid == own_pid => None,
5690        pid => Some(pid),
5691    }
5692}
5693
5694fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5695    reading.worker_protocol != Some(1)
5696        && (foreign_loop(Some(reading), now, own_pid).is_some()
5697            || reading
5698                .pid
5699                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5700}
5701
5702/// Low-level claimed-task execution shared by the detached standalone worker
5703/// and focused lifecycle fixtures. The caller must retain the queue claim for
5704/// this entire call. CLI callers transfer ownership through
5705/// [`run_detached_claimed`] instead of executing inside their own runtime.
5706///
5707/// The one deliberate difference from the loop: a task the attempt leaves
5708/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5709/// Nobody asked for a retry, and a daemon starting later must not spend agent
5710/// calls re-running a hand-started task behind the operator's back;
5711/// `magi task release` is the explicit retry.
5712pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5713    run_claimed_until(opts, queue, task, &Stop::new()).await;
5714}
5715
5716async fn run_claimed_until(
5717    opts: &Opts,
5718    queue: &Queue,
5719    task: &mut Task,
5720    stop: &Stop,
5721) -> Vec<QuotaLoss> {
5722    let status = Arc::new(Mutex::new(Status::new()));
5723    // An attempt embeds startup and graph futures. Keep it off the standalone
5724    // caller's stack, on both the initial execution and withheld-text resume.
5725    let mut quota = Box::pin(attempt(
5726        opts,
5727        queue,
5728        &status,
5729        stop,
5730        crate::graph::Pause::new(),
5731        task,
5732    ))
5733    .await;
5734    // A run parked on the owner's word about a withheld PR title/body has no
5735    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5736    // here with the claim still held, and resume once the question is settled
5737    // (answered, or abandoned at its deadline -> the neutral text).
5738    // A rejected reply files one more question (the gate asks at most twice),
5739    // so after a resume the run may be waiting again: keep going, with a fresh
5740    // limit for the new question. `resumes` bounds it even if a resume parks
5741    // without asking anything new.
5742    let mut resumes = 0;
5743    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5744        let Some(timeout) = withheld_text_wait(task) else {
5745            break;
5746        };
5747        eprintln!(
5748            "waiting for the owner's answer on a withheld pull request text \
5749             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5750        );
5751        // The deadline abandons the question itself; the extra margin only
5752        // covers an abandon that could not be saved.
5753        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5754        let ready = loop {
5755            match land_resume_state(task) {
5756                LandResume::StillWaiting
5757                    if !stop.parking() && std::time::Instant::now() < limit =>
5758                {
5759                    tokio::time::sleep(WITHHELD_POLL).await;
5760                }
5761                LandResume::Ready => break true,
5762                _ => break false,
5763            }
5764        };
5765        if !ready || stop.parking() {
5766            break;
5767        }
5768        resumes += 1;
5769        quota.extend(
5770            Box::pin(attempt(
5771                opts,
5772                queue,
5773                &status,
5774                stop,
5775                crate::graph::Pause::new(),
5776                task,
5777            ))
5778            .await,
5779        );
5780    }
5781    hold_if_runnable(queue, task);
5782    quota
5783}
5784
5785/// Resumes an in-process run makes for withheld-text questions: the gate asks
5786/// at most twice, plus one for a resume that asks nothing new.
5787const MAX_WITHHELD_RESUMES: u32 = 3;
5788
5789/// How often an in-process run rechecks its withheld-text question.
5790const WITHHELD_POLL: Duration = Duration::from_secs(15);
5791
5792/// The `answer_timeout` (seconds) of the task's last run when that run is
5793/// parked on an unresolved withheld-text question; `None` otherwise.
5794fn withheld_text_wait(task: &Task) -> Option<u64> {
5795    let id = task.execution_runs().last()?;
5796    let s = RunState::load(id).ok()?;
5797    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5798        .then_some(s.config.graph.answer_timeout)
5799}
5800
5801/// The quota losses `after` holds that `before` did not: what one execution
5802/// suffered, as opposed to the run's history.
5803///
5804/// Compared by value rather than by length or position because
5805/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5806/// the vector can shrink and shift under a resume. A retried seat that hits
5807/// quota again is a `push` with a new `at`, so it shows up as new here.
5808/// Crash recovery uses the recorded pass start as its boundary when available;
5809/// legacy records without passes retain their original history-based policy.
5810fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5811    after
5812        .iter()
5813        .filter(|q| !before.contains(q))
5814        .cloned()
5815        .collect()
5816}
5817
5818/// When the loop-wide quota cooldown should end, given this attempt's losses;
5819/// `None` when there were none. Reset-hint parsing and the cap live here.
5820fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5821    let quota: Vec<_> = quota
5822        .iter()
5823        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5824        .collect();
5825    if quota.is_empty() {
5826        return None;
5827    }
5828    let with_hint = quota.iter().find(|q| q.reset.is_some());
5829    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5830    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5831    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5832    Some(
5833        now.checked_add(jiff::SignedDuration::from_secs(secs))
5834            .unwrap_or(Timestamp::MAX),
5835    )
5836}
5837
5838/// An explicit task count must agree with a run before any resume.
5839fn implementers_match(task: &Task, state: &RunState) -> bool {
5840    task.replacement.as_ref().map_or_else(
5841        || {
5842            task.implementers()
5843                .is_none_or(|n| n == state.config.graph.implementers)
5844        },
5845        |replacement| {
5846            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5847                && state.config.graph.implementers == 1
5848        },
5849    )
5850}
5851
5852/// Never resume or take over candidate work built for a different seat count.
5853fn starter_with_implementers(
5854    task: &Task,
5855    previous: Option<&RunState>,
5856    proposed: Starter,
5857) -> Starter {
5858    if previous.is_some_and(|s| !implementers_match(task, s)) {
5859        task.review_of
5860            .as_ref()
5861            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5862    } else {
5863        proposed
5864    }
5865}
5866
5867/// Apply this task's explicit count to the new attempt, without changing defaults.
5868fn apply_task_implementers(config: &mut Config, task: &Task) {
5869    if let Some(n) = task.implementers() {
5870        config.graph.implementers = n;
5871    }
5872}
5873
5874/// [`prepare`] for one task: its own `--config` and command-line overrides
5875/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5876/// over the loop's, so handing a hand-started task to a daemon changes nothing
5877/// about what it does.
5878#[cfg(test)]
5879fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5880    let explicit = match &task.overrides {
5881        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5882        _ => opts.config.as_deref(),
5883    };
5884    let (mut config, _) = Config::discover(repo, explicit)?;
5885    apply_options(&mut config, opts, task)?;
5886    Ok(config)
5887}
5888
5889fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5890    if task
5891        .overrides
5892        .as_ref()
5893        .is_none_or(|o| o.inherit_daemon_options)
5894        && let Some(mode) = opts.merge.as_deref()
5895    {
5896        config.merge.mode = merge_mode(mode)?;
5897    }
5898    if let Some(o) = &task.overrides {
5899        o.apply(config);
5900    }
5901    if let Some((mode, _)) = task.build_cache_override(config) {
5902        config.verify.build_cache = mode;
5903    }
5904    Ok(())
5905}
5906
5907/// Load the config for a task's repository, with the merge override applied.
5908fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5909    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5910    if let Some(mode) = &opts.merge {
5911        config.merge.mode = merge_mode(mode)?;
5912    }
5913    Ok(config)
5914}
5915
5916/// Prune the shared build cache at a between-runs boundary. The detached cache
5917/// service checks authoritative task jobs first; dispatch waits for that finite
5918/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5919/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5920async fn maybe_prune_cache_between_runs(
5921    repo: &Path,
5922    opts: &Opts,
5923    home: &Path,
5924    stop: &Stop,
5925    last_checked: &mut Option<Timestamp>,
5926    now: Timestamp,
5927) {
5928    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5929        return;
5930    }
5931    *last_checked = Some(now);
5932    let cfg = match prepare(repo, opts) {
5933        Ok(cfg) => cfg,
5934        Err(e) => {
5935            tracing::warn!("cache check: no config: {e:#}");
5936            return;
5937        }
5938    };
5939    match clean::prune_cache_if_over_limit(&cfg, home) {
5940        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5941            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5942            pruned.files,
5943            pruned.freed
5944        ),
5945        Ok(_) => {}
5946        Err(e) => {
5947            tracing::warn!("housekeep: prune cache: {e:#}");
5948            notices::raise_in(
5949                home,
5950                Notice::warn(
5951                    "housekeep:cache",
5952                    format!(
5953                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5954                        e.to_string()
5955                            .lines()
5956                            .next()
5957                            .unwrap_or("unknown cleanup error")
5958                    ),
5959                ),
5960            );
5961        }
5962    }
5963}
5964
5965/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5966/// now, given when it last did (if ever). Pure, so the cadence is asserted
5967/// directly rather than by waiting out real minutes in a test.
5968fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5969    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5970}
5971
5972/// The disk janitor, with its housekeeping logged rather than fatal.
5973///
5974/// Called only at the loop's idle points, for the reason the caller documents:
5975/// a prune racing a live compile would delete files mid-build. The config is
5976/// re-read on every call because the repository that just ran may not be the
5977/// daemon's own default, and the cache directory is a repository fact.
5978///
5979/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5980/// and [`crate::run::default_worktree_root`] read here, for the same reason
5981/// [`drive`] takes its queue and status file rather than resolving them: a
5982/// test driving the loop must not reach through to the operator's real home
5983/// or worktree bay just because the janitor runs on every idle tick.
5984/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5985/// to get wrong silently - a test's `home` was already isolated, but nothing
5986/// exercised the parameter next to it, so a real worktree bay stayed wired in
5987/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5988/// it for real, every test in this file that drives the loop at all started
5989/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5990async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5991    let cfg = match prepare(repo, opts) {
5992        Ok(cfg) => cfg,
5993        Err(e) => {
5994            tracing::warn!("housekeep: no config: {e:#}");
5995            return;
5996        }
5997    };
5998    // A run's own worktree lives under `config.graph.worktree_root` when the
5999    // repository sets one - the same precedence `RunState::worktree_root`
6000    // uses - and `worktrees_root` only stands in for the *default* an
6001    // unconfigured repository resolves to (see this function's own
6002    // parameter, or the test fixture wiring one to a fake path). Housekeeping
6003    // that always swept the default regardless of this override would never
6004    // see, and so never reclaim, a single worktree for a repository that
6005    // relocated them elsewhere.
6006    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
6007    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
6008    // Reported whenever there is anything to say, not only when `folded > 0`:
6009    // the incident this exists to prevent was 90 of 93 runs skipped and 0
6010    // folded, on every single pass, for months - a report gated on `folded`
6011    // would have stayed silent through every one of them.
6012    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
6013        let mut extra = Vec::new();
6014        if out.unreadable > 0 {
6015            extra.push(format!("{} unreadable", out.unreadable));
6016        }
6017        if out.orphaned_worktrees > 0 {
6018            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
6019        }
6020        let detail = if extra.is_empty() {
6021            String::new()
6022        } else {
6023            format!(" ({})", extra.join(", "))
6024        };
6025        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
6026    }
6027    if out.external_merges_recorded > 0 {
6028        tracing::info!(
6029            "housekeep: recorded {} run(s) as merged externally",
6030            out.external_merges_recorded
6031        );
6032    }
6033    if out.stale_pr_states_repaired > 0 {
6034        tracing::info!(
6035            "housekeep: rewrote {} run record(s) whose pull request had already settled",
6036            out.stale_pr_states_repaired
6037        );
6038    }
6039    if out.cache_files > 0 {
6040        tracing::info!(
6041            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
6042            out.cache_files,
6043            out.cache_freed
6044        );
6045    }
6046    if out.questions_abandoned > 0 {
6047        tracing::info!(
6048            "housekeep: abandoned {} question(s) left open by a finished run",
6049            out.questions_abandoned
6050        );
6051    }
6052}
6053
6054/// Run [`triage::run_once`] and log whatever it did, the same "only when
6055/// there is something to say" rule [`janitor`] follows for its own report.
6056///
6057/// Called at the same idle points as [`janitor`] - once per full poll
6058/// interval, never mid-attempt - for the same reason: it is not liveness
6059/// critical, and a task's own `hold_reason` string is the one thing this
6060/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
6061/// tick for no benefit.
6062async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
6063    let questions = Questions::at(home.join("questions"));
6064    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
6065    if report.is_empty() {
6066        return;
6067    }
6068    if !report.quarantined.is_empty() {
6069        tracing::info!(
6070            "triage: held {} blocked task(s) whose blocked-on task or \
6071             question no longer exists: {}",
6072            report.quarantined.len(),
6073            report.quarantined.join(", ")
6074        );
6075    }
6076    if !report.resumed.is_empty() {
6077        tracing::info!(
6078            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
6079            report.resumed.len(),
6080            report.resumed.join(", ")
6081        );
6082    }
6083    if !report.asked.is_empty() {
6084        tracing::info!(
6085            "triage: asked about {} held task(s): {}",
6086            report.asked.len(),
6087            report.asked.join(", ")
6088        );
6089    }
6090    if !report.answered.is_empty() {
6091        tracing::info!(
6092            "triage: applied {} operator answer(s): {}",
6093            report.answered.len(),
6094            report.answered.join(", ")
6095        );
6096    }
6097}
6098
6099/// The free-space gate: what stands between this task and a new run, if
6100/// anything. `Some(reason)` holds the task; `None` lets it start.
6101///
6102/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
6103/// the operator opted out. A measurement failure is a gate, not a pass: both
6104/// sides of "cannot tell" are served by not starting.
6105pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
6106    disk_gate_at(repo, config, crate::run::home)
6107}
6108
6109pub(crate) fn disk_gate_at(
6110    repo: &Path,
6111    config: &Config,
6112    home: impl FnOnce() -> PathBuf,
6113) -> Option<String> {
6114    let measure = if crate::build_target::isolated(config) {
6115        crate::disk::managed_free_bytes
6116    } else {
6117        crate::disk::free_bytes
6118    };
6119    disk_gate_with(repo, config, home, measure)
6120}
6121
6122/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
6123/// test can assert the exact wiring `attempt` runs - config's threshold in,
6124/// task-holding reason out - without asking the real machine's disk anything.
6125fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
6126    repo: &Path,
6127    config: &Config,
6128    home: impl FnOnce() -> PathBuf,
6129    free_bytes: F,
6130) -> Option<String> {
6131    let min = config.disk.min_free_bytes;
6132    if min == 0 {
6133        return None;
6134    }
6135    let output = match config.verify.build_cache {
6136        BuildCache::Shared => config.cache_dir(),
6137        BuildCache::Isolated => Some(home()),
6138    };
6139    let default_worktree_root;
6140    let worktree_root = match config.graph.worktree_root.as_deref() {
6141        Some(root) => root,
6142        None => {
6143            default_worktree_root = crate::run::default_worktree_root();
6144            &default_worktree_root
6145        }
6146    };
6147    for path in [Some(repo), output.as_deref(), Some(worktree_root)]
6148        .into_iter()
6149        .flatten()
6150    {
6151        let probe = if path == repo {
6152            path
6153        } else {
6154            path.ancestors().find(|p| p.exists()).unwrap_or(path)
6155        };
6156        let reason = match free_bytes(probe) {
6157            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
6158            Err(e) => Some(crate::disk::unmeasured_in(
6159                probe,
6160                &e,
6161                &config.graph.language,
6162            )),
6163        };
6164        if reason.is_some() {
6165            return reason;
6166        }
6167    }
6168    None
6169}
6170
6171/// How long to wait before offering another task when a run lost a seat to a
6172/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
6173/// could read, or carried nothing at all. Long enough that a quota outage
6174/// cannot burn through a whole backlog in the few seconds each doomed attempt
6175/// takes to fail; short enough that a quota which clears early is not left
6176/// idle for the fallback's sake.
6177const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
6178
6179/// Longest a parsed reset hint may push the wait out to. The hint comes from
6180/// the CLI's own words, not a contract, so a parsing slip that lands a day
6181/// away must not leave the loop asleep for a day.
6182const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
6183
6184/// How long [`poll`] should wait before offering the next task, after a run
6185/// lost at least one seat to a rate limit.
6186///
6187/// Pure and separate from the loop so the policy can be exercised without a
6188/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
6189/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
6190/// nothing to parse, or the parsed time has already passed; `cap` bounds how
6191/// far a parsed hint is trusted to push the wait out.
6192fn quota_wait(
6193    reset_at: Option<Timestamp>,
6194    now: Timestamp,
6195    fallback: Duration,
6196    cap: Duration,
6197) -> Duration {
6198    match reset_at {
6199        Some(at) if at > now => {
6200            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
6201            Duration::from_secs(secs).min(cap)
6202        }
6203        _ => fallback,
6204    }
6205}
6206
6207/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
6208///
6209/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
6210/// explains why parsing it exactly "would be a bug factory" — so this only
6211/// recognises the shapes actually observed in the wild, and returns `None`
6212/// for anything else rather than guess at a format nobody has seen.
6213///
6214/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
6215/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
6216/// said it, not from whenever this loop happens to read it: anchoring on `now`
6217/// would push the reset later on every read and would read an already-elapsed
6218/// reset as still in the future. (A long hint is still clamped by
6219/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
6220fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
6221    parse_reset_hint_zoned(text, now)
6222        .or_else(|| parse_reset_hint_dated(text))
6223        .or_else(|| parse_reset_hint_relative(text, recorded))
6224}
6225
6226/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
6227/// optional but at least one required, in that order. A bare number or any
6228/// unknown unit is refused.
6229fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
6230    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
6231    let mut rest = rest.trim();
6232    if rest.is_empty() {
6233        return None;
6234    }
6235    let mut total: i64 = 0;
6236    let mut matched = false;
6237    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
6238        if let Some((digits, tail)) = rest.split_once(unit)
6239            && !digits.is_empty()
6240            && digits.bytes().all(|b| b.is_ascii_digit())
6241        {
6242            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
6243            rest = tail;
6244            matched = true;
6245        }
6246    }
6247    if !rest.is_empty() || !matched {
6248        return None;
6249    }
6250    recorded
6251        .checked_add(jiff::SignedDuration::from_secs(total))
6252        .ok()
6253}
6254
6255/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
6256/// case-insensitive) into a 24-hour hour and minute. Shared by every
6257/// reset-hint shape below.
6258fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
6259    let clock = clock.trim().to_lowercase();
6260    let (digits, pm) = clock
6261        .strip_suffix("am")
6262        .map(|d| (d, false))
6263        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
6264    let (h, m) = digits.trim().split_once(':')?;
6265    let mut hour: i8 = h.trim().parse().ok()?;
6266    let minute: i8 = m.trim().parse().ok()?;
6267    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
6268        return None;
6269    }
6270    if pm && hour != 12 {
6271        hour += 12;
6272    } else if !pm && hour == 12 {
6273        hour = 0;
6274    }
6275    Some((hour, minute))
6276}
6277
6278/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
6279/// and a zone, never a date. A clock reading already past today is read as
6280/// tomorrow's: a CLI naming a same-day reset that has already gone by means
6281/// the window rolled over while nothing was watching.
6282fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
6283    let open = text.find('(')?;
6284    let close = text.rfind(')')?;
6285    if close <= open {
6286        return None;
6287    }
6288    let zone = text[open + 1..close].trim();
6289    let (hour, minute) = parse_12h_clock(&text[..open])?;
6290    let tz = jiff::tz::TimeZone::get(zone).ok()?;
6291    let candidate = now
6292        .to_zoned(tz)
6293        .with()
6294        .hour(hour)
6295        .minute(minute)
6296        .second(0)
6297        .millisecond(0)
6298        .microsecond(0)
6299        .nanosecond(0)
6300        .build()
6301        .ok()?;
6302    let mut at = candidate.timestamp();
6303    if at <= now {
6304        at += jiff::SignedDuration::from_hours(24);
6305    }
6306    Some(at)
6307}
6308
6309/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
6310/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
6311/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
6312/// "already past today" correction to make: the year already disambiguates
6313/// it. Scanned as a five-word window so it can be pulled out of the middle
6314/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
6315/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
6316/// any other timestamp with no zone attached.
6317fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
6318    let words: Vec<&str> = text.split_whitespace().collect();
6319    if words.len() < 5 {
6320        return None;
6321    }
6322    (0..=words.len() - 5)
6323        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
6324}
6325
6326/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
6327/// parenthesis right after the window is refused rather than ignored — it
6328/// reads as an explicit zone annotation on a shape that otherwise carries
6329/// none, and guessing UTC anyway would be exactly the silent misread this
6330/// module's parsing otherwise avoids.
6331fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
6332    if trailing.is_some_and(|next| next.starts_with('(')) {
6333        return None;
6334    }
6335    let month = month_number(window[0])?;
6336    let day_token = window[1].strip_suffix(',')?.to_lowercase();
6337    let day_digits = ["st", "nd", "rd", "th"]
6338        .iter()
6339        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
6340    let day: i8 = day_digits.parse().ok()?;
6341    let year_token = window[2];
6342    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
6343        return None;
6344    }
6345    let year: i16 = year_token.parse().ok()?;
6346    // The am/pm word carries the sentence's own trailing punctuation, e.g.
6347    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
6348    // reusing the same 12-hour clock reader the bracketed shape uses.
6349    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
6350    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
6351    let date = jiff::civil::Date::new(year, month, day).ok()?;
6352    let candidate = date
6353        .at(hour, minute, 0, 0)
6354        .to_zoned(jiff::tz::TimeZone::UTC)
6355        .ok()?;
6356    Some(candidate.timestamp())
6357}
6358
6359/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
6360/// case-insensitively, into a 1-based month number.
6361fn month_number(name: &str) -> Option<i8> {
6362    const NAMES: [&str; 12] = [
6363        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
6364    ];
6365    let lower = name.to_lowercase();
6366    NAMES
6367        .iter()
6368        .position(|n| *n == lower.as_str())
6369        .map(|i| i as i8 + 1)
6370}
6371
6372/// Test probe for the shared resume policy's review-budget exclusion.
6373#[cfg(test)]
6374fn exhausted_review_budget(state: &RunState) -> bool {
6375    // A run whose task-head publication failed has nothing left to review:
6376    // resuming it only retries the publication, so it is never "exhausted".
6377    !crate::handover::can_resume(state)
6378        && state.status == RunStatus::Blocked
6379        && !state.released()
6380        && state.retired_to.is_none()
6381}
6382
6383/// This task's *most recent* run, if resuming it would actually make
6384/// progress. `short` is only for the warning's own message.
6385///
6386/// Only ever `runs.last()` — never a search back through older history.
6387/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
6388/// mint, oldest first, and every entry before the last one was already
6389/// superseded at the moment it was minted: the daemon only ever starts a new
6390/// run when the previous one was not worth resuming (unresumable, exhausted,
6391/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
6392/// opens a fresh review-only run alongside an older, already-failed
6393/// competition. Searching further back would let an old run that merely
6394/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
6395/// behind, say — get resumed instead of the fresh competition
6396/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
6397/// nothing asked to revisit.
6398///
6399/// Two runs paid for the "prefer resuming over restarting" half of this
6400/// lesson, which is why this still checks `runs.last()` rather than always
6401/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
6402/// task a moment later, duplicating two and a half hours of agent work. Then
6403/// b25f stalled on a judge that timed out and one that answered with no JSON
6404/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
6405/// **one second** later, buying three fresh implementations to reach the
6406/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
6407/// the second case: a stall is terminal, and its cheap recovery re-asks only
6408/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
6409/// that is technically `resumable()` but provably cannot progress must not
6410/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
6411/// no-op instead of the fresh competition it promises.
6412///
6413/// A load failure is warned about rather than silently read as "not
6414/// resumable": the alternative is exactly what let a schema mismatch on run
6415/// `eba2` fall through to a full re-competition with nobody told why.
6416/// `crate::conduct` is what actually offers a better answer than
6417/// `Runner::start` here (see `Recovery::Review`), once this task's next
6418/// failure shows it up as `held`/`failed` with the run state unreadable.
6419fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
6420    unfinished_run_with(runs, short, RunState::load)
6421}
6422
6423/// [`unfinished_run`] with an injected state reader. Tests provide their
6424/// fixtures directly rather than touching the process-global run home.
6425pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6426where
6427    F: FnMut(&str) -> Result<RunState>,
6428{
6429    let mut id = runs.last()?.clone();
6430    let mut visited = std::collections::BTreeSet::new();
6431    let mut repo = None;
6432    loop {
6433        if !runs.contains(&id) || !visited.insert(id.clone()) {
6434            tracing::warn!("invalid or cyclic recovery authority for task {short}");
6435            return None;
6436        }
6437        let state = match load(&id) {
6438            Ok(state) if state.id == id => state,
6439            Ok(_) => return None,
6440            Err(e) => {
6441                tracing::warn!("could not read run {id} for task {short}: {e:#}");
6442                return None;
6443            }
6444        };
6445        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6446            return None;
6447        }
6448        repo = Some(state.repo.clone());
6449        if let Some(authority) = state.retired_to {
6450            id = authority;
6451            continue;
6452        }
6453        return (crate::handover::can_resume(&state)
6454            && state.liveness(false) != crate::run::Liveness::Live)
6455            .then_some(id);
6456    }
6457}
6458
6459/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
6460/// that [`attempt`] will resume it on its own?
6461///
6462/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
6463/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
6464/// injected reader like its sibling. An unreadable run is not awaiting
6465/// anything: it keeps going to the conductor as before.
6466fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6467where
6468    F: FnOnce(&str) -> Result<RunState>,
6469{
6470    // `Failed` stays: a record an older build wrote for a parked run.
6471    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6472        || task.fresh_start
6473        || task.review_branch.is_some()
6474    {
6475        return false;
6476    }
6477    let Some(id) = task.execution_runs().last() else {
6478        return false;
6479    };
6480    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6481}
6482
6483/// Which of the three ways [`attempt`] can mint or continue a run this task
6484/// should use.
6485#[derive(Debug, Clone, PartialEq, Eq)]
6486enum Starter {
6487    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
6488    /// and that still exists.
6489    Review(String),
6490    /// `crate::graph::Runner::resume` on an unfinished run of this task.
6491    Resume(String),
6492    /// `crate::graph::Runner::start`: a fresh competition.
6493    Start,
6494}
6495
6496/// A second bound independent of inputs and the resettable failure counter.
6497/// Count execution and failed-startup recovery records once per run. Startup
6498/// failures can retain unrecorded preparation assets without an execution pass.
6499/// Unknown history is not evidence that a new set of worktrees is affordable.
6500fn retained_attempt_hold(
6501    task: &Task,
6502    starter: &Starter,
6503    limit: usize,
6504    mut load: impl FnMut(&str) -> Result<RunState>,
6505) -> Option<String> {
6506    if limit == 0 || matches!(starter, Starter::Resume(_)) {
6507        return None;
6508    }
6509    let mut retained = 0;
6510    for id in task
6511        .runs
6512        .iter()
6513        .chain(task.startup_failures.iter().map(|failure| &failure.run))
6514        .collect::<std::collections::BTreeSet<_>>()
6515    {
6516        let state = match load(id) {
6517            Ok(state) if state.id == *id => state,
6518            _ => {
6519                return Some(format!(
6520                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6521                ));
6522            }
6523        };
6524        if state.retired_to.is_some() || state.released() {
6525            continue;
6526        }
6527        // Neither a completed status nor an empty candidate array proves that
6528        // all recovery sources (including unrecorded preparation) were retired.
6529        retained += 1;
6530    }
6531    (retained >= limit).then(|| format!(
6532        "[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."
6533    ))
6534}
6535
6536/// A selected public implementation overrides every historical candidate and pin.
6537fn selected_starter(
6538    selected: &crate::pr_recovery::Selection,
6539    previous: Option<&RunState>,
6540    unfinished: Option<&str>,
6541) -> Starter {
6542    if let Some(id) = unfinished
6543        && previous.is_some_and(|r| {
6544            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6545        })
6546    {
6547        Starter::Resume(id.to_owned())
6548    } else {
6549        Starter::Review(selected.branch.clone())
6550    }
6551}
6552
6553/// The owner's answer to this branch's divergence question, consumed from the
6554/// task so a later, different divergence asks again. The runner applies it
6555/// (see `Runner::review_taking_over`), after the earlier worktree is released.
6556fn take_divergence_answer(
6557    branch: &str,
6558    remote: &str,
6559    task: &mut Task,
6560) -> Option<crate::reconcile::Choice> {
6561    let summary = crate::reconcile::summary_for(branch, remote);
6562    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6563        (a.question == summary)
6564            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6565            .flatten()
6566            .map(|c| (i, c))
6567    })?;
6568    task.answers.remove(idx);
6569    Some(choice)
6570}
6571
6572/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
6573/// this attempt should use. Pure, and separate from [`attempt`], so the
6574/// routing itself is assertable without spawning a real graph or a git
6575/// process: `attempt`'s own `crate::git::branch_exists` call has already
6576/// happened by the time this is called.
6577///
6578/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
6579/// whose branch is gone falls all the way through to [`Starter::Start`], not
6580/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
6581/// old (likely `Blocked`) run in the first place, and a branch that vanished
6582/// out from under that choice is not evidence resuming it would fare better.
6583fn choose_starter(
6584    review_branch: Option<&str>,
6585    branch_exists: bool,
6586    unfinished: Option<&str>,
6587) -> Starter {
6588    match review_branch {
6589        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6590        Some(_) => Starter::Start,
6591        None => match unfinished {
6592            Some(id) => Starter::Resume(id.to_owned()),
6593            None => Starter::Start,
6594        },
6595    }
6596}
6597
6598/// Reuse a compatible latest review owner instead of taking its checked-out
6599/// branch into a new run. Different branches and changed criteria still use
6600/// the ordinary review/takeover policy.
6601fn review_retry_starter(
6602    task: &Task,
6603    previous: Option<&RunState>,
6604    branch: Option<&str>,
6605    exists: bool,
6606    unfinished: Option<&str>,
6607) -> Starter {
6608    if let Some(run) = previous
6609        && unfinished == Some(run.id.as_str())
6610        && run.reviewed_commits.is_some()
6611        && branch.is_some_and(|branch| {
6612            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6613        })
6614        && may_resume_run(run, task)
6615    {
6616        return Starter::Resume(run.id.clone());
6617    }
6618    match (branch, unfinished, &task.review_of) {
6619        (None, None, Some(branch)) => Starter::Review(branch.clone()),
6620        _ => choose_starter(branch, exists, unfinished),
6621    }
6622}
6623
6624/// A retained review is valid only while its authored criteria still match.
6625fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
6626    task.review_branch
6627        .as_deref()
6628        .filter(|&branch| match &task.review_instruction {
6629            Some(authored) => *authored == task.instruction,
6630            // Legacy retained branches must agree with their prior run; only an
6631            // explicitly pinned review can proceed without recoverable provenance.
6632            None => previous.map_or_else(
6633                || task.review_of.as_deref() == Some(branch),
6634                |run| compatible_run_instruction(run, task),
6635            ),
6636        })
6637}
6638
6639/// A current explicit pin can select an otherwise incompatible run. Edits
6640/// and subsequent approvals invalidate pins selected for earlier criteria.
6641fn may_resume_run(run: &RunState, task: &Task) -> bool {
6642    if !task.assignment_accepts(run) {
6643        return false;
6644    }
6645    task.resume_override
6646        .as_ref()
6647        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6648        || compatible_run_instruction(run, task)
6649}
6650
6651/// Review scaffolding is execution context, not evidence of an operator edit.
6652pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6653    if let Some(authored) = &run.task_instruction {
6654        return compatible_instruction(authored, task);
6655    }
6656    if compatible_instruction(&run.instruction, task) {
6657        return true;
6658    }
6659    // Recognize only the existing generated review shapes on legacy runs.
6660    // Ordinary authored text with a similar heading is left intact.
6661    if run.reviewed_commits.is_some() {
6662        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6663            return strip_answers_block(authored, task).trim() == task.instruction.trim();
6664        }
6665        if let Some(branch) = &task.review_of {
6666            let canonical = format!(
6667                "Review the branch `{branch}` (review-only: no implementation, no judging)."
6668            );
6669            let generated = format!(
6670                "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"
6671            );
6672            return task.instruction == canonical && run.instruction.starts_with(&generated);
6673        }
6674    }
6675    false
6676}
6677
6678/// Compare authored instructions, excluding answer blocks appended by the daemon.
6679pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6680    strip_answers_block(old, task) == task.instruction
6681}
6682
6683/// Which repository a task runs in. A task that names none — the normal case
6684/// for one filed from a phone — runs in the daemon's own default.
6685fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6686    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6687        return fallback.to_path_buf();
6688    }
6689    task.repo.clone()
6690}
6691
6692/// The header [`append_answers`] appends operator answers under. Shared with
6693/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
6694/// rather than grown a new block on every resume.
6695const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6696
6697/// Render the first `count` answers in the block appended to an instruction.
6698fn answers_block(task: &Task, count: usize) -> String {
6699    let mut s = ANSWERS_HEADER.to_owned();
6700    for a in &task.answers[..count] {
6701        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6702    }
6703    s
6704}
6705
6706/// Render the approval independently of transient task state, so historical
6707/// suffixes remain recognizable after another explicit release.
6708fn resumption_block(r: &crate::queue::Resumption) -> String {
6709    format!(
6710        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6711         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6712        r.generation, r.at, r.instruction, r.answers_through,
6713    )
6714}
6715
6716/// Append audit answers and the latest explicit approval to the instruction.
6717fn append_answers(base: &str, task: &Task) -> String {
6718    let mut s = base.to_owned();
6719    if !task.answers.is_empty() {
6720        s.push_str(&answers_block(task, task.answers.len()));
6721    }
6722    if let Some(r) = &task.resumption {
6723        s.push_str(&resumption_block(r));
6724    }
6725    s
6726}
6727
6728/// Drop the prior answer block only when it is exactly the suffix this task
6729/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6730/// the task author is ordinary instruction text, not a block to remove.
6731fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6732    let mut instruction = instruction;
6733    for approval in task
6734        .resumption
6735        .iter()
6736        .chain(task.resumption_history.iter().rev())
6737    {
6738        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6739            instruction = base;
6740            break;
6741        }
6742    }
6743    for count in (1..=task.answers.len()).rev() {
6744        let block = answers_block(task, count);
6745        if let Some(base) = instruction.strip_suffix(&block) {
6746            return base;
6747        }
6748    }
6749    instruction
6750}
6751
6752/// The instruction handed to `Runner::start`: the task's own text, plus any
6753/// operator answers `crate::conduct` collected for it (see
6754/// [`Task::answers`]), so a decision the operator actually made reaches the
6755/// implementers rather than only clearing the block that was waiting on it.
6756///
6757/// Appended rather than merged into [`Task::instruction`] itself, so the
6758/// task's own record stays exactly what its author wrote.
6759fn instruction_for(task: &Task) -> String {
6760    append_answers(&task.instruction, task)
6761}
6762
6763/// The instruction a resumed run should carry on with: whatever it already
6764/// had, refreshed with the task's *current* operator answers.
6765///
6766/// A resumable run's own `RunState::instruction` predates any answer
6767/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6768/// the behaviour before this function existed — silently drops the very
6769/// decision the operator made to unblock it. Re-stripping any block this
6770/// function appended on an earlier resume before re-appending the current
6771/// list (rather than blindly appending again) is what keeps a task resumed
6772/// three times over three answered questions from carrying the same answer
6773/// three times.
6774fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6775    append_answers(strip_answers_block(old_instruction, task), task)
6776}
6777
6778/// Preserve the producer's verified boundary and target, independent of prose.
6779fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6780    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6781    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6782    if let Some(cause) = task.hold_notice_cause.as_mut() {
6783        cause.target = failure.map(|f| f.target.clone());
6784    }
6785}
6786
6787#[derive(Debug, thiserror::Error)]
6788#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6789struct MissingAttachment {
6790    name: String,
6791    path: PathBuf,
6792}
6793
6794/// The task's attachments as absolute paths, each checked to still exist.
6795fn task_attachments(
6796    queue: &Queue,
6797    task: &Task,
6798) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6799    let paths = queue.attachment_paths(task);
6800    for (name, path) in task.attachments.iter().zip(&paths) {
6801        if !path.is_file() {
6802            return Err(MissingAttachment {
6803                name: name.clone(),
6804                path: path.clone(),
6805            });
6806        }
6807    }
6808    Ok(paths)
6809}
6810
6811/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6812/// answers before handing it to `Runner` — the actual boundary between
6813/// [`choose_starter`]'s routing and the graph, factored out so it is
6814/// assertable without a real repository, git branch, or agent CLI.
6815///
6816/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6817/// instruction from the reviewed branch's own commit log because there is no
6818/// task statement to speak of for hand-written work, and splicing operator
6819/// answers into that text would contradict the very message it sends
6820/// reviewers ("there is no task statement").
6821fn prepare_instruction(
6822    starter: &Starter,
6823    old_instruction: Option<&str>,
6824    task: &Task,
6825) -> Option<String> {
6826    match starter {
6827        Starter::Start => Some(instruction_for(task)),
6828        Starter::Resume(_) => Some(resumed_instruction(
6829            old_instruction.expect("a resumed run always has a prior instruction"),
6830            task,
6831        )),
6832        Starter::Review(_) => None,
6833    }
6834}
6835
6836/// Persist a transition. A queue write failure is logged rather than fatal: the
6837/// run already happened, and taking the daemon down would only add a lost
6838/// backlog to a full disk.
6839fn record(queue: &Queue, task: &mut Task) {
6840    if let Err(e) = queue.put(task) {
6841        tracing::error!("could not record task {}: {e:#}", task.short());
6842        let notice = Notice::error(
6843            "loop:record",
6844            format!(
6845                "Task {} state could not be saved: {}. Check the disk.",
6846                task.id,
6847                e.to_string().lines().next().unwrap_or("unknown save error")
6848            ),
6849        )
6850        .link(Link::Task {
6851            id: task.id.clone(),
6852        });
6853        // The queue lives at `<home>/queue`, so its parent is the home.
6854        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6855            Some(home) => notices::raise_in(home, notice),
6856            None => notices::raise(notice),
6857        }
6858    }
6859}
6860
6861/// Every runnable task, in the order the loop should try them.
6862///
6863/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6864/// tail exists so that a claim somebody else holds costs the loop the next
6865/// candidate rather than a whole poll interval of idleness.
6866fn runnable(queue: &Queue) -> Vec<Task> {
6867    let mut tasks: Vec<Task> = queue
6868        .list()
6869        .into_iter()
6870        .filter(|t| t.status.runnable())
6871        .collect();
6872    tasks.sort_unstable_by(crate::queue::dispatch_order);
6873    tasks
6874}
6875
6876/// Why a run ended where it did, in one line, for [`Task::last_error`].
6877///
6878/// A stalled run names the seats the quota took out: "out of quota" is not
6879/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6880/// agent to replace or which plan to top up.
6881///
6882/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6883/// purpose: unlike `label`'s other callers (an internal log line, an
6884/// already-a-bug fallback message), this string becomes `Task::last_error`
6885/// verbatim, which the phone renders in the same alarm-styled box an
6886/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6887/// `.err` styling. A bare `verified_noop` there would read exactly like the
6888/// failure this whole feature exists to tell apart from one.
6889fn describe(state: &RunState) -> String {
6890    let p = phrases(&state.config.graph.language);
6891    let mut detail = if state.status == RunStatus::Stalled {
6892        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6893        seats.sort_unstable();
6894        seats.dedup();
6895        if seats.is_empty() {
6896            p.quorum_lost.to_owned()
6897        } else {
6898            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6899        }
6900    } else {
6901        format!("{}{}", p.run_ended, state.status.display_label())
6902    };
6903    if let Some(cause) = state.verification_blocking_cause() {
6904        detail.push_str(&format!(" ({cause})"));
6905    } else if let Some(last) = state.events.last() {
6906        // The review loop's "never answered" stop is the one event worth
6907        // translating; it is recognised from structured state, not by
6908        // matching the English event text (which stays as recorded).
6909        let unanswered = state
6910            .reviews
6911            .last()
6912            .filter(|r| {
6913                state.status == RunStatus::Blocked
6914                    && last.node == "review"
6915                    && r.incomplete()
6916                    && r.blocking == 0
6917                    && r.round == state.config.graph.review_rounds
6918                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6919            })
6920            .map(|r| (r.expected - r.answered, r.round));
6921        match unanswered {
6922            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6923                detail.push_str(&format!(
6924                    " ({}: {})",
6925                    last.node,
6926                    (p.reviewers_never_answered)(missing, rounds)
6927                ));
6928            }
6929            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6930        }
6931    }
6932    detail.push_str(&format!(" [run {}]", state.id));
6933    detail
6934}
6935
6936/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6937///
6938/// The task file lives in the backlog indefinitely; a diagnostic is an
6939/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6940/// stay small regardless of how much a gate command or a candidate printed.
6941const DIAGNOSTIC_MAX: usize = 4_000;
6942
6943/// Tail kept from a single failing command's output inside a diagnostic.
6944/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6945/// pointer for a human deciding whether to go read the full artifact by hand,
6946/// not a replacement for reading it.
6947const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6948
6949/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6950/// `magi task show` says more than the one-line reason in [`describe`].
6951///
6952/// The one-liner answers "where did the run stop"; this answers "what would a
6953/// human have found opening `artifacts/` by hand" — the point of the whole
6954/// feature is the case that one-liner actively misleads on: a run held as "no
6955/// candidate produced a change" can mean the implementer actually finished
6956/// the task (opened a PR, merged it, tagged a release) and only left a clean
6957/// local worktree behind, which reads as "nothing happened" unless someone
6958/// goes and reads what the agent actually said. `None` when the run carries
6959/// none of the three shapes this recognises — an ordinary run held for
6960/// something not diagnosable from `RunState` alone still explains itself
6961/// through `Task::last_error`.
6962fn diagnostic(state: &RunState) -> Option<String> {
6963    let mut parts: Vec<String> = Vec::new();
6964
6965    // Gate failure: which check(s), and the tail of what each printed.
6966    for o in state.gate.iter().filter(|o| !o.ok()) {
6967        parts.push(format!(
6968            "gate `{}` failed ({}):\n{}",
6969            o.command,
6970            notices::exit_status(o.code),
6971            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6972        ));
6973    }
6974
6975    // The land loop gave up because the fixer declined while checks were
6976    // still red: the message already names them (see `land::run`).
6977    if let Some(last) = state
6978        .events
6979        .iter()
6980        .rev()
6981        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6982    {
6983        parts.push(last.message.clone());
6984    }
6985
6986    // No viable candidate: every implementer's own final word, sanitized the
6987    // same way a judge would have read it, so a run that actually finished
6988    // the job does not read as an unexplained failure. A verified no-op is
6989    // called out ahead of its own summary and apart from an ordinary
6990    // failure's `why` — this is the one candidate shape whose diagnostic a
6991    // human is expected to actually judge, not just skim.
6992    if state.viable().is_empty() {
6993        for c in &state.candidates {
6994            if let Some(evidence) = &c.verified_noop {
6995                parts.push(format!(
6996                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6997                    c.label
6998                ));
6999            } else if !c.summary.trim().is_empty() {
7000                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
7001            } else if let Some(why) = &c.failed {
7002                parts.push(format!("candidate {}: {why}", c.label));
7003            }
7004        }
7005    }
7006
7007    if parts.is_empty() {
7008        return None;
7009    }
7010    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
7011    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
7012    // back slightly over. Leave it enough room to always land under the
7013    // limit.
7014    Some(crate::run::tail(
7015        &parts.join("\n\n"),
7016        DIAGNOSTIC_MAX.saturating_sub(100),
7017    ))
7018}
7019
7020/// Stable lower-case name for a run status, for an internal log line and the
7021/// "graph stopped without reaching a terminal status" bug message in
7022/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
7023/// doc for why that one reads [`RunStatus::display_label`] instead. One
7024/// definition of a status's name, on the type that owns it: this table used
7025/// to live here as a second copy, and a status renamed in one place would
7026/// have gone on reading correctly in the other.
7027fn label(status: RunStatus) -> &'static str {
7028    status.as_str()
7029}
7030
7031/// Parse a merge mode override.
7032pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
7033    match mode {
7034        "none" => Ok(MergeMode::None),
7035        "local" => Ok(MergeMode::Local),
7036        "pr" => Ok(MergeMode::Pr),
7037        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
7038    }
7039}
7040
7041/// Take the status lock, recovering from a poisoned one.
7042///
7043/// A panic elsewhere must not silently stop the heartbeat: the status is plain
7044/// data, and the worst a poisoned lock can hold is a stale timestamp.
7045fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
7046    mutex
7047        .lock()
7048        .unwrap_or_else(std::sync::PoisonError::into_inner)
7049}
7050
7051#[cfg(test)]
7052mod tests {
7053    use super::*;
7054    use crate::queue::{Source, TaskStatus};
7055    use crate::run::{Candidate, CommandOutcome};
7056    use pretty_assertions::assert_eq;
7057
7058    fn task() -> Task {
7059        Task::new(
7060            "add retries".to_owned(),
7061            "add retries".to_owned(),
7062            PathBuf::from("/repo"),
7063            Source::Human,
7064        )
7065    }
7066
7067    #[test]
7068    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
7069        let skips = DispatchSkips::from([
7070            ("a".into(), SkipReason::CoolingDown),
7071            ("b".into(), SkipReason::WaitingOnLanding),
7072            ("c".into(), SkipReason::WaitingOnLanding),
7073            ("d".into(), SkipReason::OrdinaryCapacity),
7074        ]);
7075        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
7076        assert_eq!(wait.runnable, 4);
7077        assert_eq!(
7078            wait.reasons
7079                .iter()
7080                .map(|r| (r.reason.as_str(), r.count))
7081                .collect::<Vec<_>>(),
7082            [
7083                ("waiting_on_landing", 2),
7084                ("cooling_down", 1),
7085                ("ordinary_capacity", 1)
7086            ]
7087        );
7088        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
7089        assert!(
7090            aggregate_dispatch_wait(2, &DispatchSkips::new())
7091                .unwrap()
7092                .reasons
7093                .is_empty()
7094        );
7095    }
7096
7097    #[test]
7098    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
7099        let before = vec!["a".into(), "b".into(), "c".into()];
7100        let allowed = vec![task_with_id("b")];
7101        let skips = interrupt_skips(&before, &allowed);
7102        assert_eq!(
7103            skips,
7104            DispatchSkips::from([
7105                ("a".into(), SkipReason::InterruptGate),
7106                ("c".into(), SkipReason::InterruptGate),
7107            ])
7108        );
7109        let mut previous = DispatchSkips::new();
7110        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7111        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
7112        assert!(!changed_dispatch_skips(&mut previous, skips));
7113        assert!(changed_dispatch_skips(
7114            &mut previous,
7115            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
7116        ));
7117        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7118    }
7119
7120    #[test]
7121    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
7122        let mut value = serde_json::to_value(Status::new()).unwrap();
7123        value.as_object_mut().unwrap().remove("dispatch_wait");
7124        assert!(
7125            serde_json::from_value::<Status>(value.clone())
7126                .unwrap()
7127                .dispatch_wait
7128                .is_none()
7129        );
7130        assert!(
7131            serde_json::from_value::<Reading>(value.clone())
7132                .unwrap()
7133                .dispatch_wait
7134                .is_none()
7135        );
7136        value["dispatch_wait"] = serde_json::json!({
7137            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
7138        });
7139        let reading = serde_json::from_value::<Reading>(value).unwrap();
7140        assert_eq!(
7141            reading.dispatch_wait.unwrap().reasons[0].reason,
7142            "future_reason"
7143        );
7144    }
7145
7146    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
7147        let job = crate::worker::Job {
7148            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
7149            sequence: 1,
7150            kind: "task".into(),
7151            key: format!("task:{}", request.task),
7152            payload: serde_json::to_value(request).unwrap(),
7153            generation: "a".repeat(64),
7154            version: None,
7155            status: crate::worker::Status::Starting,
7156            result: None,
7157            pid: None,
7158            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
7159            finished_at: None,
7160        };
7161        let dir = home.join("workers/jobs").join(&job.id);
7162        std::fs::create_dir_all(&dir).unwrap();
7163        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
7164        job
7165    }
7166
7167    #[test]
7168    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
7169        let home = tempfile::tempdir().unwrap();
7170        let request = TaskWorker {
7171            opts: Opts::default(),
7172            queue: home.path().join("queue"),
7173            task: "startup".into(),
7174            lane: PermitKind::Ordinary,
7175            standalone: false,
7176        };
7177        let job = starting_task_reservation(home.path(), &request);
7178        let error = task_worker_spawn_error(
7179            home.path(),
7180            &request,
7181            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
7182        )
7183        .expect_err("our own reservation must not turn a failed spawn into a resync");
7184        let active = crate::worker::active(home.path()).unwrap();
7185        assert_eq!(active.len(), 1);
7186        assert_eq!(active[0].id, job.id);
7187        assert_eq!(active[0].status, crate::worker::Status::Starting);
7188        assert!(
7189            crate::worker::control(home.path(), &job.key)
7190                .unwrap()
7191                .is_none()
7192        );
7193        let notices = notices::Notices::at(home.path().join("notifications")).list();
7194        assert_eq!(notices.len(), 1);
7195        assert_eq!(notices[0].key, "loop:worker-startup");
7196        assert!(!notices[0].message.contains("private-error-detail"));
7197        assert!(notices[0].message.contains(&request.task));
7198        assert!(
7199            notices[0]
7200                .message
7201                .contains("could not be started or acknowledged")
7202        );
7203        assert!(notices[0].message.contains("worker.log"));
7204        assert_eq!(
7205            notices[0].link,
7206            Some(Link::Task {
7207                id: request.task.clone()
7208            })
7209        );
7210        assert!(format!("{error:#}").contains("private-error-detail"));
7211    }
7212
7213    #[test]
7214    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
7215        let home = tempfile::tempdir().unwrap();
7216        let mut request = TaskWorker {
7217            opts: Opts::default(),
7218            queue: home.path().join("queue"),
7219            task: "handoff".into(),
7220            lane: PermitKind::Ordinary,
7221            standalone: true,
7222        };
7223        let job = starting_task_reservation(home.path(), &request);
7224        request.standalone = false;
7225        task_worker_spawn_error(
7226            home.path(),
7227            &request,
7228            anyhow::anyhow!("operation key is already reserved for a different request"),
7229        )
7230        .expect("a different standalone request is the handoff race, not our startup failure");
7231        let active = crate::worker::active(home.path()).unwrap();
7232        assert_eq!(active.len(), 1);
7233        assert_eq!(active[0].id, job.id);
7234        assert_eq!(active[0].payload, job.payload);
7235        assert!(
7236            notices::Notices::at(home.path().join("notifications"))
7237                .list()
7238                .is_empty()
7239        );
7240    }
7241
7242    #[test]
7243    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
7244        let home = tempfile::tempdir().unwrap();
7245        let queue = Queue::at(home.path().join("queue"));
7246        let mut task = task();
7247        task.runs = vec!["previous".into()];
7248        queue.put(&mut task).unwrap();
7249        let request = TaskWorker {
7250            opts: Opts::default(),
7251            queue: home.path().join("queue"),
7252            task: task.id.clone(),
7253            lane: PermitKind::Ordinary,
7254            standalone: false,
7255        };
7256        let job = starting_task_reservation(home.path(), &request);
7257        let claims = current_work(home.path(), Timestamp::now());
7258        assert_eq!(claims.len(), 1);
7259        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
7260        assert_eq!(claims[0].run, "previous");
7261        assert!(other_claims_run(&claims, "previous", None));
7262        // Only after confirming the executing caller may admission ignore
7263        // this exact projection. Cleanup continues to observe it as live.
7264        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
7265        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
7266    }
7267
7268    #[test]
7269    fn admission_excludes_only_the_callers_exact_reservation() {
7270        let own = Current {
7271            worker: Some("own".into()),
7272            task: "same-task".into(),
7273            run: "previous".into(),
7274        };
7275        assert!(!other_claims_run(
7276            std::slice::from_ref(&own),
7277            "previous",
7278            Some("own")
7279        ));
7280        assert!(other_claims_run(
7281            std::slice::from_ref(&own),
7282            "previous",
7283            None
7284        ));
7285        for worker in [None, Some("other".into())] {
7286            let other = Current {
7287                worker,
7288                ..own.clone()
7289            };
7290            assert!(other_claims_run(
7291                &[own.clone(), other],
7292                "previous",
7293                Some("own")
7294            ));
7295        }
7296        let legacy: Current =
7297            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
7298        assert!(other_claims_run(&[legacy], "previous", Some("own")));
7299    }
7300
7301    #[test]
7302    fn os_leased_task_worker_survives_wall_clock_advance() {
7303        let home = tempfile::tempdir().unwrap();
7304        let queue = Queue::at(home.path().join("queue"));
7305        let mut task = task();
7306        let run = "20260903-100000-abcd";
7307        task.start(run.into());
7308        queue.put(&mut task).unwrap();
7309        let mut worker = live_task_fixture(home.path(), &task.id).unwrap();
7310        let future = Timestamp::now() + jiff::SignedDuration::from_secs(3600);
7311        assert!(
7312            current_work(home.path(), future)
7313                .iter()
7314                .any(
7315                    |claim| claim.worker.as_deref() == Some(worker.job.id.as_str())
7316                        && claim.run == run
7317                )
7318        );
7319        worker.release_lease();
7320        assert!(worker.dir.join("job.json").is_file());
7321        assert!(!is_working_on(home.path(), run, future));
7322        let dir = worker.dir.clone();
7323        drop(worker);
7324        assert!(!dir.exists());
7325    }
7326
7327    #[test]
7328    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
7329        let mut task = task();
7330        let mut run = run_state(RunStatus::Reviewing);
7331        run.task_instruction = Some(task.instruction.clone());
7332        run.reviewed_commits = Some(vec!["committed-fix".into()]);
7333        let branch = "magi/test/B";
7334        run.candidates.push(crate::run::Candidate {
7335            branch: branch.into(),
7336            ..candidate('B', "preserved work", false, None)
7337        });
7338        task.runs = vec![run.id.clone()];
7339        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
7340        assert_eq!(
7341            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7342            Starter::Resume(run.id.clone())
7343        );
7344        assert!(matches!(
7345            review_retry_starter(
7346                &task,
7347                Some(&run),
7348                Some("different"),
7349                true,
7350                unfinished.as_deref()
7351            ),
7352            Starter::Review(_)
7353        ));
7354        assert_eq!(
7355            review_retry_starter(
7356                &task,
7357                Some(&run),
7358                Some(branch),
7359                false,
7360                unfinished.as_deref()
7361            ),
7362            Starter::Start
7363        );
7364        task.instruction.push_str(" changed criteria");
7365        assert!(matches!(
7366            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7367            Starter::Review(_)
7368        ));
7369        assert!(matches!(
7370            review_retry_starter(&task, Some(&run), Some(branch), true, None),
7371            Starter::Review(_)
7372        ));
7373    }
7374
7375    #[test]
7376    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
7377        let dir = tempfile::tempdir().unwrap();
7378        let queue = Queue::at(dir.path().join("queue"));
7379        let mut task = task();
7380        task.status = TaskStatus::Running;
7381        task.attempts = 1;
7382        queue.put(&mut task).unwrap();
7383        let live = std::collections::BTreeSet::from([task.id.clone()]);
7384        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
7385        drop(queue.claim(&task.id).unwrap());
7386        let saved = queue.get(&task.id).unwrap();
7387        assert_eq!(saved.status, TaskStatus::Running);
7388        assert_eq!(saved.attempts, 1);
7389        assert!(saved.last_error.is_none());
7390    }
7391
7392    #[test]
7393    fn standalone_workers_do_not_consume_scheduler_lanes() {
7394        let request = |task: &str, lane, standalone| TaskWorker {
7395            opts: Opts::default(),
7396            queue: PathBuf::from("/queue"),
7397            task: task.to_owned(),
7398            lane,
7399            standalone,
7400        };
7401        let mut jobs = vec![
7402            request("ordinary", PermitKind::Ordinary, false),
7403            request("standalone-urgent", PermitKind::Urgent, true),
7404            request("standalone-ordinary", PermitKind::Ordinary, true),
7405            request("decision", PermitKind::None, false),
7406        ];
7407        assert_eq!(available_slots(&jobs, 2), (1, 1));
7408        jobs.push(request("urgent", PermitKind::Urgent, false));
7409        assert_eq!(available_slots(&jobs, 2), (1, 0));
7410        assert_eq!(available_slots(&jobs, 0), (0, 0));
7411    }
7412
7413    #[test]
7414    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
7415        let now = Timestamp::now();
7416        let mut reading = Reading {
7417            pid: Some(std::process::id()),
7418            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
7419            ..Reading::default()
7420        };
7421        assert!(!reading.running(now));
7422        assert!(legacy_scheduler_running(&reading, now, 0));
7423        reading.worker_protocol = Some(1);
7424        assert!(!legacy_scheduler_running(&reading, now, 0));
7425    }
7426
7427    #[test]
7428    fn selected_public_head_overrides_historical_resume_and_pin() {
7429        let mut t = task();
7430        let mut old = run_state(RunStatus::Blocked);
7431        let selection = crate::pr_recovery::Selection {
7432            url: "url".into(),
7433            branch: format!("magi/task-{}", t.id),
7434            head: "a".repeat(40),
7435            source_head: None,
7436            source_run: None,
7437            source_proof: None,
7438            disposition: Some(crate::pr_recovery::Disposition::Review),
7439            instruction: t.instruction.clone(),
7440            approved_at: Timestamp::now(),
7441        };
7442        t.resume_override = Some(crate::queue::OperatorResume {
7443            pinned_run: Some(old.id.clone()),
7444            question_id: "choice".into(),
7445            at: Timestamp::now(),
7446            conductor_rehold: None,
7447            forced: false,
7448        });
7449        assert_eq!(
7450            selected_starter(&selection, Some(&old), Some(&old.id)),
7451            Starter::Review(selection.branch.clone())
7452        );
7453        old.pr_recovery = Some(selection.clone());
7454        assert_eq!(
7455            selected_starter(&selection, Some(&old), Some(&old.id)),
7456            Starter::Review(selection.branch.clone())
7457        );
7458        old.reviewed_commits = Some(vec!["implementation".into()]);
7459        assert_eq!(
7460            selected_starter(&selection, Some(&old), Some(&old.id)),
7461            Starter::Resume(old.id.clone())
7462        );
7463        let mut changed = selection.clone();
7464        changed.head = "b".repeat(40);
7465        assert_eq!(
7466            selected_starter(&changed, Some(&old), Some(&old.id)),
7467            Starter::Review(changed.branch)
7468        );
7469    }
7470
7471    #[test]
7472    fn candidate_transplant_failure_is_one_actionable_hold() {
7473        let dir = tempfile::tempdir().unwrap();
7474        let q = Queue::at(dir.path().join("queue"));
7475        let mut t = task();
7476        let mut state = run_state(RunStatus::Blocked);
7477        state.event("prep", "cannot apply referenced commit: conflict");
7478        state.prep_failure = Some("conflict".into());
7479        t.start(state.id.clone());
7480        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
7481        assert_eq!(t.attempts, 1);
7482        assert_eq!(t.status, TaskStatus::Held);
7483        assert!(t.operator_held());
7484        assert!(!t.status.runnable());
7485        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
7486        let first = t.chat_notice_key().unwrap();
7487        t.chat_notices.push(first.clone());
7488        t.release_operator("test", None);
7489        state.id = "another-unprepared-run".into();
7490        t.start(state.id.clone());
7491        finish_attempt(
7492            3,
7493            &q,
7494            &mut t,
7495            &state,
7496            &[],
7497            Err(anyhow::anyhow!("still conflicts")),
7498        );
7499        assert_eq!(
7500            t.chat_notice_key().as_ref(),
7501            Some(&first),
7502            "no work happened"
7503        );
7504        t.release_operator("test", None);
7505        state.prep_failure = None;
7506        state.status = RunStatus::Failed;
7507        state.begin_pass();
7508        t.start(state.id.clone());
7509        finish_attempt(
7510            1,
7511            &q,
7512            &mut t,
7513            &state,
7514            &[],
7515            Err(anyhow::anyhow!("new gate failure")),
7516        );
7517        let failure = t.chat_notice_key().unwrap();
7518        assert_ne!(failure, first, "approved recovery reached a real failure");
7519        t.release_operator("test", None);
7520        state.begin_pass();
7521        t.start(state.id.clone());
7522        finish_attempt(
7523            1,
7524            &q,
7525            &mut t,
7526            &state,
7527            &[],
7528            Err(anyhow::anyhow!("new failure on resume")),
7529        );
7530        assert_ne!(
7531            t.chat_notice_key().as_ref(),
7532            Some(&failure),
7533            "a new settled pass"
7534        );
7535    }
7536
7537    #[test]
7538    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7539        for source in ["cli", "web"] {
7540            let mut t = task();
7541            let mut run = run_state(RunStatus::Blocked);
7542            run.instruction = "Run A original criteria".into();
7543            run.task_instruction = Some(run.instruction.clone());
7544            t.start(run.id.clone());
7545            t.release_operator("choice", Some("resume-question"));
7546            t.resume_override = Some(crate::queue::OperatorResume {
7547                question_id: "resume-question".into(),
7548                at: Timestamp::now(),
7549                conductor_rehold: None,
7550                forced: true,
7551                pinned_run: Some(run.id.clone()),
7552            });
7553            t.hold_machine(Some("not enough free space to start a run".into()));
7554            let mut unchanged = t.clone();
7555            unchanged
7556                .edit("title changed".into(), unchanged.instruction.clone())
7557                .unwrap();
7558            unchanged.release_operator(source, None);
7559            assert_eq!(
7560                unchanged
7561                    .resume_override
7562                    .as_ref()
7563                    .unwrap()
7564                    .pinned_run
7565                    .as_deref(),
7566                Some(run.id.as_str())
7567            );
7568            assert!(!compatible_run_instruction(&run, &unchanged));
7569            assert!(may_resume_run(&run, &unchanged));
7570
7571            t.edit(
7572                "approved recovery".into(),
7573                "Reuse measured PR head B; fix Clippy; review".into(),
7574            )
7575            .unwrap();
7576            assert!(t.resume_override.is_none());
7577            t.release_operator(source, None);
7578            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7579            assert!(reloaded.resume_override.is_none());
7580            assert!(!may_resume_run(&run, &reloaded));
7581            let unfinished =
7582                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7583                    .filter(|_| may_resume_run(&run, &reloaded));
7584            assert_eq!(
7585                choose_starter(None, false, unfinished.as_deref()),
7586                Starter::Start
7587            );
7588            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7589            assert_eq!(
7590                reloaded.resumption_history[0].question_id.as_deref(),
7591                Some("resume-question")
7592            );
7593
7594            // A revision already persisted with the old approval/pin is also
7595            // invalidated when the new operator release is recorded.
7596            unchanged.instruction = "Reuse measured PR head B".into();
7597            unchanged.hold_machine(Some("disk hold".into()));
7598            unchanged.release_operator(source, None);
7599            assert!(unchanged.resume_override.is_none());
7600            assert!(!may_resume_run(&run, &unchanged));
7601        }
7602    }
7603
7604    #[test]
7605    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7606        let mut t = task();
7607        let mut run = run_state(RunStatus::Blocked);
7608        t.review_of = Some("approved-head".into());
7609        t.instruction =
7610            "Review the branch `approved-head` (review-only: no implementation, no judging)."
7611                .into();
7612        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();
7613        run.reviewed_commits = Some(vec!["Commit log".into()]);
7614        t.start(run.id.clone());
7615        t.hold_machine(Some("interrupted review".into()));
7616        t.release_operator("cli", None);
7617        assert!(
7618            compatible_run_instruction(&run, &t),
7619            "legacy explicit review remains resumable"
7620        );
7621        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7622            .filter(|_| compatible_run_instruction(&run, &t));
7623        assert_eq!(
7624            choose_starter(None, false, unfinished.as_deref()),
7625            Starter::Resume(run.id.clone())
7626        );
7627        run.task_instruction = Some(t.instruction.clone());
7628        assert!(compatible_run_instruction(&run, &t));
7629        let reloaded: RunState =
7630            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7631        assert!(compatible_run_instruction(&reloaded, &t));
7632        t.edit(
7633            "new approved head".into(),
7634            "Reuse measured PR head B".into(),
7635        )
7636        .unwrap();
7637        assert!(!compatible_run_instruction(&run, &t));
7638
7639        // Legacy recovery reviews retain the task criteria ahead of the log.
7640        t.review_of = None;
7641        t.instruction = "Fix Clippy on approved head".into();
7642        run.task_instruction = None;
7643        run.instruction = format!(
7644            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7645            t.instruction
7646        );
7647        assert!(compatible_run_instruction(&run, &t));
7648        t.instruction.push('\n');
7649        assert!(
7650            compatible_run_instruction(&run, &t),
7651            "legacy generated review trimmed the original criteria"
7652        );
7653        t.hold_for_handover(Some("approved-head".into()), "refused".into());
7654        assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
7655        t.edit("new plan".into(), "Reuse measured PR head B".into())
7656            .unwrap();
7657        assert!(review_branch_for(&t, Some(&run)).is_none());
7658        assert!(!compatible_run_instruction(&run, &t));
7659        t.review_branch = Some("approved-head".into());
7660        t.review_instruction = None;
7661        assert!(
7662            review_branch_for(&t, Some(&run)).is_none(),
7663            "legacy retained candidate cannot replace a revised approved head"
7664        );
7665    }
7666
7667    #[test]
7668    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7669        let home = crate::run::test_home();
7670        crate::run::pin_test_home();
7671        let dir = tempfile::tempdir().unwrap();
7672        let queue = Queue::at(dir.path().join("queue"));
7673        for resume in [true, false] {
7674            let state = run_state(RunStatus::Blocked);
7675            let mut t = task();
7676            t.start(state.id.clone());
7677            let action = if resume {
7678                ask::ChoiceAction::Resume {
7679                    run: state.id.clone(),
7680                }
7681            } else {
7682                ask::ChoiceAction::Requeue
7683            };
7684            let mut q = action_question(&state.id, action);
7685            q.status = ask::QuestionStatus::Open;
7686            q.answer = None;
7687            q.answered_at = None;
7688            t.fail("run stopped with a question", 3);
7689            hold_if_runnable(&queue, &mut t);
7690            assert!(t.operator_decided_at.is_none());
7691            assert!(t.operator_held());
7692            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7693            let expected = if resume {
7694                ActionDecision::Resume(state.id.clone())
7695            } else {
7696                ActionDecision::Requeue
7697            };
7698            assert_eq!(
7699                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7700                expected
7701            );
7702            t.hold_manual(Some("later explicit hold".into()));
7703            assert_eq!(
7704                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7705                ActionDecision::Stale
7706            );
7707        }
7708    }
7709
7710    #[test]
7711    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7712        let mut t = task();
7713        t.answers.push(crate::queue::AnsweredQuestion {
7714            question: "Inspect the remote?".into(),
7715            answer: "Inspect then wait".into(),
7716        });
7717        let old = instruction_for(&t);
7718        assert!(compatible_instruction(&old, &t));
7719        t.instruction = "Reuse approved PR head and review".into();
7720        t.release_operator("cli", None);
7721        assert!(!compatible_instruction(&old, &t));
7722        let approved = instruction_for(&t);
7723        assert!(approved.contains("waiting premises are superseded"));
7724        assert!(compatible_instruction(&approved, &t));
7725        assert_eq!(resumed_instruction(&approved, &t), approved);
7726        t.release_operator("web", None);
7727        assert!(compatible_instruction(&approved, &t));
7728        assert_eq!(t.resumption_history.len(), 1);
7729        t.start("run".into());
7730        assert!(instruction_for(&t).contains("Explicit operator resumption"));
7731    }
7732
7733    /// A run that stopped on an infrastructure wait asked no agent anything:
7734    /// the task is held by the machine under a `[resource]` reason (resumable,
7735    /// re-checked by triage), and the attempt it started is given back.
7736    #[test]
7737    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7738        let mut state = RunState::new(
7739            PathBuf::from("/repo"),
7740            "main".into(),
7741            "base".into(),
7742            "task".into(),
7743            Config::default(),
7744        );
7745        state.status = RunStatus::Landing;
7746        state.parked = true;
7747        state.pr_pushed_head = Some("head".into());
7748        state.land_unrelated = Some(
7749            serde_json::from_value(serde_json::json!({
7750                "head": "head", "question": "ci-question",
7751                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7752            }))
7753            .unwrap(),
7754        );
7755        let mut t = task();
7756        t.start(state.id.clone());
7757        let verdict = Verdict {
7758            status: RunStatus::Landing,
7759            left_pr: true,
7760            quota_hit: false,
7761            parked: true,
7762            no_viable_candidates: false,
7763        };
7764        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7765        assert_eq!(t.attempts, 0);
7766        assert_eq!(t.status, TaskStatus::Held);
7767        assert!(!t.operator_held());
7768        assert!(
7769            t.hold_reason
7770                .as_deref()
7771                .unwrap()
7772                .starts_with("[ci-unrelated]")
7773        );
7774        // A second settlement must not refund an earlier task attempt.
7775        t.attempts = 1;
7776        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7777        assert_eq!(t.attempts, 1);
7778        assert_eq!(t.passes.len(), 1);
7779        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7780        state.pr_pushed_head = Some("new-head".into());
7781        state.parked = false;
7782        state.status = RunStatus::Blocked;
7783        let stale = Verdict {
7784            status: RunStatus::Blocked,
7785            parked: false,
7786            ..verdict
7787        };
7788        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7789        assert_eq!(t.attempts, 1);
7790        // A new execution pass can refund its own newly charged attempt.
7791        state.begin_pass();
7792        state.begin_pass();
7793        state.status = RunStatus::Landing;
7794        state.parked = true;
7795        state.pr_pushed_head = Some("head".into());
7796        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7797        assert_eq!(t.attempts, 0);
7798        assert_eq!(t.passes.len(), 2);
7799    }
7800
7801    #[test]
7802    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7803        let mut state = run_state(RunStatus::Failed);
7804        state
7805            .quota
7806            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7807        state.begin_pass();
7808        let mut t = task();
7809        t.start(state.id.clone());
7810        reclaim(&mut t, Some(state), 2, "en");
7811        assert_eq!(t.attempts, 1);
7812    }
7813
7814    #[test]
7815    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7816        let mut state = run_state(RunStatus::Blocked);
7817        let losses: Vec<_> = ["alpha", "beta"]
7818            .into_iter()
7819            .enumerate()
7820            .map(|(i, agent)| {
7821                QuotaLoss::from_report(
7822                    format!("advisor-{i}"),
7823                    "advise",
7824                    Some(&crate::agent::Quota {
7825                        cause: crate::agent::QuotaCause::Authentication,
7826                        agent: agent.to_owned(),
7827                        reset: None,
7828                    }),
7829                )
7830            })
7831            .collect();
7832        crate::graph::block_machine_outage(&mut state, "advise", &losses);
7833        state.quota = losses;
7834        let mut t = task();
7835        t.start(state.id.clone());
7836        let verdict = Verdict {
7837            status: state.status,
7838            left_pr: false,
7839            quota_hit: true,
7840            parked: false,
7841            no_viable_candidates: true,
7842        };
7843        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7844        assert_eq!(t.attempts, 0);
7845        assert_eq!(t.status, TaskStatus::Held);
7846        assert!(!t.operator_held());
7847        let reason = t.hold_reason.as_deref().unwrap();
7848        assert!(reason.starts_with("[authentication]"));
7849        assert!(
7850            reason.contains("alpha")
7851                && reason.contains("beta")
7852                && reason.contains("re-authenticate")
7853        );
7854        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7855        // Orphan recovery uses the same settlement and cannot spend an attempt.
7856        let mut orphan = task();
7857        orphan.start(state.id.clone());
7858        reclaim(&mut orphan, Some(state), 2, "en");
7859        assert_eq!(orphan.attempts, 0);
7860        assert_eq!(orphan.status, TaskStatus::Held);
7861    }
7862
7863    #[test]
7864    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7865        let mut state = RunState::new(
7866            PathBuf::from("/repo"),
7867            "main".to_owned(),
7868            "abc1234".to_owned(),
7869            "task".to_owned(),
7870            Config::default(),
7871        );
7872        state.status = RunStatus::Blocked;
7873        state.resource_block = Some(crate::run::ResourceBlock {
7874            cause: crate::run::ResourceBlockCause::Other,
7875            node: "graft".to_owned(),
7876            kind: "shared build cache".to_owned(),
7877            detail: "timed out".to_owned(),
7878            at: jiff::Timestamp::now(),
7879        });
7880        let mut t = task();
7881        t.start("20260902-000000-aaaa".to_owned());
7882        assert_eq!(t.attempts, 1);
7883        let verdict = Verdict {
7884            status: RunStatus::Blocked,
7885            left_pr: false,
7886            quota_hit: false,
7887            parked: false,
7888            no_viable_candidates: false,
7889        };
7890        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7891        assert_eq!(t.status, TaskStatus::Held);
7892        assert_eq!(t.attempts, 0, "the attempt is refunded");
7893        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7894        assert!(
7895            !t.operator_held(),
7896            "a machine hold, released without a human"
7897        );
7898
7899        let mut selected = task();
7900        selected.start("20260902-000000-cccc".into());
7901        selected.replacement = Some(crate::merge_decision::Replacement {
7902            question: "fixture".into(),
7903            run: "earlier".into(),
7904            pr: "https://example.invalid/pr/1".into(),
7905            agent: "selected".into(),
7906            context: "fixture".into(),
7907        });
7908        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7909        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7910        assert_eq!(selected.attempts, 0);
7911        assert!(
7912            !selected.operator_held(),
7913            "a selected agent also retains a machine resource hold"
7914        );
7915        assert!(
7916            selected
7917                .hold_reason
7918                .as_deref()
7919                .unwrap()
7920                .starts_with("[resource] ")
7921        );
7922
7923        // A park request outranks it: still the operator's doing.
7924        let mut p = task();
7925        p.start("20260902-000000-bbbb".to_owned());
7926        settle_and_diagnose(
7927            &mut p,
7928            Verdict {
7929                parked: true,
7930                ..verdict
7931            },
7932            "parked",
7933            2,
7934            &state,
7935        );
7936        assert_eq!(p.status, TaskStatus::Parked);
7937        assert_eq!(
7938            p.attempts, 0,
7939            "parking refunds once rather than also settling the resource hold"
7940        );
7941    }
7942
7943    #[test]
7944    fn record_failure_notice_links_the_task() {
7945        let dir = tempfile::tempdir().unwrap();
7946        // A regular file where the queue directory should be makes every
7947        // `put` fail, on every platform and whoever runs the test.
7948        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7949        let queue = Queue::at(dir.path().join("queue"));
7950        let mut t = interrupt_task("rec-fail-1");
7951        record(&queue, &mut t);
7952
7953        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7954        assert_eq!(found.len(), 1);
7955        assert_eq!(found[0].key, "loop:record");
7956        assert_eq!(
7957            found[0].link,
7958            Some(Link::Task {
7959                id: "rec-fail-1".to_owned()
7960            })
7961        );
7962    }
7963
7964    /// A runnable task marked to interrupt, with an id fixed for assertions
7965    /// rather than the random one [`Task::new`] mints.
7966    fn interrupt_task(id: &str) -> Task {
7967        let mut t = task();
7968        t.id = id.to_owned();
7969        t.interrupt = true;
7970        t
7971    }
7972
7973    /// An ordinary runnable task with an id fixed for assertions.
7974    fn task_with_id(id: &str) -> Task {
7975        let mut t = task();
7976        t.id = id.to_owned();
7977        t
7978    }
7979
7980    /// A runnable task marked `--urgent`, with an id fixed for assertions.
7981    fn urgent_task(id: &str) -> Task {
7982        let mut t = task();
7983        t.id = id.to_owned();
7984        t.urgent = true;
7985        t
7986    }
7987
7988    #[test]
7989    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7990        let dir = tempfile::tempdir().unwrap();
7991        let queue = Queue::at(dir.path().join("queue"));
7992        let mut parked = task_with_id("parked");
7993        parked.start("run".into());
7994        parked.park("upgrade");
7995        parked.record_pass_at(
7996            "run",
7997            0,
7998            Some(Timestamp::now()),
7999            1,
8000            Some(crate::run::ParkCause::Upgrade {
8001                from: "old".into(),
8002                to: None,
8003            }),
8004        );
8005        let mut fresh = task_with_id("fresh");
8006        fresh.priority = 100;
8007        let mut urgent_task = urgent_task("urgent");
8008        for t in [&mut parked, &mut fresh, &mut urgent_task] {
8009            queue.put(t).unwrap();
8010        }
8011        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8012        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8013        let candidates = runnable(&queue);
8014        assert_eq!(candidates[0].id, parked.id);
8015        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
8016        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
8017        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
8018        drop(first);
8019        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
8020        let next = runnable(&queue)
8021            .into_iter()
8022            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
8023            .unwrap();
8024        assert_eq!(next.task.id, fresh.id);
8025        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
8026        drop(claimed_elsewhere);
8027        drop(next);
8028        assert!(matches!(
8029            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
8030            Err(SkipReason::CoolingDown)
8031        ));
8032    }
8033
8034    #[test]
8035    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
8036        let dir = tempfile::tempdir().unwrap();
8037        let queue = Queue::at(dir.path().join("queue"));
8038        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8039        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8040        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
8041        let mut first = task();
8042        queue.put(&mut first).unwrap();
8043        let stale_plain = queue.get(&first.id).unwrap();
8044        first.set_urgent(true).unwrap();
8045        queue.put(&mut first).unwrap();
8046        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
8047        let mut second = urgent_task("second");
8048        queue.put(&mut second).unwrap();
8049        assert!(matches!(
8050            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
8051            Err(SkipReason::UrgentCapacity)
8052        ));
8053        drop(queue.claim(&second.id).unwrap());
8054        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
8055        drop(dispatched);
8056        let stale_urgent = queue.get(&first.id).unwrap();
8057        first.set_urgent(false).unwrap();
8058        queue.put(&mut first).unwrap();
8059        assert!(matches!(
8060            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
8061            Err(SkipReason::OrdinaryCapacity)
8062        ));
8063        assert_eq!(urgent.available_permits(), 1);
8064        drop(queue.claim(&first.id).unwrap());
8065        drop(occupied);
8066    }
8067
8068    #[test]
8069    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
8070        let dir = tempfile::tempdir().unwrap();
8071        let queue = Queue::at(dir.path().join("queue"));
8072        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8073        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8074        let mut t = task();
8075        queue.put(&mut t).unwrap();
8076        for enabled in [true, false] {
8077            let stale = queue.get(&t.id).unwrap();
8078            t.set_urgent(enabled).unwrap();
8079            queue.put(&mut t).unwrap();
8080            assert_ne!(stale.urgent, enabled);
8081            let DispatchClaim {
8082                task: fresh,
8083                claim,
8084                permit,
8085            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
8086            assert_eq!(fresh.urgent, enabled);
8087            assert_eq!(ordinary.available_permits(), usize::from(enabled));
8088            assert_eq!(urgent.available_permits(), usize::from(!enabled));
8089            assert!(queue.claim(&t.id).is_err());
8090            assert_eq!(fresh.attempts, stale.attempts);
8091            drop((claim, permit));
8092            assert_eq!(ordinary.available_permits(), 1);
8093            assert_eq!(urgent.available_permits(), 1);
8094        }
8095        t.set_urgent(true).unwrap();
8096        queue.put(&mut t).unwrap();
8097        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
8098        assert!(matches!(
8099            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8100            Err(SkipReason::UrgentCapacity)
8101        ));
8102        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
8103        drop(queue.claim(&t.id).unwrap());
8104        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
8105        drop(occupied);
8106        assert!(matches!(
8107            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
8108            Err(SkipReason::CoolingDown)
8109        ));
8110        drop(queue.claim(&t.id).unwrap());
8111        let held = queue.claim(&t.id).unwrap();
8112        assert!(matches!(
8113            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8114            Err(SkipReason::ClaimUnavailable)
8115        ));
8116        drop(held);
8117        t.status = TaskStatus::Held;
8118        queue.put(&mut t).unwrap();
8119        assert!(matches!(
8120            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8121            Err(SkipReason::NoLongerRunnable)
8122        ));
8123        drop(queue.claim(&t.id).unwrap());
8124        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
8125        assert!(matches!(
8126            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8127            Err(SkipReason::RereadFailed)
8128        ));
8129        drop(queue.claim(&t.id).unwrap());
8130        assert_eq!(urgent.available_permits(), 1);
8131    }
8132
8133    /// The land-resume exemption wins outright, whether or not the candidate
8134    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
8135    /// queue behind anything" guarantee cannot be weaker just because the
8136    /// same task was also filed with `--urgent`.
8137    #[test]
8138    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
8139        assert_eq!(permit_kind(true, false), PermitKind::None);
8140        assert_eq!(permit_kind(true, true), PermitKind::None);
8141    }
8142
8143    /// The one property this whole feature exists for: `--urgent` draws from
8144    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
8145    /// ordinary candidate draws from the ordinary pool exactly as before,
8146    /// untouched by the urgent slot's existence.
8147    #[test]
8148    fn permit_kind_separates_urgent_from_ordinary() {
8149        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
8150        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
8151    }
8152
8153    /// The exact wiring `attempt` runs before minting anything: a config's
8154    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
8155    /// Free space is injected rather than asked of the real disk - the point
8156    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
8157    /// is deterministic on every machine this test runs on, never dependent
8158    /// on how full the CI runner's own disk happens to be.
8159    #[test]
8160    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
8161        let cfg = Config::default();
8162        let repo = Path::new("/any/repo/path");
8163
8164        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
8165            .expect("must hold below the threshold");
8166        assert!(reason.contains("1024"), "{reason}");
8167        assert!(
8168            reason.contains(&cfg.disk.min_free_bytes.to_string()),
8169            "{reason}"
8170        );
8171
8172        assert_eq!(
8173            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
8174            None,
8175            "exactly at the floor is open"
8176        );
8177        assert_eq!(
8178            disk_gate_with(
8179                repo,
8180                &cfg,
8181                PathBuf::new,
8182                |_| Ok(cfg.disk.min_free_bytes + 1)
8183            ),
8184            None,
8185            "comfortably above the floor is open"
8186        );
8187    }
8188
8189    #[test]
8190    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
8191        let dir = tempfile::tempdir().unwrap();
8192        let repo = dir.path().join("repo");
8193        let cache = dir.path().join("cache");
8194        let worktrees = dir.path().join("worktrees");
8195        for path in [&repo, &cache, &worktrees] {
8196            std::fs::create_dir(path).unwrap();
8197        }
8198        let mut cfg = Config::default();
8199        cfg.graph.worktree_root = Some(worktrees.clone());
8200        cfg.verify.gate = vec![format!(
8201            "CARGO_TARGET_DIR='{}' cargo build",
8202            cache.display()
8203        )];
8204        for blocked in [&cache, &worktrees] {
8205            for unmeasured in [false, true] {
8206                assert!(
8207                    disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
8208                        if path == blocked {
8209                            if unmeasured {
8210                                Err(anyhow::anyhow!("measurement failed"))
8211                            } else {
8212                                Ok(0)
8213                            }
8214                        } else {
8215                            Ok(u64::MAX)
8216                        }
8217                    })
8218                    .is_some(),
8219                    "a blocked secondary output volume must close admission"
8220                );
8221            }
8222        }
8223        assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
8224    }
8225
8226    #[test]
8227    fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
8228        let dir = tempfile::tempdir().unwrap();
8229        let repo = dir.path().join("repo");
8230        let cache = dir.path().join("cache");
8231        let home_parent = dir.path().join("run-volume");
8232        let home = home_parent.join("new-home");
8233        for path in [&repo, &cache, &home_parent] {
8234            std::fs::create_dir(path).unwrap();
8235        }
8236        let mut cfg = Config::default();
8237        cfg.graph.worktree_root = Some(repo.clone());
8238        cfg.verify.gate = vec![format!(
8239            "CARGO_TARGET_DIR='{}' cargo build",
8240            cache.display()
8241        )];
8242        cfg.verify.build_cache = BuildCache::Isolated;
8243        let denied = |blocked: &Path| {
8244            disk_gate_with(
8245                &repo,
8246                &cfg,
8247                || home.clone(),
8248                |path| Ok(if path == blocked { 0 } else { u64::MAX }),
8249            )
8250            .is_some()
8251        };
8252        assert!(!denied(&cache));
8253        assert!(denied(&home_parent));
8254    }
8255
8256    #[test]
8257    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
8258        let mut cfg = Config::default();
8259        cfg.disk.min_free_bytes = 0;
8260        let repo = Path::new("/any/repo/path");
8261        assert_eq!(
8262            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
8263            None,
8264            "a zero floor never measures at all"
8265        );
8266    }
8267
8268    #[test]
8269    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
8270        let cfg = Config::default();
8271        let repo = Path::new("/any/repo/path");
8272        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
8273            Err(anyhow::anyhow!("no df on this box"))
8274        })
8275        .expect("a measurement failure must close the gate, not open it");
8276        assert!(reason.contains("could not measure"), "{reason}");
8277    }
8278
8279    #[test]
8280    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
8281        let ordinary = task();
8282        let next = advance_interrupt(
8283            Interrupt::Idle,
8284            std::slice::from_ref(&ordinary.id),
8285            std::slice::from_ref(&ordinary),
8286        );
8287        assert_eq!(next, Interrupt::Idle);
8288    }
8289
8290    #[test]
8291    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
8292        // Nothing to interrupt - this is just an ordinary candidate, and the
8293        // loop's normal dispatch will pick it up like any other.
8294        let marked = interrupt_task("marked");
8295        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8296        assert_eq!(next, Interrupt::Idle);
8297    }
8298
8299    #[test]
8300    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
8301        let marked = interrupt_task("marked");
8302        let next = advance_interrupt(
8303            Interrupt::Idle,
8304            &["running".to_owned()],
8305            std::slice::from_ref(&marked),
8306        );
8307        assert_eq!(
8308            next,
8309            Interrupt::Parking {
8310                parked: vec!["running".to_owned()],
8311                interrupt_task: "marked".to_owned(),
8312            }
8313        );
8314    }
8315
8316    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
8317    /// one run can be in flight when a task becomes runnable and marked.
8318    /// Parking all of them would mean `Resuming` later has more than one id
8319    /// to release back to ordinary dispatch, which cannot be made safe
8320    /// against that same setting's own extra concurrency slots letting two
8321    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
8322    /// The simplification the task's own constraints ask for: do not begin
8323    /// a sequence at all until the herd settles back to exactly one.
8324    #[test]
8325    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
8326        let marked = interrupt_task("marked");
8327
8328        let two = advance_interrupt(
8329            Interrupt::Idle,
8330            &["a".to_owned(), "b".to_owned()],
8331            std::slice::from_ref(&marked),
8332        );
8333        assert_eq!(two, Interrupt::Idle);
8334
8335        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8336        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
8337    }
8338
8339    #[test]
8340    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
8341        let state = Interrupt::Parking {
8342            parked: vec!["running".to_owned()],
8343            interrupt_task: "marked".to_owned(),
8344        };
8345        // Still in flight: no change.
8346        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
8347        assert_eq!(still_going, state);
8348
8349        // Left flight, but the interrupt task has not been dispatched yet on
8350        // this tick - stays `Parking` so `interrupt_gate` can let it through,
8351        // as long as it is still runnable.
8352        let stopped_but_not_yet_dispatched =
8353            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
8354        assert_eq!(stopped_but_not_yet_dispatched, state);
8355
8356        // Left flight, and the interrupt task is now in flight itself.
8357        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
8358        assert_eq!(
8359            dispatched,
8360            Interrupt::Running {
8361                parked: vec!["running".to_owned()],
8362                interrupt_task: "marked".to_owned(),
8363            }
8364        );
8365    }
8366
8367    #[test]
8368    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
8369        let state = Interrupt::Running {
8370            parked: vec!["running".to_owned()],
8371            interrupt_task: "marked".to_owned(),
8372        };
8373        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
8374        assert_eq!(still_running, state);
8375
8376        // Whatever it ended as - merged, failed, held - is not this
8377        // function's concern: leaving flight is the only trigger, driven
8378        // straight off the same in-flight list `poll` already reaps. It does
8379        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
8380        // why that would let an unrelated task start ahead of, or alongside,
8381        // the guaranteed resume.
8382        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
8383        assert_eq!(
8384            ended,
8385            Interrupt::Resuming {
8386                parked: vec!["running".to_owned()]
8387            }
8388        );
8389    }
8390
8391    #[test]
8392    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
8393        let state = Interrupt::Resuming {
8394            parked: vec!["running".to_owned()],
8395        };
8396        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
8397        assert_eq!(still_waiting, state);
8398
8399        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
8400        assert_eq!(dispatched, Interrupt::Idle);
8401    }
8402
8403    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
8404    /// or otherwise moved on by an operator with no claim standing in the
8405    /// way - must not wedge the sequence (and so the whole loop's dispatch,
8406    /// via `interrupt_gate`) waiting forever for a dispatch that can never
8407    /// come. The parked run still gets its resume.
8408    #[test]
8409    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
8410    {
8411        let state = Interrupt::Parking {
8412            parked: vec!["running".to_owned()],
8413            interrupt_task: "marked".to_owned(),
8414        };
8415        // `marked` has been held/blocked/deleted since the sequence began:
8416        // it no longer appears in `runnable` at all.
8417        let next = advance_interrupt(state, &[], &[]);
8418        assert_eq!(
8419            next,
8420            Interrupt::Resuming {
8421                parked: vec!["running".to_owned()]
8422            },
8423            "abandoning the interrupt must not abandon the resume it owes"
8424        );
8425    }
8426
8427    /// The same abandonment, one step later: `Resuming` itself must not wait
8428    /// forever for a parked task that has since become unrunnable.
8429    #[test]
8430    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
8431        let state = Interrupt::Resuming {
8432            parked: vec!["running".to_owned()],
8433        };
8434        let next = advance_interrupt(state, &[], &[]);
8435        assert_eq!(
8436            next,
8437            Interrupt::Idle,
8438            "nothing is left to wait for; the loop must not stay wedged"
8439        );
8440    }
8441
8442    #[test]
8443    fn disabled_by_config_the_sequence_can_never_leave_idle() {
8444        let marked = interrupt_task("marked");
8445        let next = advance_interrupt_tick(
8446            false,
8447            Interrupt::Idle,
8448            &["running".to_owned()],
8449            std::slice::from_ref(&marked),
8450        );
8451        assert_eq!(
8452            next,
8453            Interrupt::Idle,
8454            "an unmarked, unconfigured daemon must behave exactly as before"
8455        );
8456    }
8457
8458    #[test]
8459    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
8460        let state = Interrupt::Parking {
8461            parked: vec!["running".to_owned()],
8462            interrupt_task: "marked".to_owned(),
8463        };
8464        let candidates = vec![interrupt_task("marked"), task()];
8465        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8466        assert!(
8467            allowed.is_empty(),
8468            "nothing may dispatch - not even the interrupt task itself - \
8469             until the parked run has actually stopped"
8470        );
8471    }
8472
8473    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
8474    /// grow a special case for it: an urgent candidate that is not the
8475    /// interrupt task withholds exactly like an ordinary one for as long as
8476    /// the parked run it is racing has not actually left flight. A version
8477    /// of this feature once bypassed the gate for urgent candidates, on the
8478    /// theory that a genuinely separate concurrency lane could not collide
8479    /// with 75dd's own; it could, and did - the bypassed task dispatched
8480    /// alongside a run 75dd's own state machine had only *asked* to park,
8481    /// not yet confirmed gone, which is exactly the second run
8482    /// `Interrupt::Parking`'s own doc says must never happen. There is no
8483    /// tick during Parking/Running/Resuming where letting an extra
8484    /// candidate through is safe, urgent or not - the parked run may still
8485    /// be genuinely mid-call.
8486    #[test]
8487    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
8488        for state in [
8489            Interrupt::Parking {
8490                parked: vec!["running".to_owned()],
8491                interrupt_task: "marked".to_owned(),
8492            },
8493            Interrupt::Running {
8494                parked: vec!["running".to_owned()],
8495                interrupt_task: "marked".to_owned(),
8496            },
8497            Interrupt::Resuming {
8498                parked: vec!["running".to_owned()],
8499            },
8500        ] {
8501            let candidates = vec![
8502                interrupt_task("marked"),
8503                urgent_task("hot"),
8504                task_with_id("ordinary"),
8505            ];
8506            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8507            assert!(
8508                !allowed.iter().any(|t| t.id == "hot"),
8509                "an urgent candidate must wait out the same gate as anything \
8510                 else while the run it would run alongside has not actually \
8511                 left flight, for state {state:?}: {allowed:?}"
8512            );
8513        }
8514    }
8515
8516    /// The one case where marking a task `--urgent` and `interrupt` at once
8517    /// is not redundant: once the interrupt sequence's own guaranteed
8518    /// resume/dispatch actually admits the task, it is unaffected by also
8519    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
8520    /// never on the urgent flag.
8521    #[test]
8522    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
8523        let state = Interrupt::Resuming {
8524            parked: vec!["hot".to_owned()],
8525        };
8526        let candidates = vec![urgent_task("hot"), task()];
8527        let allowed = interrupt_gate(&state, &[], candidates);
8528        assert_eq!(
8529            allowed.iter().filter(|t| t.id == "hot").count(),
8530            1,
8531            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
8532        );
8533    }
8534
8535    #[test]
8536    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
8537        let state = Interrupt::Parking {
8538            parked: vec!["running".to_owned()],
8539            interrupt_task: "marked".to_owned(),
8540        };
8541        let other = task();
8542        let candidates = vec![interrupt_task("marked"), other.clone()];
8543        let allowed = interrupt_gate(&state, &[], candidates);
8544        assert_eq!(allowed.len(), 1);
8545        assert_eq!(allowed[0].id, "marked");
8546    }
8547
8548    #[test]
8549    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
8550        let state = Interrupt::Running {
8551            parked: vec!["running".to_owned()],
8552            interrupt_task: "marked".to_owned(),
8553        };
8554        let candidates = vec![task(), task()];
8555        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
8556        assert!(allowed.is_empty());
8557    }
8558
8559    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
8560    /// sequence began (only reachable above the default
8561    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
8562    /// never both in the same tick, which is what "exactly one resume, no
8563    /// simultaneous run" actually requires structurally rather than by
8564    /// coincidence of how many ordinary slots happen to be free.
8565    #[test]
8566    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
8567        let state = Interrupt::Resuming {
8568            parked: vec!["a".to_owned(), "c".to_owned()],
8569        };
8570        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
8571        let allowed = interrupt_gate(&state, &[], candidates);
8572        assert_eq!(
8573            allowed.len(),
8574            1,
8575            "at most one candidate may be offered while resuming: {allowed:?}"
8576        );
8577        assert_eq!(allowed[0].id, "a");
8578    }
8579
8580    #[test]
8581    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
8582        let state = Interrupt::Resuming {
8583            parked: vec!["a".to_owned()],
8584        };
8585        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
8586        assert!(allowed.is_empty());
8587    }
8588
8589    /// The invariant the completion criteria ask for by name: across a whole
8590    /// simulated sequence, there is never a tick where the gate would let
8591    /// through both the parked run's resume and the interrupt task, and
8592    /// exactly one candidate resumes the instant the interrupt task's run
8593    /// ends - never zero, never more than one.
8594    #[test]
8595    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8596        let running = task(); // id: whatever `Task::new` minted
8597        let marked = interrupt_task("marked");
8598
8599        let mut state = Interrupt::Idle;
8600        // Tick 1: `running` is in flight, `marked` becomes runnable.
8601        let in_flight = vec![running.id.clone()];
8602        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8603        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8604        assert!(gated.is_empty(), "still waiting on `running` to park");
8605
8606        // Tick 2: `running` parked and left flight; nothing dispatched yet.
8607        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8608        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8609        assert_eq!(
8610            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8611            vec!["marked"],
8612            "only the interrupt task may be offered to the dispatcher now"
8613        );
8614
8615        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
8616        state = advance_interrupt_tick(
8617            true,
8618            state,
8619            &["marked".to_owned()],
8620            std::slice::from_ref(&running),
8621        );
8622        let gated = interrupt_gate(
8623            &state,
8624            &["marked".to_owned()],
8625            vec![marked.clone(), running.clone()],
8626        );
8627        assert!(
8628            gated.is_empty(),
8629            "the parked run must not be offered back while the interrupt \
8630             task is still running"
8631        );
8632
8633        // Tick 4: `marked`'s run reached a terminal status and left flight.
8634        // A higher-priority ordinary task `other` is also runnable now - it
8635        // must not be let through instead of, or alongside, `running`.
8636        let other = task_with_id("other");
8637        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8638        assert_eq!(
8639            state,
8640            Interrupt::Resuming {
8641                parked: vec![running.id.clone()]
8642            }
8643        );
8644        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8645        assert_eq!(
8646            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8647            vec![running.id.as_str()],
8648            "exactly the parked run resumes - not the unrelated task, even \
8649             though it was offered first"
8650        );
8651
8652        // Tick 5: `running` is now in flight (dispatched from tick 4's
8653        // gate). Only now does the sequence end and ordinary dispatch fully
8654        // resume.
8655        state = advance_interrupt_tick(
8656            true,
8657            state,
8658            std::slice::from_ref(&running.id),
8659            std::slice::from_ref(&other),
8660        );
8661        assert_eq!(state, Interrupt::Idle);
8662        let gated = interrupt_gate(
8663            &state,
8664            std::slice::from_ref(&running.id),
8665            vec![other.clone()],
8666        );
8667        assert_eq!(
8668            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8669            vec![other.id.as_str()],
8670            "ordinary dispatch is unrestricted again"
8671        );
8672    }
8673
8674    #[test]
8675    fn every_run_status_settles_the_task_it_came_from() {
8676        // run status, resulting task status, attempts still standing after one
8677        let table = [
8678            (RunStatus::Merged, TaskStatus::Done, 1),
8679            (RunStatus::Ready, TaskStatus::Done, 1),
8680            (RunStatus::Stalled, TaskStatus::Failed, 0),
8681            (RunStatus::Blocked, TaskStatus::Failed, 1),
8682            (RunStatus::Failed, TaskStatus::Failed, 1),
8683            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8684            (RunStatus::Prep, TaskStatus::Failed, 1),
8685            (RunStatus::Implementing, TaskStatus::Failed, 1),
8686            (RunStatus::Judging, TaskStatus::Failed, 1),
8687            (RunStatus::Deliberating, TaskStatus::Failed, 1),
8688            (RunStatus::Voting, TaskStatus::Failed, 1),
8689            (RunStatus::Reviewing, TaskStatus::Failed, 1),
8690            (RunStatus::Gating, TaskStatus::Failed, 1),
8691        ];
8692        for (run, want, attempts) in table {
8693            let mut t = task();
8694            t.start("20260902-000000-aaaa".to_owned());
8695            settle(
8696                &mut t,
8697                Verdict {
8698                    status: run,
8699                    left_pr: false,
8700                    parked: false,
8701                    quota_hit: matches!(run, RunStatus::Stalled),
8702                    no_viable_candidates: false,
8703                },
8704                "why",
8705                2,
8706            );
8707            assert_eq!(t.status, want, "task status after {}", label(run));
8708            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8709        }
8710    }
8711
8712    #[test]
8713    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8714        let mut stalled = task();
8715        stalled.start("20260902-000000-aaaa".to_owned());
8716        settle(
8717            &mut stalled,
8718            Verdict {
8719                status: RunStatus::Stalled,
8720                left_pr: false,
8721                parked: false,
8722                quota_hit: true,
8723                no_viable_candidates: false,
8724            },
8725            "quota",
8726            1,
8727        );
8728        assert_eq!(stalled.attempts, 0);
8729        assert!(
8730            stalled.status.runnable(),
8731            "a machine problem must leave the task in line"
8732        );
8733
8734        let mut blocked = task();
8735        blocked.start("20260902-000000-aaaa".to_owned());
8736        settle(
8737            &mut blocked,
8738            Verdict {
8739                status: RunStatus::Blocked,
8740                left_pr: false,
8741                parked: false,
8742                quota_hit: false,
8743                no_viable_candidates: false,
8744            },
8745            "findings open",
8746            1,
8747        );
8748        assert_eq!(blocked.attempts, 1);
8749        assert_eq!(
8750            blocked.status,
8751            TaskStatus::Held,
8752            "the last attempt hands the task to a human"
8753        );
8754    }
8755
8756    #[test]
8757    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8758        // Attempts to spare: without the pull request this task would go
8759        // straight back in line and run the whole competition again.
8760        let mut delivered = task();
8761        delivered.start("20260903-080619-01c2".to_owned());
8762        settle(
8763            &mut delivered,
8764            Verdict {
8765                status: RunStatus::Blocked,
8766                left_pr: true,
8767                parked: false,
8768                quota_hit: false,
8769                no_viable_candidates: false,
8770            },
8771            "no check status",
8772            4,
8773        );
8774        assert_eq!(
8775            delivered.status,
8776            TaskStatus::Held,
8777            "a pull request waiting on CI or a person is not a retryable failure"
8778        );
8779        assert!(
8780            !delivered.status.runnable(),
8781            "the loop must not pick this task up again"
8782        );
8783        assert_eq!(
8784            delivered.last_error.as_deref(),
8785            Some("no check status"),
8786            "the operator needs to be told what the gate was waiting for"
8787        );
8788
8789        // The same status without a pull request is a plain failure, and with
8790        // attempts left it is retried.
8791        let mut empty_handed = task();
8792        empty_handed.start("20260903-080619-01c2".to_owned());
8793        settle(
8794            &mut empty_handed,
8795            Verdict {
8796                status: RunStatus::Blocked,
8797                left_pr: false,
8798                parked: false,
8799                quota_hit: false,
8800                no_viable_candidates: false,
8801            },
8802            "findings open",
8803            4,
8804        );
8805        assert_eq!(empty_handed.status, TaskStatus::Failed);
8806        assert!(empty_handed.status.runnable());
8807    }
8808
8809    #[test]
8810    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8811        // Every candidate agreed, with evidence, that nothing belonged in the
8812        // worktree. That is not a confirmed success to close automatically -
8813        // a human still has to check the claim - and it is not an ordinary
8814        // failure either, so this settles exactly like a pull request nobody
8815        // merged yet: `Held`, same as `Blocked` with a PR.
8816        let mut noop = task();
8817        noop.start("20260912-131304-391f".to_owned());
8818        settle(
8819            &mut noop,
8820            Verdict {
8821                status: RunStatus::VerifiedNoop,
8822                left_pr: false,
8823                parked: false,
8824                quota_hit: false,
8825                no_viable_candidates: true,
8826            },
8827            "candidate A: already fixed by b32cfc4, on main",
8828            4,
8829        );
8830        assert_eq!(
8831            noop.status,
8832            TaskStatus::Held,
8833            "an unverified claim is a request for a human, not a failure"
8834        );
8835        assert!(
8836            !noop.status.runnable(),
8837            "the loop must not requeue this on the same unverified claim"
8838        );
8839        // `Task::release` resets attempts to zero the moment a human looks at
8840        // the evidence and lets it run again, so it does not matter here
8841        // whether the one attempt already spent stays spent - what matters is
8842        // that nothing retries this task unattended in the meantime.
8843        assert_eq!(noop.attempts, 1);
8844    }
8845
8846    #[test]
8847    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8848        // Parking is the operator asking for the process back - to replace the
8849        // binary, most of all. The run's work is intact on disk, so this is
8850        // not a failed attempt, and charging for it would mean a few upgrades
8851        // could exhaust a budget meant for agents that misbehaved.
8852        let mut parked = task();
8853        parked.start("20260903-183634-2d98".to_owned());
8854        settle(
8855            &mut parked,
8856            Verdict {
8857                status: RunStatus::Implementing,
8858                left_pr: false,
8859                quota_hit: false,
8860                parked: true,
8861                no_viable_candidates: false,
8862            },
8863            "parked after `implementing`",
8864            2,
8865        );
8866        assert_eq!(parked.attempts, 0, "a park is refunded");
8867        assert!(
8868            parked.status.runnable(),
8869            "and the task stays in line so the next loop resumes its run"
8870        );
8871        assert_eq!(parked.status, TaskStatus::Parked);
8872        assert_eq!(
8873            parked.park_reason.as_deref(),
8874            Some("parked after `implementing`"),
8875            "the card says where it stopped"
8876        );
8877        assert_eq!(parked.last_error, None, "nothing failed");
8878
8879        // Without the park flag the same non-terminal status is what it always
8880        // was: `execute` returning mid-flight, which is a bug and spends an
8881        // attempt so a task cannot loop on it forever.
8882        let mut broken = task();
8883        broken.start("20260903-183634-2d98".to_owned());
8884        settle(
8885            &mut broken,
8886            Verdict {
8887                status: RunStatus::Implementing,
8888                left_pr: false,
8889                quota_hit: false,
8890                parked: false,
8891                no_viable_candidates: false,
8892            },
8893            "returned mid-flight",
8894            2,
8895        );
8896        assert_eq!(broken.attempts, 1);
8897    }
8898
8899    #[test]
8900    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
8901        // Run e633: quorum lost because two judges answered with the wrong
8902        // JSON shape, `quota: []`. Refunding that takes the bound off the
8903        // retry loop, and each retry pays for a fresh hour-long implement
8904        // wave before it can fail the same way.
8905        let mut flaky = task();
8906        flaky.start("20260903-123023-e633".to_owned());
8907        settle(
8908            &mut flaky,
8909            Verdict {
8910                status: RunStatus::Stalled,
8911                left_pr: false,
8912                parked: false,
8913                quota_hit: false,
8914                no_viable_candidates: false,
8915            },
8916            "verdict rests on 1 of 3 judges",
8917            2,
8918        );
8919        assert_eq!(
8920            flaky.attempts, 1,
8921            "flakiness spends an attempt, so `max_attempts` still bounds it"
8922        );
8923        assert!(flaky.status.runnable(), "and it is still worth retrying");
8924
8925        // The same status, lost to a rate limit, is the machine's fault.
8926        let mut limited = task();
8927        limited.start("20260903-123023-e633".to_owned());
8928        settle(
8929            &mut limited,
8930            Verdict {
8931                status: RunStatus::Stalled,
8932                left_pr: false,
8933                parked: false,
8934                quota_hit: true,
8935                no_viable_candidates: false,
8936            },
8937            "judge-2, judge-3 out of quota",
8938            2,
8939        );
8940        assert_eq!(limited.attempts, 0, "a quota window is refunded");
8941        assert!(limited.status.runnable());
8942
8943        // And the bound really binds: a task that keeps stalling on flakiness
8944        // reaches a human instead of running the roster forever.
8945        let mut worn = task();
8946        for _ in 0..2 {
8947            worn.release();
8948        }
8949        worn.start("20260903-123023-e633".to_owned());
8950        worn.attempts = 2;
8951        settle(
8952            &mut worn,
8953            Verdict {
8954                status: RunStatus::Stalled,
8955                left_pr: false,
8956                parked: false,
8957                quota_hit: false,
8958                no_viable_candidates: false,
8959            },
8960            "no quorum again",
8961            2,
8962        );
8963        assert_eq!(worn.status, TaskStatus::Held);
8964        assert!(!worn.status.runnable());
8965    }
8966
8967    #[test]
8968    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8969        // The implement wave loses every seat to the same rate limit and
8970        // `after_implement` bails with nothing viable, which surfaces as
8971        // `Failed` rather than `Stalled`. That is the same machine fact the
8972        // `Stalled`-quota row already refunds, and must be refunded the same
8973        // way, or a quota outage quietly holds every task it touches instead
8974        // of leaving them in line for the reset.
8975        let mut wiped_out = task();
8976        wiped_out.start("20260907-025000-a1b2".to_owned());
8977        settle(
8978            &mut wiped_out,
8979            Verdict {
8980                status: RunStatus::Failed,
8981                left_pr: false,
8982                parked: false,
8983                quota_hit: true,
8984                no_viable_candidates: true,
8985            },
8986            "no candidate produced a change; nothing to judge",
8987            2,
8988        );
8989        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8990        assert!(
8991            wiped_out.status.runnable(),
8992            "a machine problem must leave the task in line"
8993        );
8994
8995        // This is the exemption that must stay narrow: a candidate that did
8996        // produce a change, and then failed for some other reason, still
8997        // spends the attempt even though a seat elsewhere hit its quota.
8998        // Otherwise every ordinary failure that happens to share a run with
8999        // an unrelated rate limit would be refunded for free.
9000        let mut partial_progress = task();
9001        partial_progress.start("20260907-025500-c3d4".to_owned());
9002        settle(
9003            &mut partial_progress,
9004            Verdict {
9005                status: RunStatus::Failed,
9006                left_pr: false,
9007                parked: false,
9008                quota_hit: true,
9009                no_viable_candidates: false,
9010            },
9011            "gate failed on the winning candidate",
9012            2,
9013        );
9014        assert_eq!(
9015            partial_progress.attempts, 1,
9016            "a candidate that actually produced a change spends the attempt \
9017             even though some other seat hit its quota"
9018        );
9019        assert!(partial_progress.status.runnable());
9020    }
9021
9022    #[test]
9023    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
9024        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
9025        // disk, and that construction must reach the same conclusion as the
9026        // one `attempt` builds from a live run, or a crash at exactly the
9027        // wrong moment gives a recovered task a different policy than one a
9028        // daemon finished settling itself.
9029        let mut t = task();
9030        t.start("20260907-025000-a1b2".to_owned());
9031        let mut state = run_state(RunStatus::Failed);
9032        state.quota.push(QuotaLoss {
9033            cause: crate::agent::QuotaCause::UsageLimit,
9034            agent: String::new(),
9035            seat: "cand-a".to_owned(),
9036            node: "implement".to_owned(),
9037            at: Timestamp::now(),
9038            reset: None,
9039        });
9040        assert!(
9041            state.viable().is_empty(),
9042            "no candidate was added, so nothing is viable"
9043        );
9044        reclaim(&mut t, Some(state), 2, "en");
9045        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
9046        assert!(t.status.runnable());
9047    }
9048
9049    #[test]
9050    fn a_held_task_is_never_offered_to_the_loop() {
9051        let dir = tempfile::tempdir().unwrap();
9052        let queue = Queue::at(dir.path().to_path_buf());
9053        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
9054            let mut t = task();
9055            t.id = format!("2026090{n}-000000-000{n}");
9056            t.priority = priority;
9057            queue.put(&mut t).unwrap();
9058        }
9059        let mut held = task();
9060        held.id = "20260909-000000-9999".to_owned();
9061        held.priority = 99;
9062        held.hold_machine(None);
9063        queue.put(&mut held).unwrap();
9064
9065        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
9066        assert_eq!(order.len(), 3);
9067        assert!(!order.contains(&held.id));
9068        assert_eq!(
9069            order.first().cloned(),
9070            queue.next_runnable().map(|t| t.id),
9071            "the loop's first candidate is exactly what the queue offers"
9072        );
9073        assert_eq!(
9074            order,
9075            vec![
9076                "20260902-000000-0002".to_owned(),
9077                "20260903-000000-0003".to_owned(),
9078                "20260901-000000-0001".to_owned(),
9079            ],
9080            "priority first, then oldest, so nothing starves"
9081        );
9082    }
9083
9084    #[test]
9085    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
9086        let dir = tempfile::tempdir().unwrap();
9087        let queue = Queue::at(dir.path().to_path_buf());
9088        let mut old = task();
9089        old.id = "20260101-000000-old0".to_owned();
9090        queue.put(&mut old).unwrap();
9091        let mut fresh = task();
9092        fresh.id = "20260101-000000-new0".to_owned();
9093        queue.put(&mut fresh).unwrap();
9094
9095        // No parseable pid at all, so age is the only signal there is to
9096        // check - unlike a real `Queue::claim`, which always names a real,
9097        // and therefore alive, pid this test cannot fake as dead.
9098        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
9099        std::thread::sleep(Duration::from_millis(60));
9100        let live = queue.claim(&fresh.id).unwrap();
9101
9102        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9103        assert_eq!(swept, vec![old.id.clone()]);
9104        assert!(
9105            queue.claim(&old.id).is_ok(),
9106            "an unparseable lock older than the threshold is swept"
9107        );
9108        assert!(
9109            queue.claim(&fresh.id).is_err(),
9110            "a live pid protects its lock regardless of age"
9111        );
9112        drop(live);
9113    }
9114
9115    #[test]
9116    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
9117        // A live worker's claim remains authoritative even beyond the sweep's
9118        // age limit. Sweeping it would permit a second competing attempt.
9119        let dir = tempfile::tempdir().unwrap();
9120        let queue = Queue::at(dir.path().to_path_buf());
9121        let mut t = task();
9122        t.id = "20260101-000000-live".to_owned();
9123        queue.put(&mut t).unwrap();
9124
9125        let claim = queue.claim(&t.id).unwrap();
9126        std::thread::sleep(Duration::from_millis(60));
9127
9128        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9129        assert!(
9130            swept.is_empty(),
9131            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
9132        );
9133        assert!(
9134            queue.claim(&t.id).is_err(),
9135            "the lock still protects its task"
9136        );
9137        drop(claim);
9138    }
9139
9140    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
9141    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
9142    fn injected_dead_pid() -> u32 {
9143        std::process::id().checked_add(1).unwrap_or(1)
9144    }
9145
9146    #[test]
9147    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
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-dead".to_owned();
9152        queue.put(&mut t).unwrap();
9153        let dead_pid = injected_dead_pid();
9154
9155        // Written directly rather than through `Queue::claim`, which would
9156        // stamp this test process's own very much alive pid and defeat the
9157        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
9158        // like moments after it died, not six hours later.
9159        std::fs::write(
9160            dir.path().join(format!("{}.lock", t.id)),
9161            dead_pid.to_string(),
9162        )
9163        .unwrap();
9164
9165        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9166            pid != dead_pid
9167        });
9168        assert_eq!(
9169            swept,
9170            vec![t.id.clone()],
9171            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
9172        );
9173        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
9174    }
9175
9176    #[test]
9177    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
9178        let dir = tempfile::tempdir().unwrap();
9179        let queue = Queue::at(dir.path().to_path_buf());
9180        let mut t = task();
9181        t.id = "20260101-000000-late".to_owned();
9182        queue.put(&mut t).unwrap();
9183        let dead_pid = injected_dead_pid();
9184
9185        // Tick one, standing in for the sweep `poll` already runs at
9186        // startup: nothing to find yet.
9187        assert!(
9188            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
9189            "nothing has claimed the task yet"
9190        );
9191
9192        // A second daemon claims the task and dies before it ever writes
9193        // `running`, well after this loop's own startup sweep already ran.
9194        std::fs::write(
9195            dir.path().join(format!("{}.lock", t.id)),
9196            dead_pid.to_string(),
9197        )
9198        .unwrap();
9199
9200        // Tick two, standing in for a poll long into this daemon's uptime:
9201        // the same function, called again, notices what only just appeared -
9202        // proving the sweep is not a one-shot startup check.
9203        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9204            pid != dead_pid
9205        });
9206        assert_eq!(swept, vec![t.id.clone()]);
9207    }
9208
9209    #[test]
9210    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
9211        // `reclaim_orphaned_running` looks up the task's last run, which
9212        // touches `run::home()`; the first call anywhere in this binary wins,
9213        // so this is a no-op if another test already pinned one, and either
9214        // way the run id below is never written under it.
9215        crate::run::pin_test_home();
9216        let dir = tempfile::tempdir().unwrap();
9217        let queue = Queue::at(dir.path().to_path_buf());
9218        let mut t = task();
9219        t.id = "20260101-000000-crsh".to_owned();
9220        t.status = TaskStatus::Running;
9221        t.attempts = 1;
9222        // No `run.json` behind this id: standing in for a run this test does
9223        // not need to make readable, since the point is the lock, not the
9224        // recovery table `reclaim` already has its own tests for.
9225        t.runs.push("20260904-000000-4043".to_owned());
9226        queue.put(&mut t).unwrap();
9227        let dead_pid = injected_dead_pid();
9228
9229        // The crashed daemon's own claim, naming a pid nothing on the
9230        // machine holds anymore.
9231        std::fs::write(
9232            dir.path().join(format!("{}.lock", t.id)),
9233            dead_pid.to_string(),
9234        )
9235        .unwrap();
9236
9237        // Before the lock is swept the task looks claimed, and
9238        // `reclaim_orphaned_running` must leave it alone - this is exactly
9239        // the bug: a `running` task stranded behind a dead daemon's lock,
9240        // invisible to the claim-as-proof check because the lock outlived
9241        // the process that wrote it.
9242        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
9243        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9244
9245        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9246            pid != dead_pid
9247        });
9248        assert_eq!(swept, vec![t.id.clone()]);
9249
9250        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9251        assert_eq!(reclaimed, vec![t.id.clone()]);
9252        let after = queue.get(&t.id).unwrap();
9253        assert_eq!(
9254            after.status,
9255            TaskStatus::Held,
9256            "no run.json to recover from, so a human is asked"
9257        );
9258        assert_eq!(
9259            after.runs,
9260            vec!["20260904-000000-4043".to_owned()],
9261            "the crashed run's id is kept as evidence, not discarded"
9262        );
9263    }
9264
9265    #[test]
9266    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
9267        let dir = tempfile::tempdir().unwrap();
9268        let queue = Queue::at(dir.path().to_path_buf());
9269        let mut t = task();
9270        t.id = "20260101-000000-unknown".to_owned();
9271        queue.put(&mut t).unwrap();
9272        let dead_pid = injected_dead_pid();
9273        std::fs::write(
9274            dir.path().join(format!("{}.lock", t.id)),
9275            dead_pid.to_string(),
9276        )
9277        .unwrap();
9278
9279        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
9280        assert!(swept.is_empty(), "an unknown pid must keep its lock");
9281        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
9282    }
9283
9284    fn run_state_in(status: RunStatus, language: &str) -> RunState {
9285        let mut s = run_state(status);
9286        s.config.graph.language = language.to_owned();
9287        s
9288    }
9289
9290    fn unstarted_verdict(status: RunStatus) -> Verdict {
9291        Verdict {
9292            status,
9293            left_pr: false,
9294            quota_hit: false,
9295            parked: false,
9296            no_viable_candidates: false,
9297        }
9298    }
9299
9300    #[test]
9301    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
9302        let mut t = task();
9303        t.attempts = 1;
9304        settle_in(
9305            &mut t,
9306            unstarted_verdict(RunStatus::AlreadyInBase),
9307            "already in main",
9308            1,
9309            phrases("en"),
9310            None,
9311        );
9312        assert_eq!(t.status, TaskStatus::Done);
9313        assert_eq!(t.attempts, 0);
9314    }
9315
9316    #[test]
9317    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
9318        let reason = |language: &str| {
9319            let mut t = task();
9320            settle_in(
9321                &mut t,
9322                unstarted_verdict(RunStatus::Judging),
9323                "boom",
9324                1,
9325                phrases(language),
9326                None,
9327            );
9328            t.last_error.or(t.hold_reason).unwrap_or_default()
9329        };
9330        assert!(
9331            reason("en").starts_with("the graph stopped at `"),
9332            "{}",
9333            reason("en")
9334        );
9335        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
9336        assert!(reason("日本語").contains("boom"));
9337        assert_eq!(reason("fr"), reason("en"));
9338    }
9339
9340    #[test]
9341    fn describe_follows_the_run_language_and_keeps_the_run_id() {
9342        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
9343        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
9344        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
9345        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
9346        assert!(ja.contains("[run "), "{ja}");
9347        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
9348        assert!(ended.starts_with("run 終了: "), "{ended}");
9349        let mut de = run_state_in(RunStatus::Failed, "de");
9350        let mut en = run_state_in(RunStatus::Failed, "en");
9351        de.id = "same".to_owned();
9352        en.id = "same".to_owned();
9353        assert_eq!(describe(&de), describe(&en));
9354    }
9355
9356    #[test]
9357    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
9358        use crate::handover::Refused;
9359        let cases = [
9360            Refused::Foreign {
9361                branch: "b".into(),
9362                path: "/w/x".into(),
9363                why: "made by hand".into(),
9364            },
9365            Refused::Unsafe {
9366                branch: "b".into(),
9367                path: "/w/x".into(),
9368                why: "its worktree has uncommitted changes (a.rs)".into(),
9369            },
9370            Refused::ReleaseFailed {
9371                branch: "b".into(),
9372                path: "/w/x".into(),
9373                run: "ab12".into(),
9374            },
9375        ];
9376        for r in &cases {
9377            let en = (phrases("en").handover_refused)(r);
9378            assert_eq!(en, r.to_string());
9379            let ja = (phrases("ja").handover_refused)(r);
9380            assert!(
9381                !ja.contains("is checked out") && !ja.contains("try again"),
9382                "{ja}"
9383            );
9384            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
9385            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
9386                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
9387            }
9388        }
9389        assert!(phrases("en").handover_hint.contains("release the task"));
9390        assert!(phrases("ja").handover_hint.contains("解放"));
9391    }
9392
9393    #[test]
9394    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
9395        let build = |lang: &str| {
9396            let mut s = run_state_in(RunStatus::Blocked, lang);
9397            s.id = "same".to_owned();
9398            s.config.graph.review_rounds = 3;
9399            let mut r = review_round(3);
9400            r.expected = 3;
9401            r.answered = 1;
9402            s.reviews.push(r);
9403            s.event(
9404                "review",
9405                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
9406            );
9407            s
9408        };
9409        let en = describe(&build("en"));
9410        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
9411        let ja = describe(&build("ja"));
9412        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
9413        assert!(!ja.contains("never answered"), "{ja}");
9414        assert!(ja.contains("[run "), "{ja}");
9415
9416        // An incomplete panel whose verification failed is a different stop:
9417        // the real event must survive in ja too.
9418        let mut failed = build("ja");
9419        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
9420            command: "cargo test".to_owned(),
9421            code: Some(1),
9422            output_tail: String::new(),
9423            duration_ms: 0,
9424            resource_blocked: false,
9425            ..Default::default()
9426        });
9427        failed.event("review", "stopped; e2e failed: cargo test");
9428        let ja = describe(&failed);
9429        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
9430        assert!(!ja.contains("席のレビュアー"), "{ja}");
9431    }
9432
9433    #[test]
9434    fn refusals_and_recovery_prose_follow_the_language() {
9435        let home = crate::run::test_home();
9436        let t = held_task_with("r1");
9437        let q = action_question(
9438            "r1",
9439            ask::ChoiceAction::Resume {
9440                run: "r1".to_owned(),
9441            },
9442        );
9443        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
9444            ActionDecision::Refuse(s) => s,
9445            other => panic!("{other:?}"),
9446        };
9447        assert!(refuse(phrases("en")).contains("could not be read: gone"));
9448        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
9449        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
9450
9451        let mut held = task();
9452        reclaim(&mut held, None, 2, "ja");
9453        assert!(held.hold_reason.unwrap().contains("保留にしました"));
9454        let mut held = task();
9455        reclaim(&mut held, None, 2, "xx");
9456        assert!(held.hold_reason.unwrap().contains("held for a human"));
9457    }
9458
9459    fn run_state(status: RunStatus) -> RunState {
9460        let mut state = RunState::new(
9461            PathBuf::from("/repo"),
9462            "main".to_owned(),
9463            "abc1234def".to_owned(),
9464            "add retries".to_owned(),
9465            Config::default(),
9466        );
9467        state.status = status;
9468        state
9469    }
9470
9471    #[test]
9472    fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
9473        crate::run::pin_test_home();
9474        let dir = tempfile::tempdir().unwrap();
9475        let mut state = run_state(RunStatus::Blocked);
9476        state.id = "20260101-000000-audit".into();
9477        state.save_under(dir.path()).unwrap();
9478        let mut t = task();
9479        t.start(state.id.clone());
9480        // The final state is newer than disk, as when a worker settles its
9481        // in-memory outcome or recovery is passed an already loaded run.
9482        state.status = RunStatus::Ready;
9483        settle_and_diagnose(
9484            &mut t,
9485            unstarted_verdict(RunStatus::Ready),
9486            "Verified local delivery",
9487            2,
9488            &state,
9489        );
9490        let completion = t.completion_history.last().unwrap();
9491        assert_eq!(completion.actor, CompletionActor::DaemonSettle);
9492        assert_eq!(completion.prior_status, TaskStatus::Running);
9493        assert_eq!(
9494            completion.reason.as_deref(),
9495            Some("Verified local delivery")
9496        );
9497        let snapshot = completion.run.as_ref().unwrap();
9498        assert_eq!(snapshot.id, state.id);
9499        assert_eq!(snapshot.status, Some(RunStatus::Ready));
9500        assert_eq!(
9501            RunState::load_under(&state.id, dir.path()).unwrap().status,
9502            RunStatus::Blocked,
9503            "settlement records the actual outcome without rewriting run history"
9504        );
9505    }
9506
9507    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
9508        Candidate {
9509            index: 0,
9510            label,
9511            agent: "claude".to_owned(),
9512            branch: format!("magi/x/{label}"),
9513            worktree: PathBuf::from("/repo"),
9514            summary: summary.to_owned(),
9515            stat: String::new(),
9516            files: 0,
9517            commits: usize::from(!empty),
9518            empty,
9519            failed: failed.map(str::to_owned),
9520            verified_noop: None,
9521            duration_ms: 0,
9522            folded: false,
9523        }
9524    }
9525
9526    #[test]
9527    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
9528        let mut state = run_state(RunStatus::Blocked);
9529        state.gate = vec![
9530            CommandOutcome {
9531                command: "cargo make check".to_owned(),
9532                code: Some(0),
9533                output_tail: "ok".to_owned(),
9534                duration_ms: 0,
9535                resource_blocked: false,
9536                ..Default::default()
9537            },
9538            CommandOutcome {
9539                command: "cargo test".to_owned(),
9540                code: Some(101),
9541                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
9542                duration_ms: 0,
9543                resource_blocked: false,
9544                ..Default::default()
9545            },
9546        ];
9547        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
9548        assert!(d.contains("cargo test"), "{d}");
9549        assert!(
9550            !d.contains("cargo make check"),
9551            "a passing check is not a diagnostic: {d}"
9552        );
9553        assert!(d.contains("assertion failed"), "{d}");
9554    }
9555
9556    #[test]
9557    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
9558        let mut state = run_state(RunStatus::Blocked);
9559        state.event(
9560            "land",
9561            "stopped: the fixer produced no commit while 2 check(s) were failing \
9562             (build, lint); stopping instead of looping on an unchanged tree",
9563        );
9564        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
9565        assert!(d.contains("build"), "{d}");
9566        assert!(d.contains("lint"), "{d}");
9567        assert!(d.contains("fixer produced no commit"), "{d}");
9568    }
9569
9570    #[test]
9571    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
9572        // `describe`'s output becomes `Task::last_error` verbatim, and the
9573        // phone renders that in the same alarm-styled box an ordinary
9574        // failure gets. A bare `verified_noop` there would read exactly like
9575        // the failure this status exists to be told apart from.
9576        let state = run_state(RunStatus::VerifiedNoop);
9577        let d = describe(&state);
9578        assert!(
9579            d.contains("agent-verified no-op"),
9580            "expected the display label, not the wire spelling: {d}"
9581        );
9582        assert!(!d.contains("verified_noop"), "{d}");
9583    }
9584
9585    #[test]
9586    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
9587        let mut state = run_state(RunStatus::Failed);
9588        state.gate.push(crate::run::CommandOutcome {
9589            command: "cargo test".into(),
9590            code: Some(101),
9591            output_tail: format!(
9592                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
9593                "  41: 0x1234 - backtrace frame\n".repeat(10000)
9594            ),
9595            duration_ms: 1,
9596            resource_blocked: false,
9597            ..Default::default()
9598        });
9599        let d = diagnostic(&state).unwrap();
9600        assert!(d.contains("panicked at widget.rs:12"), "{d}");
9601        assert!(d.contains("assertion failed: widget missing"));
9602        assert!(d.contains("widget log"));
9603    }
9604
9605    #[test]
9606    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
9607        // The whole point of the feature: a run held as "no candidate produced
9608        // a change" can mean the implementer actually finished the task and
9609        // only left a clean local tree behind - see AGENTS.md on this exact
9610        // failure mode. The diagnostic has to carry what the agent actually
9611        // said, not just the fact that nothing was there to judge.
9612        let mut state = run_state(RunStatus::Failed);
9613        state.candidates = vec![candidate(
9614            'A',
9615            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
9616            true,
9617            None,
9618        )];
9619        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
9620        assert!(d.contains("candidate A"), "{d}");
9621        assert!(d.contains("tagged v1.2.3"), "{d}");
9622    }
9623
9624    #[test]
9625    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
9626        let mut state = run_state(RunStatus::Failed);
9627        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
9628        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
9629        assert!(d.contains("candidate A"), "{d}");
9630        assert!(d.contains("agent timed out"), "{d}");
9631    }
9632
9633    #[test]
9634    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9635        // A viable candidate existed, the gate never ran, and nothing land
9636        // said matches - `Task::last_error` is left to explain this one alone.
9637        let mut state = run_state(RunStatus::Failed);
9638        state.candidates = vec![candidate('A', "did the work", false, None)];
9639        assert!(diagnostic(&state).is_none());
9640    }
9641
9642    #[test]
9643    fn diagnostic_is_bounded_however_much_a_run_printed() {
9644        let mut state = run_state(RunStatus::Blocked);
9645        state.gate = vec![
9646            CommandOutcome {
9647                command: "cargo test".to_owned(),
9648                code: Some(101),
9649                output_tail: "x".repeat(50_000),
9650                duration_ms: 0,
9651                resource_blocked: false,
9652                ..Default::default()
9653            },
9654            CommandOutcome {
9655                command: "cargo clippy".to_owned(),
9656                code: Some(1),
9657                output_tail: "y".repeat(50_000),
9658                duration_ms: 0,
9659                resource_blocked: false,
9660                ..Default::default()
9661            },
9662        ];
9663        state.candidates = vec![
9664            candidate('A', &"z".repeat(50_000), true, None),
9665            candidate('B', &"w".repeat(50_000), true, None),
9666        ];
9667        let d = diagnostic(&state).expect("plenty here to diagnose");
9668        assert!(
9669            d.len() <= DIAGNOSTIC_MAX,
9670            "diagnostic grew to {} bytes, unbounded",
9671            d.len()
9672        );
9673    }
9674
9675    #[test]
9676    fn selected_delivery_guards_survive_recovery_failure_accounting() {
9677        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9678            let mut t = task();
9679            let mut state = run_state(status);
9680            t.pr_recovery = Some(crate::pr_recovery::Selection {
9681                url: "url".into(),
9682                branch: format!("magi/task-{}", t.id),
9683                head: "a".repeat(40),
9684                source_head: None,
9685                source_run: None,
9686                source_proof: None,
9687                disposition: Some(crate::pr_recovery::Disposition::Land),
9688                instruction: t.instruction.clone(),
9689                approved_at: Timestamp::now(),
9690            });
9691            state.pr_recovery = t.pr_recovery.clone();
9692            t.start(state.id.clone());
9693            settle_and_diagnose(
9694                &mut t,
9695                Verdict {
9696                    status,
9697                    left_pr: false,
9698                    quota_hit: false,
9699                    parked: false,
9700                    no_viable_candidates: false,
9701                },
9702                "delivery stopped",
9703                5,
9704                &state,
9705            );
9706            assert_eq!(t.status, TaskStatus::Held);
9707            let reason = t.hold_reason.as_deref().unwrap();
9708            if status == RunStatus::Ready {
9709                assert!(reason.contains("Selected PR delivery is incomplete"));
9710                assert!(t.recovery_budget.is_none());
9711            } else {
9712                assert!(reason.contains("Selected recovery stopped"));
9713                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9714            }
9715            assert!(t.pr_recovery.is_some());
9716        }
9717    }
9718
9719    #[test]
9720    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9721        let mut state = run_state(RunStatus::Voting);
9722        state.base_sync = Some(crate::run::BaseSync {
9723            tip: "base-tip".into(),
9724            behind: 3,
9725            attempts: 4,
9726            conflict: Some("base stopped".into()),
9727            already_in: None,
9728        });
9729        state.record_base_sync_stop("candidate-head");
9730        let mut t = task();
9731        t.start(state.id.clone());
9732        let verdict = Verdict {
9733            status: RunStatus::Blocked,
9734            left_pr: false,
9735            quota_hit: false,
9736            parked: false,
9737            no_viable_candidates: false,
9738        };
9739        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9740        assert_eq!(
9741            t.status,
9742            TaskStatus::Held,
9743            "unspent task attempts cannot start another competition"
9744        );
9745        let at = t.held_at;
9746        let cause = t.hold_notice_cause.clone();
9747        state.begin_pass();
9748        t.release_operator("test-resume", None);
9749        t.start(state.id.clone());
9750        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9751        assert_eq!(t.status, TaskStatus::Held);
9752        assert_eq!(t.held_at, at);
9753        assert_eq!(t.hold_notice_cause, cause);
9754    }
9755
9756    #[test]
9757    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9758        let mut state = run_state(RunStatus::Blocked);
9759        state.gate = vec![CommandOutcome {
9760            command: "cargo test".to_owned(),
9761            code: Some(101),
9762            output_tail: "assertion failed".to_owned(),
9763            duration_ms: 0,
9764            resource_blocked: false,
9765            ..Default::default()
9766        }];
9767        let verdict = Verdict {
9768            status: RunStatus::Blocked,
9769            left_pr: false,
9770            quota_hit: false,
9771            parked: false,
9772            no_viable_candidates: false,
9773        };
9774
9775        // Attempt one of two still has a retry coming: no diagnostic yet, the
9776        // task is going to run again and this run's evidence would go stale.
9777        let mut t = task();
9778        t.start("run-1".to_owned());
9779        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9780        assert_eq!(t.status, TaskStatus::Failed);
9781        assert!(t.diagnostic.is_none());
9782
9783        // Attempt two exhausts the budget: now it is held, and the
9784        // diagnostic is what `magi task show` has to say more than one line.
9785        t.start("run-2".to_owned());
9786        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9787        assert_eq!(t.status, TaskStatus::Held);
9788        let d = t.diagnostic.expect("a held task must carry its diagnostic");
9789        assert!(d.contains("cargo test"), "{d}");
9790    }
9791
9792    #[test]
9793    fn a_held_task_names_the_open_question_it_is_waiting_on() {
9794        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
9795        // `magi ask` question settled Held with `hold_reason: null`, so the
9796        // notification said nothing actionable. `note_open_question` should
9797        // append the question id to whatever `handed_off` already wrote.
9798        crate::run::pin_test_home();
9799        let home = crate::run::home();
9800        let state = run_state(RunStatus::VerifiedNoop);
9801        let mut q = ask::Question::new(
9802            state.id.clone(),
9803            "implement".to_owned(),
9804            "impl-A".to_owned(),
9805            "is this really a no-op?".to_owned(),
9806            String::new(),
9807            Vec::new(),
9808        );
9809        Questions::at(home.join("questions")).put(&mut q).unwrap();
9810
9811        let verdict = Verdict {
9812            status: RunStatus::VerifiedNoop,
9813            left_pr: false,
9814            quota_hit: false,
9815            parked: false,
9816            no_viable_candidates: false,
9817        };
9818        let mut t = task();
9819        t.start(state.id.clone());
9820        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9821
9822        assert_eq!(t.status, TaskStatus::Held);
9823        let reason = t.hold_reason.expect("a held task must record why");
9824        assert!(
9825            reason.starts_with("run ended agent-verified no-op"),
9826            "the original settle reason must survive unchanged: {reason}"
9827        );
9828        assert!(
9829            reason.contains(q.short()),
9830            "the open question's id must be named so the notice is actionable: {reason}"
9831        );
9832    }
9833
9834    #[test]
9835    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9836        crate::run::pin_test_home();
9837        let state = run_state(RunStatus::VerifiedNoop);
9838
9839        let verdict = Verdict {
9840            status: RunStatus::VerifiedNoop,
9841            left_pr: false,
9842            quota_hit: false,
9843            parked: false,
9844            no_viable_candidates: false,
9845        };
9846        let mut t = task();
9847        t.start(state.id.clone());
9848        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9849
9850        assert_eq!(t.status, TaskStatus::Held);
9851        assert_eq!(
9852            t.hold_reason.as_deref(),
9853            Some("run ended agent-verified no-op"),
9854            "nothing to append when the question was already answered or never asked"
9855        );
9856    }
9857
9858    #[test]
9859    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
9860        crate::run::pin_test_home();
9861        let mut first = run_state(RunStatus::Blocked);
9862        first.id = "20260101-000000-sup1".to_owned();
9863        first.save().unwrap();
9864        let mut second = run_state(RunStatus::Merged);
9865        second.id = "20260101-000000-sup2".to_owned();
9866        second.save().unwrap();
9867
9868        let mut t = task();
9869        t.runs = vec![first.id.clone(), second.id.clone()];
9870        t.status = TaskStatus::Done;
9871
9872        supersede_prior_runs(&t, &crate::run::home());
9873
9874        assert_eq!(
9875            RunState::load(&first.id).unwrap().status,
9876            RunStatus::Superseded,
9877            "the first attempt's Blocked no longer needs anyone's attention"
9878        );
9879        assert_eq!(
9880            RunState::load(&second.id).unwrap().status,
9881            RunStatus::Merged,
9882            "the run that actually succeeded is left exactly as it was"
9883        );
9884    }
9885
9886    #[test]
9887    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
9888        // `is_working_on` alone only proves a *daemon* claim; a `magi run
9889        // --resume` invoked by hand outside the daemon never touches
9890        // `daemon.json` at all, so it would look identical to a genuinely
9891        // idle run without also consulting `RunState::liveness`, which reads
9892        // this run's own recorded `driver_pid` instead.
9893        crate::run::pin_test_home();
9894        let mut first = run_state(RunStatus::Blocked);
9895        first.id = "20260101-000000-sup9".to_owned();
9896        // This test process's own pid: guaranteed alive without needing a
9897        // real second process or daemon.
9898        first.driver_pid = Some(std::process::id());
9899        first.driver_started_at = Some(
9900            crate::proc::process_started_at(std::process::id())
9901                .expect("this test process's own start time must be queryable"),
9902        );
9903        first.save().unwrap();
9904        let mut second = run_state(RunStatus::Merged);
9905        second.id = "20260101-000000-supa".to_owned();
9906        second.save().unwrap();
9907
9908        let mut t = task();
9909        t.runs = vec![first.id.clone(), second.id.clone()];
9910        t.status = TaskStatus::Done;
9911
9912        supersede_prior_runs(&t, &crate::run::home());
9913
9914        assert_eq!(
9915            RunState::load(&first.id).unwrap().status,
9916            RunStatus::Blocked,
9917            "a live driver_pid means something is still actually working this run, \
9918             even though no daemon claims it - rewriting under it would just be \
9919             undone the next time that process saves"
9920        );
9921    }
9922
9923    #[test]
9924    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
9925        // The first resweep must skip a still-live attempt exactly like
9926        // `supersede_prior_runs` itself does; a later resweep, once that
9927        // process is no longer actually driving it, is what closes the gap
9928        // `supersede_prior_runs` alone leaves - a task only ever reaches
9929        // `Done` once, so nothing else would ever look at this run again.
9930        let dir = tempfile::tempdir().unwrap();
9931        let home = dir.path().to_path_buf();
9932        let queue = Queue::at(dir.path().join("queue"));
9933
9934        let mut first = run_state(RunStatus::Blocked);
9935        first.id = "20260101-000000-supd".to_owned();
9936        first.driver_pid = Some(std::process::id());
9937        first.driver_started_at = Some(
9938            crate::proc::process_started_at(std::process::id())
9939                .expect("this test process's own start time must be queryable"),
9940        );
9941        first.save_under(&home).unwrap();
9942        let mut second = run_state(RunStatus::Merged);
9943        second.id = "20260101-000000-supe".to_owned();
9944        second.save_under(&home).unwrap();
9945
9946        let mut t = task();
9947        t.runs = vec![first.id.clone(), second.id.clone()];
9948        t.status = TaskStatus::Done;
9949        queue.put(&mut t).unwrap();
9950
9951        resweep_superseded_attempts(&queue, &home);
9952        assert_eq!(
9953            RunState::load_under(&first.id, &home).unwrap().status,
9954            RunStatus::Blocked,
9955            "still live on the first pass, so still untouched"
9956        );
9957
9958        // Stand in for the manual process no longer being the one driving
9959        // this run: same pid (this test process really is still alive), but
9960        // an identity marker that no longer matches it - see
9961        // `RunState::liveness`'s own doc for why a mismatched
9962        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
9963        let mut stale = RunState::load_under(&first.id, &home).unwrap();
9964        stale.driver_started_at = Some("1".to_owned());
9965        stale.save_under(&home).unwrap();
9966
9967        resweep_superseded_attempts(&queue, &home);
9968        assert_eq!(
9969            RunState::load_under(&first.id, &home).unwrap().status,
9970            RunStatus::Superseded,
9971            "the second pass catches up what the first one correctly skipped"
9972        );
9973    }
9974
9975    #[test]
9976    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
9977        crate::run::pin_test_home();
9978        let mut first = run_state(RunStatus::Blocked);
9979        first.id = "20260101-000000-sup3".to_owned();
9980        first.save().unwrap();
9981        let mut second = run_state(RunStatus::Blocked);
9982        second.id = "20260101-000000-sup4".to_owned();
9983        second.save().unwrap();
9984
9985        let mut t = task();
9986        t.runs = vec![first.id.clone(), second.id.clone()];
9987        // Still retrying: nothing about this task's story is settled yet, so
9988        // neither Blocked run may be relabelled, even though a later attempt
9989        // already exists.
9990        t.status = TaskStatus::Failed;
9991
9992        supersede_prior_runs(&t, &crate::run::home());
9993
9994        assert_eq!(
9995            RunState::load(&first.id).unwrap().status,
9996            RunStatus::Blocked
9997        );
9998        assert_eq!(
9999            RunState::load(&second.id).unwrap().status,
10000            RunStatus::Blocked
10001        );
10002    }
10003
10004    #[test]
10005    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
10006        // `magi task done` (or the API's equivalent) can close a task with no
10007        // run of its own ever having succeeded - there is nothing here that
10008        // counts as "the attempt that finished it", so nothing is rewritten.
10009        crate::run::pin_test_home();
10010        let mut first = run_state(RunStatus::Blocked);
10011        first.id = "20260101-000000-sup5".to_owned();
10012        first.save().unwrap();
10013
10014        let mut t = task();
10015        t.runs = vec![first.id.clone()];
10016        t.status = TaskStatus::Done;
10017
10018        supersede_prior_runs(&t, &crate::run::home());
10019
10020        assert_eq!(
10021            RunState::load(&first.id).unwrap().status,
10022            RunStatus::Blocked,
10023            "a single-attempt task has no earlier run to supersede"
10024        );
10025    }
10026
10027    #[test]
10028    fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
10029        for status in [
10030            RunStatus::Blocked,
10031            RunStatus::Stalled,
10032            RunStatus::Failed,
10033            RunStatus::Ready,
10034            RunStatus::Merged,
10035        ] {
10036            let dir = tempfile::tempdir().unwrap();
10037            let home = dir.path();
10038            let mut first = run_state(RunStatus::Blocked);
10039            first.id = "20260101-000000-supb".to_owned();
10040            first.save_under(home).unwrap();
10041            let mut second = run_state(status);
10042            second.id = "20260101-000000-supc".to_owned();
10043            second.save_under(home).unwrap();
10044
10045            let mut t = task();
10046            t.runs = vec![first.id.clone(), second.id.clone()];
10047            t.hold_manual(Some("Unmerged work remains".into()));
10048            let mut context = CompletionContext::new(
10049                CompletionActor::Cli,
10050                Some("Discard the unmerged attempts".into()),
10051                home,
10052                &t,
10053            );
10054            context.discard = true;
10055            t.succeed(context);
10056            assert_eq!(t.completion_history.len(), 1);
10057
10058            supersede_prior_runs(&t, home);
10059
10060            assert_eq!(
10061                RunState::load_under(&first.id, home).unwrap().status,
10062                RunStatus::Blocked,
10063                "an audited manual close is not proof the earlier work landed"
10064            );
10065            assert_eq!(
10066                RunState::load_under(&second.id, home).unwrap().status,
10067                status,
10068                "the latest attempt retains its actual outcome"
10069            );
10070        }
10071    }
10072
10073    #[test]
10074    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
10075        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
10076        // to look" - `Failed` and `VerifiedNoop` are already their own
10077        // terminal answers and must not be relabelled into a third one.
10078        crate::run::pin_test_home();
10079        let mut failed = run_state(RunStatus::Failed);
10080        failed.id = "20260101-000000-sup6".to_owned();
10081        failed.save().unwrap();
10082        let mut noop = run_state(RunStatus::VerifiedNoop);
10083        noop.id = "20260101-000000-sup7".to_owned();
10084        noop.save().unwrap();
10085        let mut winner = run_state(RunStatus::Ready);
10086        winner.id = "20260101-000000-sup8".to_owned();
10087        winner.save().unwrap();
10088
10089        let mut t = task();
10090        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
10091        t.status = TaskStatus::Done;
10092
10093        supersede_prior_runs(&t, &crate::run::home());
10094
10095        assert_eq!(
10096            RunState::load(&failed.id).unwrap().status,
10097            RunStatus::Failed
10098        );
10099        assert_eq!(
10100            RunState::load(&noop.id).unwrap().status,
10101            RunStatus::VerifiedNoop
10102        );
10103    }
10104
10105    fn approval_question(run: &str) -> ask::Question {
10106        ask::Question::new(
10107            run.to_owned(),
10108            land::APPROVAL_NODE.to_owned(),
10109            "land".to_owned(),
10110            "merge?".to_owned(),
10111            String::new(),
10112            vec!["merge".to_owned(), "hold".to_owned()],
10113        )
10114    }
10115
10116    #[test]
10117    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
10118        crate::run::pin_test_home();
10119        let mut state = run_state(RunStatus::Landing);
10120        state.id = "20260101-000000-fre1".to_owned();
10121        state.parked = true;
10122        state.save().unwrap();
10123        ask::Questions::open()
10124            .put(&mut approval_question(&state.id))
10125            .unwrap();
10126
10127        let mut t = task();
10128        t.runs.push(state.id.clone());
10129        assert_eq!(
10130            land_resume_state(&t),
10131            LandResume::StillWaiting,
10132            "nobody has answered and the timeout has not passed"
10133        );
10134    }
10135
10136    #[test]
10137    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
10138        crate::run::pin_test_home();
10139        let mut state = run_state(RunStatus::Gating);
10140        state.id = "20260101-000000-gt01".to_owned();
10141        state.parked = true;
10142        state.config.graph.answer_timeout = 60;
10143        state.github_text = Some(crate::run::GithubTextAsk {
10144            rewrite: None,
10145            fingerprint: "f".into(),
10146            title: true,
10147            body: false,
10148            categories: vec!["title-language".into()],
10149            question: None,
10150            asks: 1,
10151            resolved: false,
10152            chosen_title: None,
10153            choice: None,
10154            publication: None,
10155        });
10156        state.save().unwrap();
10157        let store = ask::Questions::open();
10158        let mut q = ask::Question::new(
10159            state.id.clone(),
10160            crate::github_text::ASK_NODE.to_owned(),
10161            crate::github_text::ASK_SEAT.to_owned(),
10162            "s".into(),
10163            String::new(),
10164            vec!["use fallback".into()],
10165        );
10166        store.put(&mut q).unwrap();
10167        let mut t = task();
10168        t.runs.push(state.id.clone());
10169        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
10170        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10171        store.put(&mut q).unwrap();
10172        assert_eq!(land_resume_state(&t), LandResume::Ready);
10173        assert!(!store.get(&q.id).unwrap().status.open());
10174        // Once decided, a parked run is an ordinary candidate again.
10175        state.github_text.as_mut().unwrap().resolved = true;
10176        state.save().unwrap();
10177        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
10178    }
10179
10180    #[test]
10181    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
10182        // `ask::ask_and_wait`'s own deadline used to retire a question
10183        // nobody answered; land's approval bypasses that wait (see
10184        // `land::approval_gate`), so this is now the only place
10185        // `graph.answer_timeout` is enforced for a land approval at all.
10186        crate::run::pin_test_home();
10187        let mut state = run_state(RunStatus::Landing);
10188        state.id = "20260101-000000-exp1".to_owned();
10189        state.parked = true;
10190        state.config.graph.answer_timeout = 60;
10191        state.save().unwrap();
10192
10193        let store = ask::Questions::open();
10194        let mut q = approval_question(&state.id);
10195        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10196        store.put(&mut q).unwrap();
10197
10198        let mut t = task();
10199        t.runs.push(state.id.clone());
10200        assert_eq!(
10201            land_resume_state(&t),
10202            LandResume::Ready,
10203            "an expired question must not be waited on forever"
10204        );
10205
10206        let after = store.get(&q.id).unwrap();
10207        assert!(
10208            !after.status.open(),
10209            "the question is abandoned, not silently ignored"
10210        );
10211        assert!(
10212            after.resolution().is_none(),
10213            "an abandoned question is not read as a decision"
10214        );
10215    }
10216
10217    #[test]
10218    fn reclaim_settles_a_running_task_against_its_last_run() {
10219        let mut t = task();
10220        t.start("20260904-000000-4043".to_owned());
10221        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
10222        assert_eq!(
10223            t.status,
10224            TaskStatus::Done,
10225            "a run that actually finished must not stay `running` forever"
10226        );
10227    }
10228
10229    #[test]
10230    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
10231        let dir = tempfile::tempdir().unwrap();
10232        let queue = Queue::at(dir.path().join("queue"));
10233        let mut task = task();
10234        let mut run = run_state(RunStatus::Blocked);
10235        run.reserve_under(dir.path()).unwrap();
10236        run.driver_exited = true;
10237        run.save_under(dir.path()).unwrap();
10238        queue.put(&mut task).unwrap();
10239        let stale = task.clone();
10240        task.resume_override = Some(crate::queue::OperatorResume {
10241            question_id: "pending-resume".into(),
10242            at: Timestamp::now(),
10243            conductor_rehold: None,
10244            forced: true,
10245            pinned_run: Some(run.id.clone()),
10246        });
10247        task.start(run.id.clone());
10248        queue.put(&mut task).unwrap();
10249        // Discard every in-memory handoff, as a worker death before execute does.
10250        let mut recovered = queue.get(&task.id).unwrap();
10251        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
10252        reclaim(&mut recovered, Some(disk), 2, "en");
10253        queue.put(&mut recovered).unwrap();
10254        assert!(recovered.resume_override.is_none());
10255        assert_eq!(
10256            recovered.dispatched_resumes.get("pending-resume"),
10257            Some(&run.id)
10258        );
10259        let mut stale = stale;
10260        queue.put(&mut stale).unwrap();
10261        assert_eq!(
10262            stale.dispatched_resumes, recovered.dispatched_resumes,
10263            "a stale task writer cannot erase dispatch ownership"
10264        );
10265        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
10266        assert!(resumed.decision_starts.is_empty());
10267        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
10268        assert!(
10269            resumed.decision_starts.is_empty(),
10270            "handoff is not execution proof"
10271        );
10272        resumed.begin_pass();
10273        resumed.save_under(dir.path()).unwrap();
10274        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
10275        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
10276        disk.carry_dispatched_resumes(&recovered);
10277        disk.begin_pass();
10278        assert_eq!(
10279            disk.decision_starts.get("pending-resume"),
10280            Some(&0),
10281            "later execution must preserve the original pass receipt"
10282        );
10283    }
10284
10285    #[test]
10286    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
10287        let mut t = task();
10288        t.start("20260904-000000-4043".to_owned());
10289        t.last_error = Some("earlier trouble".to_owned());
10290        let mut state = run_state(RunStatus::Judging);
10291        state.parked = true;
10292        reclaim(&mut t, Some(state), 1, "en");
10293        assert_eq!(t.status, TaskStatus::Parked);
10294        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
10295        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10296        assert!(t.park_reason.is_some());
10297        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
10298        assert!(!t.fresh_start);
10299        assert!(t.status.runnable());
10300    }
10301
10302    #[test]
10303    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
10304        let mut t = task();
10305        t.start("20260904-000000-4043".to_owned());
10306        t.last_error = Some("earlier trouble".to_owned());
10307        settle(
10308            &mut t,
10309            Verdict {
10310                status: RunStatus::Judging,
10311                left_pr: false,
10312                quota_hit: false,
10313                parked: true,
10314                no_viable_candidates: false,
10315            },
10316            "parked after `judging`",
10317            1,
10318        );
10319        assert_eq!(t.status, TaskStatus::Parked);
10320        assert_eq!(t.attempts, 0);
10321        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10322        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
10323        assert_eq!(t.schema, crate::queue::SCHEMA);
10324        assert!(
10325            crate::notices::task_held(&t).is_none(),
10326            "a park is not news"
10327        );
10328        t.start("20260904-000000-4043".to_owned());
10329        assert_eq!(t.park_reason, None);
10330    }
10331
10332    #[test]
10333    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
10334        // A blocked run with attempts left goes back to `Failed`, exactly as
10335        // it would from `attempt` itself - `reclaim` must not invent a second
10336        // policy for a task a daemon merely stopped without reporting.
10337        let mut t = task();
10338        t.start("20260904-000000-4043".to_owned());
10339        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
10340        assert_eq!(t.status, TaskStatus::Failed);
10341        assert!(t.status.runnable());
10342    }
10343
10344    #[test]
10345    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
10346        let mut t = task();
10347        t.start("20260904-000000-4043".to_owned());
10348        assert_eq!(t.attempts, 1);
10349        let mut run = run_state(RunStatus::Implementing);
10350        run.id = "20260904-000000-4043".to_owned();
10351        run.begin_pass();
10352        let cause = crate::run::ParkCause::Upgrade {
10353            from: "0.121.0".to_owned(),
10354            to: Some("0.121.1".to_owned()),
10355        };
10356        run.end_pass_parked(cause.clone());
10357        run.parked = true;
10358        let verdict = Verdict {
10359            status: run.status,
10360            left_pr: false,
10361            quota_hit: false,
10362            parked: true,
10363            no_viable_candidates: false,
10364        };
10365        // A crash after the checkpoint but before queue settlement must
10366        // recover exactly the same scheduling evidence and refund.
10367        let mut orphan = t.clone();
10368        reclaim(&mut orphan, Some(run.clone()), 2, "en");
10369        assert_eq!(orphan.status, TaskStatus::Parked);
10370        assert_eq!(orphan.attempts, 0);
10371        assert_eq!(
10372            orphan.upgrade_resume_key(),
10373            Some((run.passes[0].started_at, orphan.id.as_str()))
10374        );
10375        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
10376        assert_eq!(t.attempts, 0);
10377        assert_eq!(t.passes.len(), 1);
10378        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10379        assert_eq!(t.passes[0].parked, Some(cause));
10380        assert_eq!(t.passes[0].pass_index, 0);
10381        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
10382        assert!(t.upgrade_resume_key().is_some());
10383
10384        // A resumed pass that then fails spends its attempt, and the earlier
10385        // pass's entry is untouched.
10386        t.start("20260904-000000-4043".to_owned());
10387        run.begin_pass();
10388        run.status = RunStatus::Failed;
10389        let verdict = Verdict {
10390            status: RunStatus::Failed,
10391            left_pr: false,
10392            quota_hit: false,
10393            parked: false,
10394            no_viable_candidates: false,
10395        };
10396        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
10397        assert_eq!(t.passes.len(), 2);
10398        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10399        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
10400        assert_eq!(t.passes[1].pass_index, 1);
10401        assert_eq!(t.attempts, 1);
10402    }
10403
10404    #[test]
10405    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
10406        let mut t = task();
10407        t.start("20260904-000000-4043".to_owned());
10408        reclaim(&mut t, None, 2, "en");
10409        assert_eq!(t.status, TaskStatus::Held);
10410        assert!(
10411            t.last_error
10412                .as_deref()
10413                .is_some_and(|e| e.contains("running")),
10414            "the operator needs to know why this task was held"
10415        );
10416    }
10417
10418    #[test]
10419    fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
10420        let dir = tempfile::tempdir().unwrap();
10421        let queue = Queue::at(dir.path().to_path_buf());
10422        let mut task = task();
10423        let run = "20261124-000000-dead";
10424        task.link_run(run);
10425        task.attempts = 2;
10426        task.status = TaskStatus::Running;
10427        task.sync_only = Some(crate::base_sync_only::Request {
10428            run: run.into(),
10429            at: Timestamp::now(),
10430        });
10431        queue.put(&mut task).unwrap();
10432        assert_eq!(
10433            reclaim_orphaned_running(&queue, 3, &Default::default()),
10434            vec![task.id.clone()]
10435        );
10436        let saved = queue.get(&task.id).unwrap();
10437        assert_eq!(saved.status, TaskStatus::Held);
10438        assert_eq!(saved.attempts, 2);
10439        assert_eq!(saved.execution_runs(), [run]);
10440        assert!(
10441            saved
10442                .last_error
10443                .unwrap()
10444                .contains("verification was not allowed")
10445        );
10446        assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
10447    }
10448
10449    #[test]
10450    fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
10451        use crate::base_sync_only::{Outcome, Pass, Request};
10452
10453        let mut state = run_state(RunStatus::Blocked);
10454        let mut task = task();
10455        let request = Request {
10456            run: state.id.clone(),
10457            at: Timestamp::now(),
10458        };
10459        task.start(state.id.clone());
10460        task.sync_only = Some(request.clone());
10461        // Dedicated dispatch saves Running with the pre-pass attempt count.
10462        task.attempts = 2;
10463        let mut pass = Pass::new(request, &state);
10464        pass.result = Outcome::AlreadyCurrent;
10465        state.sync_only_passes.push(pass);
10466        state.begin_pass();
10467
10468        reclaim(&mut task, Some(state), 3, "en");
10469
10470        assert_eq!(task.status, TaskStatus::Held);
10471        assert_eq!(task.attempts, 2);
10472        assert!(task.sync_only.is_none());
10473        let detail = task.hold_reason.unwrap();
10474        assert!(detail.contains("HEAD already contains the base"));
10475        assert!(detail.contains("verification was not allowed"));
10476    }
10477
10478    #[test]
10479    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
10480        let dir = tempfile::tempdir().unwrap();
10481        let queue = Queue::at(dir.path().to_path_buf());
10482
10483        // No run recorded, so this never has to touch `RunState::load`.
10484        let mut orphaned = task();
10485        orphaned.id = "20260904-000000-orph".to_owned();
10486        orphaned.status = TaskStatus::Running;
10487        orphaned.attempts = 1;
10488        queue.put(&mut orphaned).unwrap();
10489
10490        let mut alive = task();
10491        alive.id = "20260904-000000-live".to_owned();
10492        alive.status = TaskStatus::Running;
10493        alive.attempts = 1;
10494        queue.put(&mut alive).unwrap();
10495        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
10496
10497        let mut queued = task();
10498        queued.id = "20260904-000000-wait".to_owned();
10499        queue.put(&mut queued).unwrap();
10500
10501        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10502        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
10503
10504        assert_eq!(
10505            queue.get(&orphaned.id).unwrap().status,
10506            TaskStatus::Held,
10507            "nothing was driving it and there was no run to recover"
10508        );
10509        assert_eq!(
10510            queue.get(&alive.id).unwrap().status,
10511            TaskStatus::Running,
10512            "a live claim must protect the task it belongs to"
10513        );
10514        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
10515    }
10516
10517    /// Read a run.json back from an explicit `home`, the same way
10518    /// `reclaim_abandoned_runs` itself does - never through the
10519    /// process-global `RunState::load`, which this test's own `home` (an
10520    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
10521    /// use at all.
10522    fn read_run_under(home: &Path, id: &str) -> RunState {
10523        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10524        serde_json::from_str(&body).unwrap()
10525    }
10526
10527    #[test]
10528    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
10529        let dir = tempfile::tempdir().unwrap();
10530        let home = dir.path().to_path_buf();
10531        let now = Timestamp::now();
10532        let overrun_seat = || crate::run::ActiveSeat {
10533            node: "implement".to_owned(),
10534            started_at: now - jiff::SignedDuration::new(21_000, 0),
10535            timeout_secs: 3_600,
10536            attempt: 0,
10537            task: None,
10538            command: None,
10539            index: None,
10540            total: None,
10541        };
10542
10543        let mut dead = run_state(RunStatus::Implementing);
10544        dead.id = "20260101-000000-dead".to_owned();
10545        dead.active.insert("impl-A".to_owned(), overrun_seat());
10546        // A `driver_pid` the injected query below confirms gone outright —
10547        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
10548        dead.driver_pid = Some(4242);
10549        dead.save_under(&home).unwrap();
10550
10551        // Same shape, but a live daemon's heartbeat names it: must be left
10552        // exactly alone, however far past its own timeout the seat sits.
10553        let mut alive = run_state(RunStatus::Implementing);
10554        alive.id = "20260101-000000-aliv".to_owned();
10555        alive.active.insert("impl-A".to_owned(), overrun_seat());
10556        alive.save_under(&home).unwrap();
10557        let mut status = Status::new();
10558        status.current = vec![Current {
10559            worker: None,
10560            task: "20260101-000000-task".to_owned(),
10561            run: alive.id.clone(),
10562        }];
10563        write_status_to(&home.join("daemon.json"), &status).unwrap();
10564
10565        // The abandoned seat left an open question behind: nobody is left to
10566        // read an answer once the run is failed, and this must not wait for
10567        // some later daemon startup's own sweep to notice that.
10568        let questions = Questions::at(home.join("questions"));
10569        let mut q = ask::Question::new(
10570            dead.id.clone(),
10571            "implement".to_owned(),
10572            "impl-A".to_owned(),
10573            "Which storage backend?".to_owned(),
10574            String::new(),
10575            vec!["SQLite".to_owned(), "Redis".to_owned()],
10576        );
10577        questions.put(&mut q).unwrap();
10578
10579        let abandoned = reclaim_abandoned_runs_with(
10580            &home,
10581            now,
10582            |pid| if pid == 4242 { Some(false) } else { None },
10583            |_| panic!("a query answering Dead outright needs no identity corroboration"),
10584        );
10585        assert_eq!(abandoned, vec![dead.id.clone()]);
10586
10587        let reloaded = read_run_under(&home, &dead.id);
10588        assert_eq!(reloaded.status, RunStatus::Failed);
10589        assert!(reloaded.active.is_empty());
10590        assert!(
10591            !questions.get(&q.id).unwrap().status.open(),
10592            "the failed run's own open question must be settled in the same pass"
10593        );
10594
10595        let still_alive = read_run_under(&home, &alive.id);
10596        assert_eq!(
10597            still_alive.status,
10598            RunStatus::Implementing,
10599            "a live daemon's claim protects it"
10600        );
10601        assert!(!still_alive.active.is_empty());
10602    }
10603
10604    /// The exact shape a review round flagged as broken: `magi serve` running
10605    /// in this same `home` scans *every* run on disk, including a manual
10606    /// `magi review` / `magi run` this daemon never started and that
10607    /// therefore claims no heartbeat of its own. Before this scan asked
10608    /// `liveness` rather than just `is_working_on`, a manual run whose active
10609    /// seat merely ran a little past its own timeout — the CLI finishing up,
10610    /// its result still being collected — got wiped and failed by a daemon
10611    /// that had nothing to do with it, out from under a process that was
10612    /// still very much running.
10613    #[test]
10614    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
10615        let dir = tempfile::tempdir().unwrap();
10616        let home = dir.path().to_path_buf();
10617        let now = Timestamp::now();
10618
10619        let mut manual = run_state(RunStatus::Reviewing);
10620        manual.id = "20260101-000000-manl".to_owned();
10621        manual.active.insert(
10622            "review-1".to_owned(),
10623            crate::run::ActiveSeat {
10624                node: "review".to_owned(),
10625                started_at: now - jiff::SignedDuration::new(21_000, 0),
10626                timeout_secs: 3_600,
10627                attempt: 0,
10628                task: None,
10629                command: None,
10630                index: None,
10631                total: None,
10632            },
10633        );
10634        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
10635        // but a real, still-running process: `liveness` must corroborate this
10636        // as `Live`, not read the missing daemon claim as death.
10637        manual.driver_pid = Some(4242);
10638        manual.driver_started_at = Some("1790000000".to_owned());
10639        manual.save_under(&home).unwrap();
10640
10641        let abandoned = reclaim_abandoned_runs_with(
10642            &home,
10643            now,
10644            |pid| if pid == 4242 { Some(true) } else { None },
10645            |pid| {
10646                if pid == 4242 {
10647                    Some("1790000000".to_owned())
10648                } else {
10649                    None
10650                }
10651            },
10652        );
10653        assert!(
10654            abandoned.is_empty(),
10655            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
10656        );
10657
10658        let reloaded = read_run_under(&home, &manual.id);
10659        assert_eq!(reloaded.status, RunStatus::Reviewing);
10660        assert!(!reloaded.active.is_empty());
10661    }
10662
10663    #[test]
10664    fn an_already_claimed_task_is_skipped_rather_than_failed() {
10665        let dir = tempfile::tempdir().unwrap();
10666        let queue = Queue::at(dir.path().to_path_buf());
10667        let mut only = task();
10668        queue.put(&mut only).unwrap();
10669
10670        let _elsewhere = queue.claim(&only.id).unwrap();
10671        let candidates = runnable(&queue);
10672        assert_eq!(candidates.len(), 1, "the task is still runnable");
10673        assert!(
10674            queue.claim(&candidates[0].id).is_err(),
10675            "the loop cannot take a claim somebody else holds"
10676        );
10677
10678        let after = queue.get(&only.id).unwrap();
10679        assert_eq!(after.status, TaskStatus::Queued);
10680        assert_eq!(
10681            after.attempts, 0,
10682            "losing the race is not an attempt at the task"
10683        );
10684        assert_eq!(after.last_error, None);
10685    }
10686
10687    #[test]
10688    fn the_status_file_round_trips_and_its_heartbeat_advances() {
10689        let dir = tempfile::tempdir().unwrap();
10690        let path = dir.path().join("daemon.json");
10691
10692        let mut status = Status::new();
10693        status.idle = false;
10694        status.completed = 7;
10695        status.current = vec![Current {
10696            worker: None,
10697            task: "20260902-000000-t111".to_owned(),
10698            run: "20260902-000001-r111".to_owned(),
10699        }];
10700        write_status_to(&path, &status).unwrap();
10701        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10702        assert_eq!(first.schema, SCHEMA);
10703        assert_eq!(first.pid, std::process::id());
10704        assert!(!first.idle);
10705        assert_eq!(first.completed, 7);
10706        assert_eq!(first.current, status.current);
10707        assert!(
10708            !path.with_extension("json.tmp").exists(),
10709            "the temp file is renamed, not left behind"
10710        );
10711
10712        std::thread::sleep(Duration::from_millis(5));
10713        status.updated_at = Timestamp::now();
10714        status.polls = 3;
10715        write_status_to(&path, &status).unwrap();
10716        let second: Status =
10717            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10718        assert!(
10719            second.updated_at > first.updated_at,
10720            "a reader can only detect staleness if the heartbeat moves"
10721        );
10722        assert_eq!(
10723            second.started_at, first.started_at,
10724            "the start time is not a heartbeat"
10725        );
10726        assert_eq!(second.polls, 3);
10727    }
10728
10729    #[test]
10730    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
10731        let dir = tempfile::tempdir().unwrap();
10732
10733        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
10734
10735        let mut status = Status::new();
10736        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
10737        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10738        let stale = read_status(dir.path()).unwrap();
10739        assert!(
10740            !stale.running(Timestamp::now()),
10741            "a minute without a heartbeat is a dead daemon, not a busy one"
10742        );
10743        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
10744
10745        status.updated_at = Timestamp::now();
10746        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10747        let fresh = read_status(dir.path()).unwrap();
10748        assert!(fresh.running(Timestamp::now()));
10749    }
10750
10751    #[test]
10752    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
10753        let dir = tempfile::tempdir().unwrap();
10754        let now = Timestamp::now();
10755        let mine = "20260903-080619-01c2";
10756
10757        assert!(
10758            !is_working_on(dir.path(), mine, now),
10759            "no status file means nobody is working on anything"
10760        );
10761
10762        let mut status = Status::new();
10763        status.current = vec![Current {
10764            worker: None,
10765            task: "20260903-080340-0167".to_owned(),
10766            run: mine.to_owned(),
10767        }];
10768        status.updated_at = now;
10769        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10770        assert!(is_working_on(dir.path(), mine, now));
10771        assert!(
10772            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
10773            "a daemon busy with one run is not working on another"
10774        );
10775
10776        // A killed daemon stops writing heartbeats but leaves the file behind
10777        // naming the run it died in. That run must not be undeletable forever.
10778        status.updated_at = now - jiff::SignedDuration::from_secs(600);
10779        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10780        assert!(
10781            !is_working_on(dir.path(), mine, now),
10782            "a stale heartbeat is a dead daemon, so its run is a leftover"
10783        );
10784    }
10785
10786    #[test]
10787    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
10788        let dir = tempfile::tempdir().unwrap();
10789        let now = Timestamp::now();
10790
10791        assert!(
10792            !is_working_on_short(dir.path(), "01c2", now),
10793            "no status file means nobody is working on anything"
10794        );
10795
10796        let mut status = Status::new();
10797        status.current = vec![Current {
10798            worker: None,
10799            task: "20260903-080340-0167".to_owned(),
10800            run: "20260903-080619-01c2".to_owned(),
10801        }];
10802        status.updated_at = now;
10803        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10804        assert!(
10805            is_working_on_short(dir.path(), "01c2", now),
10806            "the run's short id is the last block of its full id"
10807        );
10808        assert!(
10809            !is_working_on_short(dir.path(), "3cbf", now),
10810            "a daemon busy with one worktree bay is not working on another"
10811        );
10812    }
10813
10814    #[test]
10815    fn a_newer_status_file_still_yields_a_reading() {
10816        let dir = tempfile::tempdir().unwrap();
10817        // A field this build has never heard of must not turn the reading into
10818        // nothing at all; that is the whole reason the reader is permissive.
10819        std::fs::write(
10820            dir.path().join("daemon.json"),
10821            serde_json::json!({
10822                "schema": 2,
10823                "updated_at": Timestamp::now().to_string(),
10824                "idle": true,
10825                "surprise": { "nested": [1, 2, 3] },
10826            })
10827            .to_string(),
10828        )
10829        .unwrap();
10830
10831        let reading = read_status(dir.path()).expect("a forward-compatible read");
10832        assert!(reading.running(Timestamp::now()));
10833        assert!(reading.idle);
10834        assert!(reading.current.is_empty());
10835    }
10836
10837    #[test]
10838    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
10839        // A daemon started before `current` became a list keeps writing this
10840        // shape on every heartbeat until it is restarted. A rolling upgrade
10841        // - a newer `magi web` or `magi doctor` reading an older `magi
10842        // serve`'s heartbeat - must still see the run it is on, not "no
10843        // daemon" from a type mismatch failing the whole struct.
10844        let dir = tempfile::tempdir().unwrap();
10845        std::fs::write(
10846            dir.path().join("daemon.json"),
10847            serde_json::json!({
10848                "schema": 1,
10849                "pid": 4242,
10850                "updated_at": Timestamp::now().to_string(),
10851                "idle": false,
10852                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
10853                "completed": 3,
10854                "polls": 9,
10855            })
10856            .to_string(),
10857        )
10858        .unwrap();
10859
10860        let reading = read_status(dir.path()).expect("an older shape must still parse");
10861        assert!(reading.running(Timestamp::now()));
10862        assert_eq!(
10863            reading.current,
10864            vec![Current {
10865                worker: None,
10866                task: "20260902-140501-aaaa".to_owned(),
10867                run: "20260902-140502-bbbb".to_owned(),
10868            }]
10869        );
10870    }
10871
10872    #[test]
10873    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
10874        let dir = tempfile::tempdir().unwrap();
10875        std::fs::write(
10876            dir.path().join("daemon.json"),
10877            serde_json::json!({
10878                "schema": 1,
10879                "updated_at": Timestamp::now().to_string(),
10880                "idle": true,
10881                "current": null,
10882            })
10883            .to_string(),
10884        )
10885        .unwrap();
10886        let with_null = read_status(dir.path()).expect("null must still parse");
10887        assert!(with_null.current.is_empty());
10888
10889        std::fs::write(
10890            dir.path().join("daemon.json"),
10891            serde_json::json!({
10892                "schema": 1,
10893                "updated_at": Timestamp::now().to_string(),
10894                "idle": true,
10895            })
10896            .to_string(),
10897        )
10898        .unwrap();
10899        let absent = read_status(dir.path()).expect("a missing field must still parse");
10900        assert!(absent.current.is_empty());
10901    }
10902
10903    #[test]
10904    fn a_task_without_a_repository_runs_in_the_daemons_default() {
10905        let fallback = Path::new("/default");
10906        let mut blank = task();
10907        blank.repo = PathBuf::new();
10908        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
10909        let mut dot = task();
10910        dot.repo = PathBuf::from(".");
10911        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
10912        assert_eq!(
10913            repo_for(&task(), fallback),
10914            PathBuf::from("/repo"),
10915            "a task that names a repository keeps it"
10916        );
10917    }
10918
10919    #[test]
10920    fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
10921        let dir = tempfile::tempdir().unwrap();
10922        let repo = dir.path();
10923        let path = repo.join("explicit.toml");
10924        std::fs::write(
10925            &path,
10926            "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
10927        )
10928        .unwrap();
10929        let opts = Opts {
10930            config: Some(path),
10931            ..Opts::default()
10932        };
10933        let queue = Queue::at(repo.join("queue"));
10934        let mut new = task();
10935        queue.put(&mut new).unwrap();
10936        let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
10937        assert_eq!(
10938            resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
10939            BuildCache::Isolated
10940        );
10941
10942        let mut old = task();
10943        old.schema = 22;
10944        queue.put(&mut old).unwrap();
10945        let mut old = queue.get(&old.id).unwrap();
10946        let config = resolved(&old);
10947        assert_eq!(config.verify.build_cache, BuildCache::Shared);
10948        assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
10949        old.hold_manual(Some("wait".into()));
10950        queue.put(&mut old).unwrap();
10951
10952        let mut saved = queue.get(&old.id).unwrap();
10953        assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
10954        saved
10955            .overrides
10956            .as_mut()
10957            .unwrap()
10958            .merge_over(&crate::queue::RunOverrides {
10959                build_cache: Some(BuildCache::Isolated),
10960                ..Default::default()
10961            });
10962        queue.put(&mut saved).unwrap();
10963        assert_eq!(
10964            resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
10965            BuildCache::Isolated
10966        );
10967    }
10968
10969    #[test]
10970    fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
10971        let dir = tempfile::tempdir().unwrap();
10972        let path = dir.path().join("explicit.toml");
10973        let write = |verify: &str| {
10974            std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
10975        };
10976        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
10977        let opts = Opts {
10978            config: Some(path.clone()),
10979            ..Opts::default()
10980        };
10981        let mut task = task();
10982        task.set_urgent(true).unwrap();
10983        let resolved = |task: &Task| {
10984            prepare_for(dir.path(), &opts, task)
10985                .unwrap()
10986                .verify
10987                .build_cache
10988        };
10989        assert_eq!(resolved(&task), BuildCache::Isolated);
10990        task.change_build_cache(Some(BuildCache::Shared)).unwrap();
10991        assert_eq!(resolved(&task), BuildCache::Shared);
10992        task.change_build_cache(None).unwrap();
10993        assert_eq!(resolved(&task), BuildCache::Isolated);
10994        task.set_urgent(false).unwrap();
10995        assert_eq!(resolved(&task), BuildCache::Shared);
10996
10997        // Urgent work must never be the one stopped by isolation: with no
10998        // shared cache to wait behind, or with a verification command isolated
10999        // mode cannot run, an urgent task keeps the configured mode.
11000        task.set_urgent(true).unwrap();
11001        write("e2e = [\"npm test\"]\n");
11002        assert_eq!(resolved(&task), BuildCache::Shared);
11003        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
11004        assert_eq!(resolved(&task), BuildCache::Shared);
11005        // An explicit choice stays strict and is applied as asked.
11006        task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
11007        assert_eq!(resolved(&task), BuildCache::Isolated);
11008    }
11009
11010    #[test]
11011    fn task_implementers_edit_inherits_daemon_config_and_merge() {
11012        let dir = tempfile::tempdir().unwrap();
11013        let path = dir.path().join("explicit.toml");
11014        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
11015        let opts = Opts {
11016            config: Some(path),
11017            merge: Some("none".into()),
11018            ..Default::default()
11019        };
11020        let mut t = task();
11021        t.set_implementers(
11022            2,
11023            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11024                .unwrap(),
11025        )
11026        .unwrap();
11027        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
11028        assert_eq!(cfg.graph.implementers, 2);
11029        assert_eq!(cfg.graph.judges, 1);
11030        assert_eq!(cfg.merge.mode, MergeMode::None);
11031        t.set_implementers(1, &cfg).unwrap();
11032        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
11033        apply_task_implementers(&mut cfg, &t);
11034        assert_eq!(cfg.graph.implementers, 1);
11035        assert_eq!(cfg.graph.judges, 1);
11036        assert_eq!(cfg.merge.mode, MergeMode::None);
11037    }
11038
11039    #[test]
11040    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
11041        let dir = tempfile::tempdir().unwrap();
11042        let repo = dir.path().join("repo");
11043        std::fs::create_dir(&repo).unwrap();
11044        std::fs::write(
11045            repo.join("magi.toml"),
11046            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
11047        )
11048        .unwrap();
11049        let daemon_config = dir.path().join("daemon.toml");
11050        std::fs::write(
11051            &daemon_config,
11052            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
11053        )
11054        .unwrap();
11055        let opts = Opts {
11056            config: Some(daemon_config),
11057            merge: Some("pr".into()),
11058            ..Default::default()
11059        };
11060        let q = Queue::at(dir.path().join("queue"));
11061        let validation: Config =
11062            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11063                .unwrap();
11064        // No provenance field on legacy direct tasks: both shapes stay isolated.
11065        for record in ["{}", r#"{"candidates":2}"#] {
11066            let overrides = serde_json::from_str(record).unwrap();
11067            let filing = crate::direct::Filing {
11068                instruction: "work".into(),
11069                title: "direct".into(),
11070                repo: repo.clone(),
11071                source: crate::queue::Source::Human,
11072                solo: false,
11073                overrides,
11074                review_of: None,
11075                sources: Default::default(),
11076            };
11077            let filed =
11078                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
11079            let crate::direct::Filed::Standalone {
11080                mut task,
11081                claim: _claim,
11082            } = filed
11083            else {
11084                panic!("local filing")
11085            };
11086            let before = prepare_for(&repo, &opts, &task).unwrap();
11087            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
11088            assert_eq!(
11089                before.merge.mode,
11090                MergeMode::None,
11091                "daemon --merge must not leak"
11092            );
11093            for n in [2, 1, 2] {
11094                task.set_implementers(n, &validation).unwrap();
11095                q.put(&mut task).unwrap();
11096                task = q.get(&task.id).unwrap();
11097                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
11098                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
11099                apply_task_implementers(&mut cfg, &task);
11100                assert_eq!(cfg.graph.implementers, usize::from(n));
11101                assert_eq!(cfg.graph.judges, 2);
11102                assert_eq!(cfg.merge.mode, MergeMode::None);
11103            }
11104        }
11105    }
11106
11107    #[test]
11108    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
11109        let cfg: Config =
11110            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11111                .unwrap();
11112        let mut t = task();
11113        t.review_of = Some("review-target".into());
11114        t.hold_manual(Some("retry".into()));
11115        let mut previous = RunState::new(
11116            PathBuf::from("/repo"),
11117            "main".into(),
11118            "abc1234".into(),
11119            "review".into(),
11120            cfg.clone(),
11121        );
11122        previous.config.graph.implementers = 2;
11123        for count in [1, 3] {
11124            t.set_implementers(count, &cfg).unwrap();
11125            t.release();
11126            assert_eq!(t.review_of.as_deref(), Some("review-target"));
11127            for proposed in [
11128                Starter::Resume(previous.id.clone()),
11129                Starter::Review("recovery-target".into()),
11130            ] {
11131                assert_eq!(
11132                    starter_with_implementers(&t, Some(&previous), proposed),
11133                    Starter::Review("review-target".into())
11134                );
11135            }
11136            let mut configured = cfg.clone();
11137            apply_task_implementers(&mut configured, &t);
11138            assert_eq!(configured.graph.implementers, usize::from(count));
11139            assert_eq!(previous.config.graph.implementers, 2);
11140        }
11141    }
11142
11143    #[test]
11144    fn task_implementers_dispatch_and_resume_agree() {
11145        let mut t = task();
11146        let cfg: crate::config::Config =
11147            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11148                .unwrap();
11149        let mut run = RunState::new(
11150            PathBuf::from("/repo"),
11151            "main".into(),
11152            "abc1234".into(),
11153            "work".into(),
11154            cfg.clone(),
11155        );
11156        run.config.graph.implementers = 2;
11157        for n in [2, 1, 3, 2] {
11158            t.set_implementers(n, &cfg).unwrap();
11159            let mut dispatched = cfg.clone();
11160            apply_task_implementers(&mut dispatched, &t);
11161            assert_eq!(dispatched.graph.implementers, usize::from(n));
11162            assert_eq!(implementers_match(&t, &run), n == 2);
11163            for proposed in [
11164                Starter::Resume(run.id.clone()),
11165                Starter::Review("old-branch".into()),
11166            ] {
11167                let expected = if n == 2 {
11168                    proposed.clone()
11169                } else {
11170                    Starter::Start
11171                };
11172                assert_eq!(
11173                    starter_with_implementers(&t, Some(&run), proposed),
11174                    expected
11175                );
11176            }
11177            assert_eq!(
11178                run.config.graph.implementers, 2,
11179                "history must not be rewritten"
11180            );
11181        }
11182        t.solo = false;
11183        t.overrides = None;
11184        assert!(implementers_match(&t, &run));
11185    }
11186
11187    #[test]
11188    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
11189        // Three seats said out loud. What `solo` promises is one candidate
11190        // *whatever the config asks for*, so the contrast has to be a number
11191        // this test owns - it used to be `Config::default()`'s, which became
11192        // 1 when one implementation became the default and left the two
11193        // halves of this test asserting the same thing.
11194        let mut solo_cfg = Config::default();
11195        solo_cfg.graph.implementers = 3;
11196        let mut solo_task = task();
11197        solo_task.solo = true;
11198        apply_task_implementers(&mut solo_cfg, &solo_task);
11199        assert_eq!(solo_cfg.graph.implementers, 1);
11200
11201        let mut plain_cfg = Config::default();
11202        plain_cfg.graph.implementers = 3;
11203        let plain_task = task();
11204        assert!(!plain_task.solo);
11205        apply_task_implementers(&mut plain_cfg, &plain_task);
11206        assert_eq!(
11207            plain_cfg.graph.implementers, 3,
11208            "a task that did not ask to run alone keeps the config's candidates"
11209        );
11210    }
11211
11212    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
11213        QuotaLoss {
11214            cause: crate::agent::QuotaCause::UsageLimit,
11215            agent: String::new(),
11216            seat: seat.into(),
11217            node: "judge".into(),
11218            at: at.parse().unwrap(),
11219            reset: reset.map(str::to_string),
11220        }
11221    }
11222
11223    #[test]
11224    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
11225        let now = Timestamp::now();
11226        for reset in [None, Some("in 1h")] {
11227            let auth = crate::agent::Quota {
11228                cause: crate::agent::QuotaCause::Authentication,
11229                agent: "alpha".into(),
11230                reset: reset.map(str::to_owned),
11231            };
11232            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
11233            assert_eq!(cooldown_until(&[loss], now), None);
11234        }
11235    }
11236
11237    #[test]
11238    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
11239        let old: Vec<QuotaLoss> = (1..=4)
11240            .map(|i| {
11241                loss(
11242                    &format!("judge-{i}"),
11243                    "2026-09-23T05:23:00Z",
11244                    Some("2:40pm (Asia/Tokyo)"),
11245                )
11246            })
11247            .collect();
11248        let fresh = losses_this_attempt(&old, &old);
11249        assert!(fresh.is_empty());
11250        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
11251        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
11252    }
11253
11254    #[test]
11255    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
11256        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
11257        let now = Timestamp::now();
11258        let mut after = old.clone();
11259        after.push(loss("judge-2", &now.to_string(), None));
11260        let fresh = losses_this_attempt(&old, &after);
11261        assert_eq!(fresh, vec![after[1].clone()]);
11262        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
11263        assert_eq!(
11264            until,
11265            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
11266        );
11267    }
11268
11269    #[test]
11270    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
11271        // `recover_stall` removes judge-1's loss and the retry then hits quota
11272        // again: the vector is the same length, so an index diff sees nothing.
11273        let before = vec![
11274            loss("judge-1", "2026-09-23T05:23:00Z", None),
11275            loss("judge-2", "2026-09-23T05:24:00Z", None),
11276        ];
11277        let after = vec![
11278            loss("judge-2", "2026-09-23T05:24:00Z", None),
11279            loss("judge-1", "2026-09-24T01:00:00Z", None),
11280        ];
11281        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
11282    }
11283
11284    #[test]
11285    fn merge_overrides_are_parsed_or_refused() {
11286        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
11287        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
11288        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
11289        assert!(merge_mode("squash").is_err());
11290    }
11291
11292    #[test]
11293    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
11294        let now = Timestamp::now();
11295        let fallback = Duration::from_secs(300);
11296        let cap = Duration::from_secs(1800);
11297
11298        // No reset hint at all: the fallback.
11299        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
11300
11301        // A reset ten minutes out, well inside the cap: waited for exactly.
11302        let soon = now + jiff::SignedDuration::from_secs(600);
11303        assert_eq!(
11304            quota_wait(Some(soon), now, fallback, cap),
11305            Duration::from_secs(600)
11306        );
11307
11308        // A reset already in the past is not trusted: the fallback, not a
11309        // zero or negative wait that would spin the loop right back around.
11310        let past = now - jiff::SignedDuration::from_secs(60);
11311        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
11312
11313        // A reset further out than the cap is trusted for direction but not
11314        // for magnitude: a parsing slip must not sleep the loop for a day.
11315        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
11316        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
11317    }
11318
11319    #[test]
11320    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
11321        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11322
11323        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
11324        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
11325
11326        // Same clock reading, but it has already gone by today: read as
11327        // tomorrow's, since the CLI would not still be reporting a limit past
11328        // its own stated reset.
11329        let already_past =
11330            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
11331        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
11332
11333        assert!(
11334            parse_reset_hint("session limit reached", now, now).is_none(),
11335            "free text with no recognised shape is not guessed at"
11336        );
11337        assert!(
11338            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
11339            "an unresolvable zone name is not guessed at either"
11340        );
11341    }
11342
11343    #[test]
11344    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
11345        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11346
11347        let at = parse_reset_hint(
11348            "You've hit your usage limit. Visit \
11349             https://chatgpt.com/codex/settings/usage to purchase more \
11350             credits or try again at Sep 19th, 2026 5:10 PM.",
11351            now,
11352            now,
11353        )
11354        .expect("the codex reset wording is a recognised shape");
11355        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
11356
11357        // The month is explicit, so a date already earlier in the same
11358        // sentence-implied year than `now` is trusted as written rather than
11359        // rolled forward a year the way the bracketed shape rolls a
11360        // same-day clock reading to tomorrow.
11361        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
11362            .expect("an explicit year needs no rollover");
11363        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
11364
11365        assert!(
11366            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
11367            "a two-digit year is not the documented shape and is not guessed at"
11368        );
11369        assert!(
11370            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
11371            "a four-letter month name is not the documented three-letter abbreviation"
11372        );
11373        assert!(
11374            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
11375            "an explicit zone on the dated shape is a format nobody has \
11376             documented, and is refused rather than guessed at as UTC"
11377        );
11378    }
11379
11380    #[test]
11381    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
11382        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
11383        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
11384
11385        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
11386        assert_eq!(at.as_second() - recorded.as_second(), 3769);
11387
11388        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
11389        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
11390
11391        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
11392            assert!(
11393                parse_reset_hint(bad, now, recorded).is_none(),
11394                "{bad:?} must not be guessed at"
11395            );
11396        }
11397    }
11398
11399    /// A loop whose queue lives in a temp tree and whose poll interval is far
11400    /// longer than the test's patience, so anything that waits out a poll
11401    /// instead of noticing the stop fails rather than merely being slow.
11402    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
11403        let config = dir.join("magi.toml");
11404        std::fs::write(
11405            &config,
11406            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
11407        )
11408        .unwrap();
11409        let opts = Opts {
11410            poll: Duration::from_secs(30),
11411            config: Some(config),
11412            // The explicit fixture config keeps startup cleanup from reading
11413            // machine configuration. This fictional repository likewise
11414            // keeps any best-effort git cleanup away from this checkout.
11415            repo: dir.join("repo"),
11416            ..Opts::default()
11417        };
11418        // The status file goes in a directory that does not exist yet, so its
11419        // creation is itself evidence the loop published one. `worktrees`
11420        // must be just as fictional: the janitor reclaims worktrees under it
11421        // for real, and a test that let it fall through to
11422        // `crate::run::default_worktree_root()` would have it reclaim
11423        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
11424        // which is exactly what happened before this function took the
11425        // parameter at all.
11426        let home = dir.join("home");
11427        // These control-only fixtures do not launch native workers. Give the
11428        // independently tested maintenance services a fresh cadence receipt.
11429        let stamps = home.join("service-ticks");
11430        std::fs::create_dir_all(&stamps).unwrap();
11431        for service in ["waiter", "deputies", "release-watch"] {
11432            std::fs::write(
11433                stamps.join(service),
11434                Timestamp::now().as_second().to_string(),
11435            )
11436            .unwrap();
11437        }
11438        for operation in [
11439            "conductor",
11440            "maintenance",
11441            "housekeeping",
11442            "disk-pressure",
11443            "cache",
11444            "fetch",
11445            "chat-goals",
11446        ] {
11447            std::fs::write(
11448                stamps.join(format!("daemon-{operation}")),
11449                serde_json::to_vec(&Timestamp::now()).unwrap(),
11450            )
11451            .unwrap();
11452        }
11453        let worktrees = dir.join("wt");
11454        (
11455            opts,
11456            Queue::at(dir.join("queue")),
11457            home.join("daemon.json"),
11458            home,
11459            worktrees,
11460        )
11461    }
11462
11463    #[tokio::test]
11464    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
11465        let dir = tempfile::tempdir().unwrap();
11466        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11467        let mut waiting = task();
11468        waiting.repo = opts.repo.clone();
11469        waiting.hold_machine(crate::disk::gate(1, 100));
11470        waiting.mark_disk_capacity();
11471        waiting.attempts = 2;
11472        queue.put(&mut waiting).unwrap();
11473        let mut busy = task();
11474        busy.status = TaskStatus::Running;
11475        queue.put(&mut busy).unwrap();
11476        let payload = serde_json::to_value(ServiceWorker {
11477            opts,
11478            queue: queue.root().to_owned(),
11479            worktrees_root: worktrees,
11480            operation: "maintenance".into(),
11481        })
11482        .unwrap();
11483        run_service_worker(&home, payload.clone()).await.unwrap();
11484        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
11485        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11486        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
11487        run_service_worker(&home, payload).await.unwrap();
11488        assert!(
11489            crate::worker::active(&home).unwrap().is_empty(),
11490            "monitoring only queues; normal dispatch owns launches"
11491        );
11492        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11493    }
11494
11495    #[tokio::test]
11496    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
11497        let dir = tempfile::tempdir().unwrap();
11498        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11499        let cfg = Config::default();
11500        start_service(
11501            &home,
11502            &opts,
11503            &queue,
11504            &worktrees,
11505            "housekeeping",
11506            Some(&cfg),
11507            true,
11508        )
11509        .await
11510        .unwrap();
11511        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
11512        let read = |path: &Path| -> serde_json::Value {
11513            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
11514        };
11515        assert_eq!(read(&receipt)["detail"], "cadence not due");
11516        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
11517        start_service(
11518            &home,
11519            &opts,
11520            &queue,
11521            &worktrees,
11522            "housekeeping",
11523            Some(&cfg),
11524            true,
11525        )
11526        .await
11527        .unwrap();
11528        assert_eq!(
11529            read(&receipt)["detail"],
11530            "active work or runnable task queue"
11531        );
11532        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
11533        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
11534        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
11535        start_service(
11536            &home,
11537            &opts,
11538            &queue,
11539            &worktrees,
11540            "disk-pressure",
11541            Some(&cfg),
11542            false,
11543        )
11544        .await
11545        .unwrap();
11546        assert_eq!(
11547            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
11548            "no active work; idle housekeeping owns scan"
11549        );
11550        assert!(crate::worker::active(&home).unwrap().is_empty());
11551    }
11552
11553    #[tokio::test]
11554    async fn goal_observation_service_does_not_block_scheduler_decisions() {
11555        let dir = tempfile::tempdir().unwrap();
11556        let (opts, _, _, home, worktrees) = idle_loop(dir.path());
11557        let queue = Queue::at(home.join("queue"));
11558        let mut task = task();
11559        task.repo = opts.repo.clone();
11560        task.chat = Some("decision-chat".into());
11561        task.hold_machine(Some("waiting for a decision".into()));
11562        queue.put(&mut task).unwrap();
11563        let questions = Questions::at(home.join("questions"));
11564        let mut question = action_question(&task.id, ask::ChoiceAction::Done);
11565        question.node = crate::conduct::NODE.into();
11566        question.status = ask::QuestionStatus::Open;
11567        question.answer = None;
11568        question.answered_at = None;
11569        questions.put(&mut question).unwrap();
11570        questions
11571            .update(&question.id, |q| {
11572                q.answer(ask::Answer::Choice("resume で続行する".into()))
11573            })
11574            .unwrap();
11575
11576        let talks = crate::talk::Talks::at(home.join("talks"));
11577        let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
11578        decision_chat.pending = "Keep this unsent status question".into();
11579        talks.put(&mut decision_chat).unwrap();
11580        let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
11581        talk.goals.push(serde_json::from_value(serde_json::json!({
11582            "id":"goal","purpose":"follow the retained job","scope":"one task",
11583            "condition":{"description":"land the result","kind":"runs_merged"},
11584            "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
11585            "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
11586            "started":1,"wakes":1,"last_checked":null,"fingerprint":""
11587        })).unwrap());
11588        talks.put(&mut talk).unwrap();
11589
11590        // A retained service lease models an observation still waiting on its
11591        // external dependency. Admission must neither await nor repeat it.
11592        let directory = home.join("workers/jobs/abcdef");
11593        std::fs::create_dir_all(&directory).unwrap();
11594        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11595        crate::pr_head::try_lock_file(&lease).unwrap();
11596        let mut job = crate::worker::Job {
11597            id: "abcdef".into(),
11598            sequence: 1,
11599            kind: "daemon-service".into(),
11600            key: "service:daemon-chat-goals".into(),
11601            payload: serde_json::Value::Null,
11602            generation: "fixture".into(),
11603            version: None,
11604            status: crate::worker::Status::Running,
11605            result: None,
11606            pid: Some(std::process::id()),
11607            created_at: Timestamp::now().as_second() as u64,
11608            finished_at: None,
11609        };
11610        let record = directory.join("job.json");
11611        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11612        let status = Arc::new(Mutex::new(Status::new()));
11613        let stop = Stop::new();
11614        let mut dispatch = Box::pin(poll(
11615            &opts,
11616            &queue,
11617            &status,
11618            &home,
11619            &worktrees,
11620            &stop,
11621            DispatchLimits {
11622                max_concurrent: 1,
11623                pause_for_interrupts: false,
11624                recovery_cfg: None,
11625            },
11626        ));
11627        std::future::poll_fn(|cx| {
11628            assert!(dispatch.as_mut().poll(cx).is_pending());
11629            std::task::Poll::Ready(())
11630        })
11631        .await;
11632        assert!(lock(&status).polls > 0);
11633        let saved = queue.get(&task.id).unwrap();
11634        assert_eq!(saved.status, TaskStatus::Done);
11635        assert!(saved.action_applied(&question.id));
11636        assert!(
11637            talks
11638                .get("decision-chat")
11639                .unwrap()
11640                .pending
11641                .contains("Keep this unsent status question")
11642        );
11643        let goal = talks.get(&talk.id).unwrap().goals.remove(0);
11644        assert_eq!(goal.state, crate::chat_goal::State::Runnable);
11645        assert_eq!(
11646            goal.started,
11647            Some(1),
11648            "only the observation worker may reconcile its goal"
11649        );
11650        assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
11651
11652        stop.stop();
11653        dispatch.await.unwrap();
11654        job.status = crate::worker::Status::Finished;
11655        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
11656        drop(lease);
11657    }
11658
11659    #[test]
11660    fn a_stop_is_idempotent_and_once_set_stays_set() {
11661        let stop = Stop::new();
11662        assert!(!stop.stopped());
11663
11664        stop.stop();
11665        assert!(stop.stopped());
11666        stop.stop();
11667        assert!(stop.stopped(), "a second stop is not a toggle");
11668
11669        let shared = stop.clone();
11670        assert!(
11671            shared.stopped(),
11672            "a clone is the same stop; that is how the loop and its caller share one"
11673        );
11674    }
11675
11676    #[tokio::test]
11677    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
11678        for operation in ["conductor", "maintenance", "housekeeping"] {
11679            let dir = tempfile::tempdir().unwrap();
11680            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
11681            opts.once = true;
11682            opts.poll = Duration::from_millis(1);
11683            // This test exercises answer scheduling, not explicit discard:
11684            // ordinary Done requires a completed retained execution.
11685            let mut state = run_state(RunStatus::Ready);
11686            state.reserve_under(&home).unwrap();
11687            state.save_under(&home).unwrap();
11688            let mut task = task();
11689            task.runs.push(state.id.clone());
11690            queue.put(&mut task).unwrap();
11691            let claim = queue.claim(&task.id).unwrap();
11692
11693            // Model a live service holding the task's claim across the
11694            // scheduler's dispatch scan. No real subprocess or timed race.
11695            let directory = home.join("workers/jobs/abcdef");
11696            std::fs::create_dir_all(&directory).unwrap();
11697            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11698            crate::pr_head::try_lock_file(&lease).unwrap();
11699            let mut job = crate::worker::Job {
11700                id: "abcdef".into(),
11701                sequence: 1,
11702                kind: "daemon-service".into(),
11703                key: format!("service:daemon-{operation}"),
11704                payload: serde_json::Value::Null,
11705                generation: "fixture".into(),
11706                version: None,
11707                status: crate::worker::Status::Running,
11708                result: None,
11709                pid: Some(std::process::id()),
11710                created_at: Timestamp::now().as_second() as u64,
11711                finished_at: None,
11712            };
11713            let record = directory.join("job.json");
11714            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11715
11716            let status = Arc::new(Mutex::new(Status::new()));
11717            let stop = Stop::new();
11718            let mut drain = Box::pin(poll(
11719                &opts,
11720                &queue,
11721                &status,
11722                &home,
11723                &worktrees,
11724                &stop,
11725                DispatchLimits {
11726                    max_concurrent: 1,
11727                    pause_for_interrupts: false,
11728                    recovery_cfg: None,
11729                },
11730            ));
11731            std::future::poll_fn(|cx| {
11732                use std::future::Future;
11733                assert!(
11734                    drain.as_mut().poll(cx).is_pending(),
11735                    "--once must wait for {operation} to release its queue claim"
11736                );
11737                std::task::Poll::Ready(())
11738            })
11739            .await;
11740            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
11741
11742            // An answer arrives while the service still owns the claim. A
11743            // fresh scheduling pass must apply it before declaring idle.
11744            let questions = Questions::at(home.join("questions"));
11745            let mut q = action_question(&state.id, ask::ChoiceAction::Done);
11746            questions.put(&mut q).unwrap();
11747            drop(claim);
11748            // Model services that took longer than their cadence, without a
11749            // wall-clock sleep. The final scans must not respawn them even
11750            // though their receipts now permit another periodic invocation.
11751            let expired =
11752                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
11753            for service in [operation, "housekeeping"] {
11754                std::fs::write(
11755                    home.join("service-ticks").join(format!("daemon-{service}")),
11756                    &expired,
11757                )
11758                .unwrap();
11759            }
11760            job.status = crate::worker::Status::Finished;
11761            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11762            drop(lease);
11763            tokio::time::timeout(Duration::from_secs(2), drain)
11764                .await
11765                .expect("the settled service must allow the drain to finish")
11766                .unwrap();
11767            let after = queue.get(&task.id).unwrap();
11768            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
11769            assert!(after.action_applied(&q.id));
11770            for service in [operation, "housekeeping"] {
11771                assert_eq!(
11772                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
11773                        .unwrap(),
11774                    expired,
11775                    "the final once rescan must not restart {service}"
11776                );
11777            }
11778        }
11779    }
11780
11781    #[test]
11782    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
11783        let stop = Stop::new();
11784        stop.busy.store(1, Ordering::SeqCst);
11785        assert!(
11786            !stop.finishing(),
11787            "a busy loop nobody has asked to stop is just running"
11788        );
11789
11790        stop.stop();
11791        assert!(
11792            stop.finishing(),
11793            "a stop asked for mid-run has not landed until the run is settled"
11794        );
11795
11796        stop.busy.store(0, Ordering::SeqCst);
11797        assert!(
11798            !stop.finishing(),
11799            "once the run is settled the stop has landed and there is nothing to finish"
11800        );
11801    }
11802
11803    #[test]
11804    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
11805        let stop = Stop::new();
11806        stop.busy.store(2, Ordering::SeqCst);
11807        stop.stop();
11808        assert!(stop.finishing(), "two runs still in flight");
11809
11810        stop.busy.store(1, Ordering::SeqCst);
11811        assert!(
11812            stop.finishing(),
11813            "one run finished, but a sibling is still working"
11814        );
11815
11816        stop.busy.store(0, Ordering::SeqCst);
11817        assert!(
11818            !stop.finishing(),
11819            "the last run out is what actually lands the stop"
11820        );
11821    }
11822
11823    #[tokio::test]
11824    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
11825        let dir = tempfile::tempdir().unwrap();
11826        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11827        let stop = Stop::new();
11828        stop.stop();
11829
11830        let began = std::time::Instant::now();
11831        tokio::time::timeout(
11832            Duration::from_secs(2),
11833            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11834        )
11835        .await
11836        .expect("a stopped loop must return, not sit out its poll interval")
11837        .expect("the loop's own setup and teardown must not fail");
11838        assert!(
11839            began.elapsed() < opts.poll,
11840            "returned only after {:?}, which is a poll interval, not a stop",
11841            began.elapsed()
11842        );
11843    }
11844
11845    #[tokio::test]
11846    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
11847        let dir = tempfile::tempdir().unwrap();
11848        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11849        let stop = Stop::new();
11850
11851        // Asked for after the loop is already parked on its empty queue, which
11852        // is the case an operator tapping stop on a phone actually hits.
11853        let asker = {
11854            let stop = stop.clone();
11855            tokio::spawn(async move {
11856                tokio::time::sleep(Duration::from_millis(20)).await;
11857                stop.stop();
11858            })
11859        };
11860
11861        let began = std::time::Instant::now();
11862        tokio::time::timeout(
11863            Duration::from_secs(2),
11864            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11865        )
11866        .await
11867        .expect("a stop asked for while idle must wake the wait")
11868        .expect("the loop's own setup and teardown must not fail");
11869        asker.await.unwrap();
11870        assert!(
11871            began.elapsed() < opts.poll,
11872            "returned only after {:?}, so the stop waited on the sleep",
11873            began.elapsed()
11874        );
11875    }
11876
11877    #[tokio::test]
11878    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
11879        let dir = tempfile::tempdir().unwrap();
11880        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11881        let stop = Stop::new();
11882        stop.stop();
11883
11884        tokio::time::timeout(
11885            Duration::from_secs(2),
11886            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11887        )
11888        .await
11889        .expect("a stopped loop must return")
11890        .expect("the loop's own setup and teardown must not fail");
11891
11892        assert!(
11893            home.is_dir(),
11894            "the loop did publish a status file, so its removal is the teardown and not an absence"
11895        );
11896        assert!(
11897            !status_file.exists(),
11898            "a stopped loop clears its status file"
11899        );
11900        assert!(
11901            read_status(&home).is_none(),
11902            "a reader must see no daemon at all, not a heartbeat that merely stopped"
11903        );
11904    }
11905
11906    #[tokio::test]
11907    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
11908        let dir = tempfile::tempdir().unwrap();
11909        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11910
11911        let mut settled = RunState::new(
11912            dir.path().join("repo"),
11913            "main".to_owned(),
11914            "abc1234".to_owned(),
11915            "fixture".to_owned(),
11916            Config::default(),
11917        );
11918        settled.status = RunStatus::Ready;
11919        let run_dir = home.join("runs").join(&settled.id);
11920        std::fs::create_dir_all(&run_dir).unwrap();
11921        std::fs::write(
11922            run_dir.join("run.json"),
11923            serde_json::to_string_pretty(&settled).unwrap(),
11924        )
11925        .unwrap();
11926        let questions = Questions::at(home.join("questions"));
11927        let mut question = ask::Question::new(
11928            settled.id.clone(),
11929            "review".to_owned(),
11930            "reviewer-1".to_owned(),
11931            "Continue?".to_owned(),
11932            String::new(),
11933            Vec::new(),
11934        );
11935        questions.put(&mut question).unwrap();
11936
11937        run_service_worker(
11938            &home,
11939            serde_json::to_value(ServiceWorker {
11940                opts,
11941                queue: queue.root().to_path_buf(),
11942                worktrees_root: worktrees,
11943                operation: "housekeeping".to_owned(),
11944            })
11945            .unwrap(),
11946        )
11947        .await
11948        .unwrap();
11949
11950        assert_eq!(
11951            questions.get(&question.id).unwrap().status,
11952            ask::QuestionStatus::Abandoned,
11953            "the independent housekeeping worker settles ended-run questions"
11954        );
11955    }
11956
11957    #[test]
11958    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
11959        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11960
11961        assert!(
11962            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
11963            "never checked before: due at once"
11964        );
11965
11966        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
11967        assert!(
11968            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
11969            "well inside the interval: not due yet"
11970        );
11971
11972        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
11973        assert!(
11974            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
11975            "exactly at the edge: not yet due, same convention as `clean::due`"
11976        );
11977
11978        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11979        assert!(
11980            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
11981            "past the interval: due again"
11982        );
11983    }
11984
11985    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
11986    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
11987    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
11988    /// and the congestion test below both need, and must not drift apart.
11989    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
11990        let config = dir.join("magi.toml");
11991        // A literal (single-quoted) TOML string, not a basic one: the cache
11992        // path is a Windows path full of backslashes, and a basic string
11993        // would have TOML try to interpret `\U` (from `\Users\...`) as a
11994        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
11995        // `{{ vars.cache }}` rendering documents.
11996        std::fs::write(
11997            &config,
11998            format!(
11999                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
12000                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
12001                cache_dir.display()
12002            ),
12003        )
12004        .unwrap();
12005        Opts {
12006            config: Some(config),
12007            repo: dir.join("repo"),
12008            ..Opts::default()
12009        }
12010    }
12011
12012    #[tokio::test]
12013    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
12014        let dir = tempfile::tempdir().unwrap();
12015        let home = dir.path().join("home");
12016        let cache_dir = dir.path().join("cache");
12017        std::fs::create_dir_all(&cache_dir).unwrap();
12018        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12019        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12020
12021        // Nobody has asked this daemon to stop, which is the ordinary case;
12022        // the skip that a stop buys is asserted by its own test below.
12023        let running = Stop::new();
12024        let mut last_checked = None;
12025        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12026        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
12027            .await;
12028        assert_eq!(
12029            crate::disk::dir_size(&cache_dir),
12030            0,
12031            "over the cap on the first check ever: pruned at once, no idle queue required"
12032        );
12033        assert_eq!(last_checked, Some(t0));
12034
12035        // A fresh oversized file lands, but the next check is not due yet.
12036        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
12037        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
12038        maybe_prune_cache_between_runs(
12039            &opts.repo,
12040            &opts,
12041            &home,
12042            &running,
12043            &mut last_checked,
12044            too_soon,
12045        )
12046        .await;
12047        assert_eq!(
12048            crate::disk::dir_size(&cache_dir),
12049            10,
12050            "too soon since the last check: left alone rather than rescanned every call"
12051        );
12052        assert_eq!(
12053            last_checked,
12054            Some(t0),
12055            "an idle check does not reset the clock"
12056        );
12057
12058        // Once the interval elapses, the same oversized cache is caught again.
12059        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
12060        maybe_prune_cache_between_runs(
12061            &opts.repo,
12062            &opts,
12063            &home,
12064            &running,
12065            &mut last_checked,
12066            due_again,
12067        )
12068        .await;
12069        assert_eq!(
12070            crate::disk::dir_size(&cache_dir),
12071            0,
12072            "due again: pruned back under the cap"
12073        );
12074    }
12075
12076    /// A stop must not queue behind housekeeping. The prune below is a
12077    /// synchronous walk of the whole cache with no await point in it, so a
12078    /// loop that entered it could not get back to its own `stopped()` test
12079    /// until the walk finished - and because no run is in flight at this
12080    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
12081    /// the stop had already landed. The idle branch has always made this same
12082    /// check before reaching `janitor`; the between-runs path makes it too.
12083    #[tokio::test]
12084    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
12085        let dir = tempfile::tempdir().unwrap();
12086        let home = dir.path().join("home");
12087        let cache_dir = dir.path().join("cache");
12088        std::fs::create_dir_all(&cache_dir).unwrap();
12089        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12090        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12091
12092        let stop = Stop::new();
12093        stop.stop();
12094        assert!(
12095            !stop.finishing(),
12096            "no run is in flight at a between-runs boundary, so nothing else \
12097             would tell the operator this stop had not taken effect yet"
12098        );
12099
12100        let mut last_checked = None;
12101        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12102        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
12103            .await;
12104        assert_eq!(
12105            crate::disk::dir_size(&cache_dir),
12106            10,
12107            "over its cap, and due for the first check ever, but a stop outranks \
12108             it: the cap is a standing policy the next start measures again"
12109        );
12110        assert_eq!(
12111            last_checked, None,
12112            "a check that never happened must not claim the interval"
12113        );
12114    }
12115
12116    /// A backlog must not starve cache pruning. The finite cache worker runs
12117    /// independently of queue drain and must not consume any task attempts.
12118    #[tokio::test]
12119    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
12120        let dir = tempfile::tempdir().unwrap();
12121        let cache_dir = dir.path().join("cache");
12122        std::fs::create_dir_all(&cache_dir).unwrap();
12123        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
12124
12125        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
12126        opts.poll = Duration::from_millis(20);
12127        opts.max_attempts = 1_000;
12128
12129        let queue = Queue::at(dir.path().join("queue"));
12130        for i in 0..128 {
12131            let mut task = Task::new(
12132                format!("queued work {i}"),
12133                format!("queued work {i}"),
12134                opts.repo.clone(),
12135                Source::Human,
12136            );
12137            queue.put(&mut task).unwrap();
12138        }
12139
12140        let home = dir.path().join("home");
12141        let worktrees = dir.path().join("wt");
12142        run_service_worker(
12143            &home,
12144            serde_json::to_value(ServiceWorker {
12145                opts,
12146                queue: queue.root().to_path_buf(),
12147                worktrees_root: worktrees,
12148                operation: "cache".to_owned(),
12149            })
12150            .unwrap(),
12151        )
12152        .await
12153        .unwrap();
12154        let after = queue.list();
12155        assert_eq!(after.len(), 128);
12156        assert!(
12157            after
12158                .iter()
12159                .all(|task| task.status.runnable() && task.attempts == 0)
12160        );
12161
12162        assert_eq!(
12163            crate::disk::dir_size(&cache_dir),
12164            0,
12165            "an oversized cache must not be left to grow unboundedly just because the \
12166             queue kept the loop busy the whole time"
12167        );
12168    }
12169
12170    #[test]
12171    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
12172        let dir = tempfile::tempdir().unwrap();
12173        let queue = Queue::at(dir.path().join("queue"));
12174        let questions = Questions::at(dir.path().join("questions"));
12175        let mut task = task();
12176        queue.put(&mut task).unwrap();
12177
12178        let mut task_question = ask::Question::new(
12179            task.id.clone(),
12180            crate::conduct::NODE.to_owned(),
12181            "conduct".to_owned(),
12182            "Which backend?".to_owned(),
12183            String::new(),
12184            Vec::new(),
12185        );
12186        questions.put(&mut task_question).unwrap();
12187        task.block(vec![task_question.id.clone()], None);
12188        queue.put(&mut task).unwrap();
12189
12190        let mut run_question = ask::Question::new(
12191            "20260101-000000-run1".to_owned(),
12192            "review".to_owned(),
12193            "reviewer-1".to_owned(),
12194            "Run question".to_owned(),
12195            String::new(),
12196            Vec::new(),
12197        );
12198        questions.put(&mut run_question).unwrap();
12199
12200        // A question from another node whose `run` happens to equal this
12201        // task's id — the same field, filled in for an unrelated reason. Only
12202        // `crate::conduct::NODE` questions use `run` as a task id; this one
12203        // must never be touched by this reconciliation, even after release.
12204        let mut coincidental = ask::Question::new(
12205            task.id.clone(),
12206            "review".to_owned(),
12207            "reviewer-1".to_owned(),
12208            "Unrelated review question".to_owned(),
12209            String::new(),
12210            Vec::new(),
12211        );
12212        questions.put(&mut coincidental).unwrap();
12213
12214        reconcile_task_questions(&queue, &questions);
12215        assert!(questions.get(&task_question.id).unwrap().status.open());
12216        assert!(questions.get(&run_question.id).unwrap().status.open());
12217        assert!(questions.get(&coincidental.id).unwrap().status.open());
12218
12219        task.release();
12220        queue.put(&mut task).unwrap();
12221        reconcile_task_questions(&queue, &questions);
12222        assert_eq!(
12223            questions.get(&task_question.id).unwrap().status,
12224            ask::QuestionStatus::Abandoned
12225        );
12226        assert!(
12227            questions.get(&run_question.id).unwrap().status.open(),
12228            "run questions remain the run janitor's responsibility"
12229        );
12230        assert!(
12231            questions.get(&coincidental.id).unwrap().status.open(),
12232            "a non-conductor question must not be abandoned just because its \
12233             run id coincides with a task id"
12234        );
12235    }
12236
12237    #[test]
12238    fn a_freshly_started_running_task_is_never_stalled() {
12239        let dir = tempfile::tempdir().unwrap();
12240        let mut t = task();
12241        t.start("run-1".to_owned());
12242        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
12243        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
12244        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
12245    }
12246
12247    #[test]
12248    fn a_long_running_task_with_no_live_daemon_is_stalled() {
12249        let dir = tempfile::tempdir().unwrap();
12250        let mut t = task();
12251        t.start("run-1".to_owned());
12252        t.updated_at = Timestamp::now()
12253            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12254        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
12255        assert_eq!(
12256            stalled_tasks(
12257                &Queue::at(dir.path().join("q")),
12258                dir.path(),
12259                Timestamp::now()
12260            )
12261            .len(),
12262            0,
12263            "the task was never written to this queue"
12264        );
12265    }
12266
12267    #[test]
12268    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
12269        let dir = tempfile::tempdir().unwrap();
12270        let mut t = task();
12271        t.id = "20260903-080340-0167".to_owned();
12272        t.start("20260903-080619-01c2".to_owned());
12273        t.updated_at = Timestamp::now()
12274            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12275
12276        let mut status = Status::new();
12277        status.current = vec![Current {
12278            worker: None,
12279            task: t.id.clone(),
12280            run: "20260903-080619-01c2".to_owned(),
12281        }];
12282        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12283
12284        assert!(
12285            !is_stalled(&t, dir.path(), Timestamp::now()),
12286            "a live daemon's own heartbeat rules out stalled, however long the task has run"
12287        );
12288    }
12289
12290    /// Rewrite a task's `updated_at` on disk directly, bypassing
12291    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
12292    /// a fixture look like it has genuinely been `running` for a while.
12293    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
12294        let path = queue.path_of(id);
12295        let body = std::fs::read_to_string(&path).unwrap();
12296        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
12297        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
12298        v["updated_at"] = serde_json::Value::String(old.to_string());
12299        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
12300    }
12301
12302    #[test]
12303    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
12304        // The realistic `poll()` ordering, not `is_stalled` in isolation:
12305        // `reclaim_orphaned_running` runs first, on every poll, and settles
12306        // any `running` task whose claim it can actually take. For most
12307        // crashes that is immediate - a dead pid is proof enough for
12308        // `sweep_stale_claims` to drop the lock the same tick, and the very
12309        // next claim attempt succeeds. But a lock whose pid cannot be parsed
12310        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
12311        // `sweep_stale_claims`'s own doc), so the lock - and the claim
12312        // failure behind it - can legitimately outlive many polls. This is
12313        // exactly the gap `stalled_tasks` exists to surface well before that
12314        // six-hour sweep would: reclaim leaves the task `running`, and it
12315        // must still reach the conductor as stalled.
12316        let dir = tempfile::tempdir().unwrap();
12317        let queue = Queue::at(dir.path().join("queue"));
12318        let home = dir.path().join("home");
12319
12320        let mut t = task();
12321        t.id = "20260101-000001-lock".to_owned();
12322        t.start("run-1".to_owned());
12323        queue.put(&mut t).unwrap();
12324        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12325        std::fs::write(
12326            dir.path().join("queue").join(format!("{}.lock", t.id)),
12327            "not a pid",
12328        )
12329        .unwrap();
12330
12331        let now = Timestamp::now();
12332        assert!(
12333            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
12334            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
12335             and reclaim must leave the task alone"
12336        );
12337        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
12338
12339        let stalled = stalled_tasks(&queue, &home, now);
12340        assert_eq!(
12341            stalled.len(),
12342            1,
12343            "reclaim's inability to claim it yet must not hide it from the conductor"
12344        );
12345        assert_eq!(stalled[0].id, t.id);
12346    }
12347
12348    #[test]
12349    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
12350        let dir = tempfile::tempdir().unwrap();
12351        crate::run::set_home(dir.path().join("run-home"));
12352        let queue = Queue::at(dir.path().join("queue"));
12353        let home = dir.path().join("home");
12354        let questions = Questions::at(dir.path().join("questions"));
12355
12356        let mut t = task();
12357        t.id = "20260101-000003-dead".to_owned();
12358        t.start("missing-run".to_owned());
12359        queue.put(&mut t).unwrap();
12360        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12361
12362        // This is the real poll ordering: retain the deterministic stalled
12363        // input before a claim proves the owner is gone and reclaims it.
12364        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12365        assert_eq!(
12366            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
12367            [&t.id]
12368        );
12369        assert_eq!(
12370            reclaim_orphaned_running(&queue, 2, &Default::default()),
12371            [t.id.clone()]
12372        );
12373        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12374
12375        // Reclaim drops its guard before conductor decisions are applied, so
12376        // the decision for the captured stalled input has a real write path.
12377        crate::conduct::apply(
12378            &queue,
12379            &questions,
12380            &crate::conduct::Verdict {
12381                decisions: vec![crate::conduct::Decision {
12382                    id: t.id.clone(),
12383                    recovery: Some(crate::conduct::Recovery::Requeue),
12384                    ..crate::conduct::Decision::default()
12385                }],
12386            },
12387        )
12388        .unwrap();
12389        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12390    }
12391
12392    #[test]
12393    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
12394        let dir = tempfile::tempdir().unwrap();
12395        let queue = Queue::at(dir.path().join("queue"));
12396        let home = dir.path().join("home");
12397
12398        let mut fresh = task();
12399        fresh.id = "20260101-000001-aaaa".to_owned();
12400        fresh.start("run-1".to_owned());
12401        queue.put(&mut fresh).unwrap();
12402
12403        let mut old = task();
12404        old.id = "20260101-000002-bbbb".to_owned();
12405        old.start("run-2".to_owned());
12406        queue.put(&mut old).unwrap();
12407        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
12408
12409        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12410        assert_eq!(stalled.len(), 1);
12411        assert_eq!(stalled[0].id, old.id);
12412    }
12413
12414    #[test]
12415    fn queued_and_finished_task_views_partition_by_status() {
12416        let dir = tempfile::tempdir().unwrap();
12417        let queue = Queue::at(dir.path().join("queue"));
12418
12419        let mut queued = task();
12420        queued.id = "20260101-000001-aaaa".to_owned();
12421        queue.put(&mut queued).unwrap();
12422
12423        let mut failed = task();
12424        failed.id = "20260101-000002-bbbb".to_owned();
12425        failed.start("run-1".to_owned());
12426        failed.fail("gate red", 5);
12427        queue.put(&mut failed).unwrap();
12428
12429        let mut held = task();
12430        held.id = "20260101-000003-cccc".to_owned();
12431        held.hold_machine(None);
12432        queue.put(&mut held).unwrap();
12433
12434        let mut running = task();
12435        running.id = "20260101-000004-dddd".to_owned();
12436        running.start("run-2".to_owned());
12437        queue.put(&mut running).unwrap();
12438
12439        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
12440        assert_eq!(queued_ids, [queued.id.clone()]);
12441
12442        let mut finished_ids: Vec<String> =
12443            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
12444        finished_ids.sort_unstable();
12445        let mut want = vec![failed.id.clone(), held.id.clone()];
12446        want.sort_unstable();
12447        assert_eq!(finished_ids, want);
12448    }
12449
12450    #[test]
12451    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
12452        for short in [false, true] {
12453            let dir = tempfile::tempdir().unwrap();
12454            let queue = Queue::at(dir.path().join("queue"));
12455            let questions = ask::Questions::at(dir.path().join("questions"));
12456            let mut running = task();
12457            running.id = "20261013-192213-feb2".into();
12458            running.start("existing-run".into());
12459            queue.put(&mut running).unwrap();
12460            let mut middle = task();
12461            middle.id = "20261013-193611-ca5b".into();
12462            middle.block(
12463                vec![if short {
12464                    "feb2".into()
12465                } else {
12466                    running.id.clone()
12467                }],
12468                None,
12469            );
12470            queue.put(&mut middle).unwrap();
12471            let mut waiting = task();
12472            waiting.id = "20261013-202849-ee37".into();
12473            waiting.block(
12474                vec![if short {
12475                    "ca5b".into()
12476                } else {
12477                    middle.id.clone()
12478                }],
12479                Some("wait for implementation".into()),
12480            );
12481            queue.put(&mut waiting).unwrap();
12482            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
12483            let inv = crate::blockers::Inventory::load(&queue, &questions);
12484            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
12485            assert!(inv.stuck().is_empty());
12486            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12487            assert!(report.quarantined.is_empty());
12488            assert!(report.asked.is_empty());
12489            resolve_blockers(&queue, &questions);
12490            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12491            assert!(questions.list().is_empty());
12492            // Finishing the transitive prerequisite alone does not satisfy
12493            // the task's direct dependency.
12494            running.succeed(CompletionContext::new(
12495                CompletionActor::DaemonSettle,
12496                None,
12497                dir.path(),
12498                &running,
12499            ));
12500            queue.put(&mut running).unwrap();
12501            resolve_blockers(&queue, &questions);
12502            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
12503            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12504            middle = queue.get(&middle.id).unwrap();
12505            middle.succeed(CompletionContext::new(
12506                CompletionActor::DaemonSettle,
12507                None,
12508                dir.path(),
12509                &middle,
12510            ));
12511            queue.put(&mut middle).unwrap();
12512            resolve_blockers(&queue, &questions);
12513            let after = queue.get(&waiting.id).unwrap();
12514            assert_eq!(after.status, TaskStatus::Queued);
12515            assert!(after.blocked_by.is_empty());
12516            assert_eq!(after.instruction, waiting.instruction);
12517        }
12518    }
12519
12520    #[test]
12521    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
12522        for future_schema in [false, true] {
12523            let name = "20261013-193611-ca5b";
12524            let mut future = task();
12525            future.id = name.into();
12526            future.schema = crate::queue::SCHEMA + 1;
12527            let contents = if future_schema {
12528                serde_json::to_string(&future).unwrap()
12529            } else {
12530                "corrupt".into()
12531            };
12532            let dir = tempfile::tempdir().unwrap();
12533            let queue = Queue::at(dir.path().join("queue"));
12534            let questions = ask::Questions::at(dir.path().join("questions"));
12535            let mut waiting = task();
12536            waiting.id = "20261013-202849-ee37".into();
12537            waiting.block(vec!["ca5b".into()], None);
12538            queue.put(&mut waiting).unwrap();
12539            std::fs::write(queue.path_of(name), contents).unwrap();
12540            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
12541            assert!(
12542                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
12543            );
12544            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12545            assert!(report.asked.is_empty());
12546            resolve_blockers(&queue, &questions);
12547            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12548            assert!(questions.list().is_empty());
12549        }
12550        let dir = tempfile::tempdir().unwrap();
12551        let queue = Queue::at(dir.path().join("queue"));
12552        let questions = ask::Questions::at(dir.path().join("questions"));
12553        let mut waiting = task();
12554        waiting.id = "20261013-202849-ee37".into();
12555        waiting.block(vec!["ca5b".into()], None);
12556        queue.put(&mut waiting).unwrap();
12557        let mut done = task();
12558        done.id = "20261013-193611-ca5b".into();
12559        done.succeed(CompletionContext::new(
12560            CompletionActor::Cli,
12561            None,
12562            dir.path(),
12563            &done,
12564        ));
12565        queue.put(&mut done).unwrap();
12566        // An unreadable second match must not disappear from uniqueness
12567        // checks just because Queue::list skips it.
12568        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
12569        assert!(queue.get("ca5b").is_err());
12570        assert_eq!(
12571            crate::queue::dependency(&queue, &questions, "ca5b"),
12572            crate::queue::Dependency::Ambiguous
12573        );
12574        resolve_blockers(&queue, &questions);
12575        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12576        assert!(report.asked.is_empty());
12577        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12578        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
12579    }
12580
12581    #[test]
12582    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
12583        for held in [false, true] {
12584            for question in [false, true] {
12585                for reference in ["ca5b", "20261013-193611-ca5b"] {
12586                    let dir = tempfile::tempdir().unwrap();
12587                    let queue = Queue::at(dir.path().join("queue"));
12588                    let questions = ask::Questions::at(dir.path().join("questions"));
12589                    let mut prerequisite = task();
12590                    prerequisite.id = "20261013-193611-ca5b".into();
12591                    prerequisite.start("existing-run".into());
12592                    queue.put(&mut prerequisite).unwrap();
12593                    let mut waiting = task();
12594                    waiting.id = "20261013-202849-ee37".into();
12595                    if held {
12596                        waiting.hold_machine(Some("waiting for separate consent".into()));
12597                    }
12598                    queue.put(&mut waiting).unwrap();
12599                    let reason = "Deleting saved data requires separate owner consent";
12600                    crate::conduct::apply(
12601                        &queue,
12602                        &questions,
12603                        &crate::conduct::Verdict {
12604                            decisions: vec![crate::conduct::Decision {
12605                                id: waiting.id.clone(),
12606                                blocked_by: vec![reference.into()],
12607                                question: question.then(|| "May the saved data be deleted?".into()),
12608                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
12609                                reason: Some(reason.into()),
12610                                ..crate::conduct::Decision::default()
12611                            }],
12612                        },
12613                    )
12614                    .unwrap();
12615                    let before = queue.get(&waiting.id).unwrap();
12616                    if question {
12617                        assert_eq!(before.status, TaskStatus::Blocked);
12618                        let q = questions.get(&before.blocked_by[0]).unwrap();
12619                        assert_eq!(q.summary, "May the saved data be deleted?");
12620                        assert!(q.status.open());
12621                    } else {
12622                        assert_eq!(before.status, TaskStatus::Held);
12623                        let recorded_reason = before.hold_reason.as_deref().unwrap();
12624                        assert!(recorded_reason.starts_with(reason));
12625                        if held {
12626                            assert!(recorded_reason.contains("waiting for separate consent"));
12627                        }
12628                    }
12629                    prerequisite.succeed(CompletionContext::new(
12630                        CompletionActor::DaemonSettle,
12631                        None,
12632                        dir.path(),
12633                        &prerequisite,
12634                    ));
12635                    queue.put(&mut prerequisite).unwrap();
12636                    resolve_blockers(&queue, &questions);
12637                    let after = queue.get(&waiting.id).unwrap();
12638                    assert_eq!(after.status, before.status);
12639                    assert_eq!(after.blocked_by, before.blocked_by);
12640                    assert_eq!(after.hold_reason, before.hold_reason);
12641                    assert_eq!(after.instruction, waiting.instruction);
12642                    if question {
12643                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
12644                    }
12645                    assert!(
12646                        queue.next_runnable().is_none(),
12647                        "dependency completion is not consent"
12648                    );
12649                }
12650            }
12651        }
12652    }
12653
12654    #[test]
12655    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
12656        let dir = tempfile::tempdir().unwrap();
12657        let queue = Queue::at(dir.path().join("queue"));
12658        let questions = ask::Questions::at(dir.path().join("questions"));
12659
12660        let mut dep = task();
12661        dep.id = "20260101-000001-dep0".to_owned();
12662        dep.succeed(CompletionContext::new(
12663            CompletionActor::DaemonSettle,
12664            None,
12665            dir.path(),
12666            &dep,
12667        ));
12668        queue.put(&mut dep).unwrap();
12669
12670        let mut still_going = task();
12671        still_going.id = "20260101-000002-dep1".to_owned();
12672        queue.put(&mut still_going).unwrap();
12673
12674        let mut blocked = task();
12675        blocked.id = "20260101-000003-main".to_owned();
12676        blocked.block(
12677            vec![dep.id.clone(), still_going.id.clone()],
12678            Some("waits on both".to_owned()),
12679        );
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::Blocked,
12688            "one dependency is still outstanding"
12689        );
12690        assert_eq!(after.blocked_by, [still_going.id.clone()]);
12691    }
12692
12693    #[test]
12694    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
12695        let dir = tempfile::tempdir().unwrap();
12696        let queue = Queue::at(dir.path().join("queue"));
12697        let questions = ask::Questions::at(dir.path().join("questions"));
12698
12699        let mut q = crate::ask::Question::new(
12700            "20260101-000001-main".to_owned(),
12701            crate::conduct::NODE.to_owned(),
12702            "conduct".to_owned(),
12703            "Which backend?".to_owned(),
12704            String::new(),
12705            Vec::new(),
12706        );
12707        questions.put(&mut q).unwrap();
12708        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
12709            .unwrap();
12710        questions.put(&mut q).unwrap();
12711
12712        let mut blocked = task();
12713        blocked.id = "20260101-000001-main".to_owned();
12714        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
12715        queue.put(&mut blocked).unwrap();
12716
12717        resolve_blockers(&queue, &questions);
12718
12719        let after = queue.get(&blocked.id).unwrap();
12720        assert_eq!(
12721            after.status,
12722            TaskStatus::Queued,
12723            "the only blocker resolved"
12724        );
12725        assert_eq!(after.answers.len(), 1);
12726        assert_eq!(after.answers[0].question, "Which backend?");
12727        assert_eq!(after.answers[0].answer, "SQLite");
12728
12729        // And the run this task starts next is told about it.
12730        let instruction = instruction_for(&after);
12731        assert!(instruction.contains("Which backend?"));
12732        assert!(instruction.contains("SQLite"));
12733    }
12734
12735    #[test]
12736    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
12737        let dir = tempfile::tempdir().unwrap();
12738        let queue = Queue::at(dir.path().join("queue"));
12739        let questions = ask::Questions::at(dir.path().join("questions"));
12740
12741        let mut q = crate::ask::Question::new(
12742            "20260101-000001-main".to_owned(),
12743            crate::conduct::NODE.to_owned(),
12744            "conduct".to_owned(),
12745            "Is the setup done?".to_owned(),
12746            String::new(),
12747            Vec::new(),
12748        );
12749        q.abandon("no answer within 60s of asking");
12750        questions.put(&mut q).unwrap();
12751
12752        let mut blocked = task();
12753        blocked.id = "20260101-000001-main".to_owned();
12754        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
12755        queue.put(&mut blocked).unwrap();
12756
12757        resolve_blockers(&queue, &questions);
12758
12759        let after = queue.get(&blocked.id).unwrap();
12760        assert_eq!(
12761            after.status,
12762            TaskStatus::Held,
12763            "never left blocked on nothing"
12764        );
12765        assert!(!after.operator_held(), "a machine hold, for triage");
12766        assert!(
12767            after
12768                .hold_reason
12769                .as_deref()
12770                .unwrap_or_default()
12771                .contains("went unanswered")
12772        );
12773    }
12774
12775    #[test]
12776    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
12777        // Reproduces the reported bug (task 3958): a task held out of
12778        // attempts, blocked on a `crate::conduct` follow-up question, must
12779        // come back `held` once that question is answered - never `queued`,
12780        // whatever the answer said - or it silently re-enters the
12781        // competition queue with its attempts already exhausted.
12782        let dir = tempfile::tempdir().unwrap();
12783        let queue = Queue::at(dir.path().join("queue"));
12784        let questions = ask::Questions::at(dir.path().join("questions"));
12785
12786        let mut q = crate::ask::Question::new(
12787            "20260101-000001-main".to_owned(),
12788            crate::conduct::NODE.to_owned(),
12789            "conduct".to_owned(),
12790            "How should this be handled?".to_owned(),
12791            String::new(),
12792            Vec::new(),
12793        );
12794        questions.put(&mut q).unwrap();
12795        q.answer(crate::ask::Answer::Text(
12796            "leave it held, a human will look at it later".to_owned(),
12797        ))
12798        .unwrap();
12799        questions.put(&mut q).unwrap();
12800
12801        let mut held = task();
12802        held.id = "20260101-000001-main".to_owned();
12803        held.hold_machine(Some("out of attempts".to_owned()));
12804        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
12805        queue.put(&mut held).unwrap();
12806
12807        resolve_blockers(&queue, &questions);
12808
12809        let after = queue.get(&held.id).unwrap();
12810        assert_eq!(after.status, TaskStatus::Held);
12811        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
12812        assert_eq!(
12813            after.answers[0].answer,
12814            "leave it held, a human will look at it later"
12815        );
12816    }
12817
12818    #[test]
12819    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
12820        let dir = tempfile::tempdir().unwrap();
12821        let queue = Queue::at(dir.path().join("queue"));
12822        let questions = ask::Questions::at(dir.path().join("questions"));
12823        let mut dep = task();
12824        dep.id = "20260101-000001-gone".to_owned();
12825        queue.put(&mut dep).unwrap();
12826        let mut blocked = task();
12827        blocked.id = "20260101-000003-main".to_owned();
12828        blocked.block(vec![dep.id.clone()], None);
12829        queue.put(&mut blocked).unwrap();
12830
12831        // Claimed, so `remove` cannot rewrite it and the resolver must.
12832        let claim = queue.claim(&blocked.id).unwrap();
12833        queue.remove(&dep.id, false, &questions).unwrap();
12834        drop(claim);
12835        resolve_blockers(&queue, &questions);
12836
12837        let after = queue.get(&blocked.id).unwrap();
12838        assert_eq!(after.status, TaskStatus::Queued);
12839        assert!(after.blocked_by.is_empty());
12840    }
12841
12842    #[test]
12843    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
12844        // Reproduces the reported bug: a task blocked on a task id that was
12845        // removed (`magi task rm`, or deleted by hand) can never see that id
12846        // reach `Done`, so the ordinary per-id loop has nothing to notice and
12847        // would otherwise leave the task `blocked` forever with no way for an
12848        // operator to find out why.
12849        let dir = tempfile::tempdir().unwrap();
12850        let queue = Queue::at(dir.path().join("queue"));
12851        let questions = ask::Questions::at(dir.path().join("questions"));
12852
12853        let mut still_going = task();
12854        still_going.id = "20260101-000002-dep1".to_owned();
12855        queue.put(&mut still_going).unwrap();
12856
12857        let mut blocked = task();
12858        blocked.id = "20260101-000003-main".to_owned();
12859        blocked.block(
12860            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
12861            Some("waits on both".to_owned()),
12862        );
12863        queue.put(&mut blocked).unwrap();
12864
12865        resolve_blockers(&queue, &questions);
12866
12867        let after = queue.get(&blocked.id).unwrap();
12868        assert_eq!(
12869            after.status,
12870            TaskStatus::Held,
12871            "a missing dependency must not leave the task blocked forever"
12872        );
12873        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
12874        assert!(after.blocked_by.is_empty());
12875        let reason = after.hold_reason.as_deref().unwrap_or_default();
12876        assert!(
12877            reason.contains("20260101-000001-gone"),
12878            "the missing id must be named so an operator can tell what happened: {reason}"
12879        );
12880        assert!(
12881            reason.contains(&still_going.id),
12882            "the still-valid dependency must not silently vanish from the record: {reason}"
12883        );
12884    }
12885
12886    #[test]
12887    fn instruction_for_is_unchanged_without_any_answers() {
12888        let t = task();
12889        assert_eq!(instruction_for(&t), t.instruction);
12890    }
12891
12892    #[test]
12893    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
12894        let dir = tempfile::tempdir().unwrap();
12895        let q = Queue::at(dir.path().join("queue"));
12896        let src = dir.path().join("shot.png");
12897        std::fs::write(&src, "x").unwrap();
12898        let mut t = task();
12899        q.attach(&mut t, &[src]).unwrap();
12900        let paths = task_attachments(&q, &t).unwrap();
12901        assert_eq!(paths.len(), 1);
12902        assert!(paths[0].is_absolute() && paths[0].is_file());
12903        std::fs::remove_file(&paths[0]).unwrap();
12904        let err = task_attachments(&q, &t).unwrap_err().to_string();
12905        assert!(err.contains("shot.png"), "{err}");
12906    }
12907
12908    #[tokio::test]
12909    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
12910        let dir = tempfile::tempdir().unwrap();
12911        let queue_path = dir.path().join("queue");
12912        let queue = Queue::at(queue_path.clone());
12913        let mut t = task();
12914        t.source = Source::Agent {
12915            run: "originating-chat".into(),
12916            node: crate::queue::CHAT_NODE.into(),
12917        };
12918        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
12919            stage: "config-fetch",
12920            target: "origin/main".into(),
12921        });
12922        record_config_failure(&mut t, &fetch);
12923        t.hold_machine(Some(format!("{fetch:#}")));
12924        let fetch_key = t.chat_notice_due().unwrap();
12925        t.chat_notices.push(fetch_key.clone());
12926        queue.put(&mut t).unwrap();
12927
12928        let queue = Queue::at(queue_path);
12929        let mut t = queue.get(&t.id).unwrap();
12930        let a = dir.path().join("a.toml");
12931        let b = dir.path().join("b.toml");
12932        for (path, text, new_cause) in [
12933            (&a, "[graph", true),
12934            (&a, "[verify", false),
12935            (&a, "[graph]\nimplementers = 'invalid-type'", true),
12936            (&b, "[graph]\nimplementers = 'invalid-type'", true),
12937        ] {
12938            t.release_operator("test", None);
12939            std::fs::write(path, text).unwrap();
12940            let error = Config::discover_fetched(dir.path(), Some(path))
12941                .await
12942                .unwrap_err();
12943            record_config_failure(&mut t, &error);
12944            t.hold_machine(Some(format!("{error:#}")));
12945            let due = t.chat_notice_due();
12946            assert_eq!(due.is_some(), new_cause, "{error:#}");
12947            if let Some(key) = due {
12948                assert_ne!(key, fetch_key);
12949                t.chat_notices.push(key);
12950            }
12951        }
12952        t.succeed(CompletionContext::new(
12953            CompletionActor::DaemonSettle,
12954            None,
12955            dir.path(),
12956            &t,
12957        ));
12958        assert_eq!(
12959            t.chat_notice_due(),
12960            Some(format!(
12961                "done:{}",
12962                t.completion_history.last().unwrap().occurrence
12963            ))
12964        );
12965    }
12966
12967    #[test]
12968    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
12969        let dir = tempfile::tempdir().unwrap();
12970        let queue_path = dir.path().join("queue");
12971        let queue = Queue::at(queue_path.clone());
12972        let mut t = task();
12973        t.source = crate::queue::Source::Agent {
12974            run: "originating-chat".into(),
12975            node: crate::queue::CHAT_NODE.into(),
12976        };
12977        let a = dir.path().join("a.png");
12978        let b = dir.path().join("b.png");
12979        std::fs::write(&a, "a").unwrap();
12980        std::fs::write(&b, "b").unwrap();
12981        queue.attach(&mut t, &[a, b]).unwrap();
12982        let paths = task_attachments(&queue, &t).unwrap();
12983        for path in &paths {
12984            std::fs::remove_file(path).unwrap();
12985        }
12986        let missing = task_attachments(&queue, &t).unwrap_err();
12987        t.attempts += 1;
12988        let reason = missing.to_string();
12989        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12990        let first = t.chat_notice_due().expect("first attachment notice");
12991        t.chat_notices.push(first.clone());
12992        queue.put(&mut t).unwrap();
12993
12994        let queue = Queue::at(queue_path.clone());
12995        let mut t = queue.get(&t.id).unwrap();
12996        assert!(t.chat_notice_due().is_none(), "restart does not replay");
12997        t.release_operator("test", None);
12998        t.attempts += 1;
12999        let missing = task_attachments(&queue, &t).unwrap_err();
13000        t.fail_startup_target(
13001            "startup-attachments",
13002            missing.name,
13003            "same missing attachment with regenerated wording",
13004            1,
13005        );
13006        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
13007
13008        std::fs::write(&paths[0], "restored").unwrap();
13009        t.release_operator("test", None);
13010        t.attempts += 1;
13011        let missing = task_attachments(&queue, &t).unwrap_err();
13012        let reason = missing.to_string();
13013        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
13014        let second = t
13015            .chat_notice_due()
13016            .expect("different attachment must notify");
13017        assert_ne!(first, second);
13018        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
13019    }
13020
13021    #[test]
13022    fn resumed_instruction_is_unchanged_without_any_answers() {
13023        let t = task();
13024        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
13025    }
13026
13027    #[test]
13028    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
13029        let mut t = task();
13030        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13031        // The run's own instruction on disk predates the answer: it is the
13032        // plain original text `Runner::start` saved before the operator was
13033        // ever asked anything.
13034        let old = t.instruction.clone();
13035
13036        let refreshed = resumed_instruction(&old, &t);
13037        assert!(refreshed.starts_with(&old), "the original text is kept");
13038        assert!(refreshed.contains("Which backend?"));
13039        assert!(refreshed.contains("SQLite"));
13040    }
13041
13042    #[test]
13043    fn resumed_instruction_keeps_an_original_answers_heading() {
13044        let mut t = task();
13045        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
13046        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13047
13048        let refreshed = resumed_instruction(&t.instruction, &t);
13049
13050        assert!(
13051            refreshed.starts_with(&t.instruction),
13052            "an answers heading in the original instruction is not the appended block"
13053        );
13054        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
13055        assert!(refreshed.contains("Which backend?"));
13056        assert!(refreshed.contains("SQLite"));
13057
13058        let repeated = resumed_instruction(&refreshed, &t);
13059        assert_eq!(
13060            repeated, refreshed,
13061            "only the final appended block is refreshed"
13062        );
13063    }
13064
13065    #[test]
13066    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
13067        let mut t = task();
13068        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13069
13070        // A first resume appends the block; a second resume of the same run,
13071        // with no new answer in between, must reproduce exactly the same
13072        // text rather than appending the block a second time.
13073        let once = resumed_instruction(&t.instruction, &t);
13074        let twice = resumed_instruction(&once, &t);
13075        assert_eq!(once, twice);
13076        assert_eq!(once.matches("Which backend?").count(), 1);
13077
13078        // A later answer replaces the block wholesale rather than growing it.
13079        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
13080        let refreshed = resumed_instruction(&once, &t);
13081        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
13082        assert!(refreshed.contains("Which backend?"));
13083        assert!(refreshed.contains("Which cache?"));
13084    }
13085
13086    #[test]
13087    fn prepare_instruction_covers_all_three_starters() {
13088        let mut t = task();
13089        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13090
13091        // Start: a fresh run gets the task text plus every answer so far —
13092        // exactly `instruction_for`.
13093        assert_eq!(
13094            prepare_instruction(&Starter::Start, None, &t),
13095            Some(instruction_for(&t))
13096        );
13097
13098        // Resume: the run's prior instruction is refreshed with the answer,
13099        // not discarded and not left stale.
13100        let old = t.instruction.clone();
13101        assert_eq!(
13102            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
13103            Some(resumed_instruction(&old, &t))
13104        );
13105
13106        // Review: a review-only pass builds its own instruction from the
13107        // branch's history in `crate::graph`, with no task statement at all -
13108        // this boundary must leave it alone.
13109        assert_eq!(
13110            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
13111            None
13112        );
13113    }
13114
13115    #[test]
13116    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
13117        assert_eq!(
13118            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
13119            Starter::Review("magi/eba2/A".to_owned())
13120        );
13121    }
13122
13123    #[test]
13124    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
13125        assert_eq!(
13126            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
13127            Starter::Start,
13128            "a vanished review branch must not fall back to resuming the old run either"
13129        );
13130    }
13131
13132    #[test]
13133    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
13134        let mut t = task();
13135        t.start("old-run".to_owned());
13136        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
13137        t.release();
13138        let branch = t.review_branch.take();
13139        assert_eq!(
13140            choose_starter(branch.as_deref(), true, Some("old-run")),
13141            Starter::Review("magi/eba2/A".to_owned()),
13142            "a review wins over resuming the old run"
13143        );
13144    }
13145
13146    #[test]
13147    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
13148        assert_eq!(
13149            choose_starter(None, false, Some("some-run")),
13150            Starter::Resume("some-run".to_owned())
13151        );
13152        assert_eq!(choose_starter(None, false, None), Starter::Start);
13153    }
13154
13155    #[test]
13156    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
13157        let mut released = task();
13158        released.start("stalled-run".to_owned());
13159        released.requeue();
13160        let unfinished = (!released.fresh_start)
13161            .then(|| Some("stalled-run".to_owned()))
13162            .flatten();
13163        assert_eq!(
13164            choose_starter(None, false, unfinished.as_deref()),
13165            Starter::Start,
13166            "release keeps run history but must not resume it"
13167        );
13168        assert_eq!(released.runs, ["stalled-run"]);
13169    }
13170
13171    #[test]
13172    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
13173        let dir = tempfile::tempdir().unwrap();
13174        let queue = Queue::at(dir.path().join("queue"));
13175        let mut state = run_state(RunStatus::Blocked);
13176        state.merge_decision = Some(crate::merge_decision::Decision {
13177            question: "hold-inquiry".into(),
13178            target: crate::merge_decision::Target {
13179                pr: "https://example.test/pull/1".into(),
13180                head: "reviewed-head".into(),
13181                language: "en".into(),
13182            },
13183            choice: land::HOLD.into(),
13184            closed: false,
13185            replacement_run: None,
13186            replacement_pr: None,
13187        });
13188        let mut t = task();
13189        t.start(state.id.clone());
13190        settle_and_diagnose(
13191            &mut t,
13192            Verdict {
13193                status: RunStatus::Blocked,
13194                left_pr: true,
13195                quota_hit: false,
13196                parked: false,
13197                no_viable_candidates: false,
13198            },
13199            "held",
13200            2,
13201            &state,
13202        );
13203        queue.put(&mut t).unwrap();
13204        t.release_operator("chat", None);
13205        t.edit("revised".into(), "revised instruction".into())
13206            .unwrap();
13207        queue.put(&mut t).unwrap();
13208        drop(state);
13209        assert_eq!(
13210            queue
13211                .get(&t.id)
13212                .unwrap()
13213                .decision_effects
13214                .get("hold-inquiry"),
13215            Some(&format!("decision: {}", land::HOLD))
13216        );
13217    }
13218
13219    fn stopped_public_run(status: RunStatus) -> RunState {
13220        let mut state = run_state(status);
13221        state.driver_exited = true;
13222        state.config.graph.land = true;
13223        state.config.graph.review_rounds = 1;
13224        state.reviews = vec![review_round(1)];
13225        state.merge = Some(crate::run::MergeOutcome {
13226            mode: MergeMode::Pr,
13227            ok: false,
13228            detail: "landing stopped".into(),
13229            empty: false,
13230        });
13231        state.pr = Some(crate::run::PrRecord {
13232            url: "https://example.test/pull/1".into(),
13233            number: 1,
13234            state: "open".into(),
13235            checks: "red".into(),
13236            round: 1,
13237            rounds: 1,
13238            red_at_merge: Vec::new(),
13239        });
13240        state
13241    }
13242
13243    #[test]
13244    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
13245        for status in [RunStatus::Blocked, RunStatus::Gating] {
13246            let home = tempfile::tempdir().unwrap();
13247            let mut state = stopped_public_run(status);
13248            state.save_under(home.path()).unwrap();
13249            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
13250            assert!(!exhausted_review_budget(&state));
13251            let mut task = held_task_with(&state.id);
13252            task.release();
13253            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13254            assert_eq!(
13255                choose_starter(None, false, unfinished.as_deref()),
13256                Starter::Resume(state.id.clone())
13257            );
13258            let question = action_question(&state.id, resume_action(&state.id));
13259            assert_eq!(
13260                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13261                    state.clone()
13262                )),
13263                ActionDecision::Resume(state.id.clone())
13264            );
13265            // The control-plane command uses this same preflight before pinning.
13266            assert_eq!(
13267                crate::resume::validate(home.path(), &state.id).unwrap().id,
13268                state.id
13269            );
13270            let queue = Queue::at(home.path().join("queue"));
13271            let mut controlled = Task::new(
13272                "resume land".into(),
13273                state.instruction.clone(),
13274                state.repo.clone(),
13275                Source::Agent {
13276                    run: "talk".into(),
13277                    node: crate::queue::CHAT_NODE.into(),
13278                },
13279            );
13280            controlled.runs.push(state.id.clone());
13281            controlled.hold_machine(Some("land stopped".into()));
13282            queue.put(&mut controlled).unwrap();
13283            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13284            assert_eq!(resumed.status, TaskStatus::Queued);
13285            assert_eq!(
13286                resumed.resume_override.unwrap().pinned_run,
13287                Some(state.id.clone())
13288            );
13289            assert_eq!(resumed.attempts, 0);
13290        }
13291    }
13292
13293    #[test]
13294    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
13295        for review_rounds in [0, 1] {
13296            let home = tempfile::tempdir().unwrap();
13297            let mut state = run_state(RunStatus::Blocked);
13298            state.config.graph.review_rounds = review_rounds;
13299            if review_rounds > 0 {
13300                let mut review = review_round(1);
13301                review.clean = true;
13302                state.reviews = vec![review];
13303            }
13304            state.gate_ran = true;
13305            state.gate = vec![crate::run::CommandOutcome {
13306                command: "verify".into(),
13307                code: Some(1),
13308                output_tail: "gate failed after repair budget exhausted".into(),
13309                duration_ms: 0,
13310                resource_blocked: false,
13311                ..Default::default()
13312            }];
13313            state.save_under(home.path()).unwrap();
13314            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13315            assert!(exhausted_review_budget(&state));
13316            let mut task = held_task_with(&state.id);
13317            task.release();
13318            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
13319            let question = action_question(&state.id, resume_action(&state.id));
13320            assert_ne!(
13321                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13322                    state.clone()
13323                )),
13324                ActionDecision::Resume(state.id.clone())
13325            );
13326            let error = crate::resume::validate(home.path(), &state.id)
13327                .unwrap_err()
13328                .to_string();
13329            assert!(!error.contains("review budget exhausted"), "{error}");
13330            assert!(
13331                error.contains(if review_rounds == 0 {
13332                    "review is disabled"
13333                } else {
13334                    "gate already ran"
13335                }),
13336                "{error}"
13337            );
13338
13339            // An unexecuted gate still has work to do with or without reviews.
13340            state.gate_ran = false;
13341            state.gate.clear();
13342            assert!(!exhausted_review_budget(&state));
13343            assert_eq!(
13344                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
13345                Some(state.id)
13346            );
13347        }
13348    }
13349
13350    #[test]
13351    fn resource_blocked_verification_resumes_the_same_run() {
13352        for (kind, stage) in [
13353            ("cache", "clean"),
13354            ("coordination", "clean"),
13355            ("cache", "review-e2e"),
13356            ("coordination", "no-reviews"),
13357            ("coordination", "handoff"),
13358        ] {
13359            let home = tempfile::tempdir().unwrap();
13360            let mut state = run_state(RunStatus::Blocked);
13361            state.config.graph.review_rounds = 1;
13362            let mut review = review_round(1);
13363            review.clean = true;
13364            state.reviews = vec![review];
13365            if stage == "review-e2e" {
13366                let review = &mut state.reviews[0];
13367                review.clean = false;
13368                review.blocking = 1;
13369                review.e2e = vec![crate::run::CommandOutcome {
13370                    command: "verify".into(),
13371                    code: None,
13372                    output_tail: "resource wait expired".into(),
13373                    duration_ms: 0,
13374                    resource_blocked: true,
13375                    ..Default::default()
13376                }];
13377            } else if stage == "no-reviews" {
13378                state.config.graph.review_rounds = 0;
13379                state.reviews.clear();
13380            } else if stage == "handoff" {
13381                // A completed final verification can hand off to the gate
13382                // even when the review still carries contested findings.
13383                let review = &mut state.reviews[0];
13384                review.clean = false;
13385                review.blocking = 1;
13386                review.e2e = vec![crate::run::CommandOutcome {
13387                    command: "verify".into(),
13388                    code: Some(0),
13389                    output_tail: String::new(),
13390                    duration_ms: 0,
13391                    resource_blocked: false,
13392                    ..Default::default()
13393                }];
13394            }
13395            state.gate_ran = false;
13396            state.resource_block = Some(crate::run::ResourceBlock {
13397                cause: crate::run::ResourceBlockCause::Other,
13398                node: if stage == "review-e2e" {
13399                    "review"
13400                } else {
13401                    "gate"
13402                }
13403                .into(),
13404                kind: kind.into(),
13405                detail: "resource wait expired".into(),
13406                at: jiff::Timestamp::now(),
13407            });
13408            state.save_under(home.path()).unwrap();
13409            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13410            assert!(!exhausted_review_budget(&state));
13411            let mut task = held_task_with(&state.id);
13412            task.release();
13413            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13414            assert_eq!(
13415                choose_starter(None, false, unfinished.as_deref()),
13416                Starter::Resume(state.id.clone())
13417            );
13418            let question = action_question(&state.id, resume_action(&state.id));
13419            assert_eq!(
13420                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13421                    state.clone()
13422                )),
13423                ActionDecision::Resume(state.id.clone())
13424            );
13425            assert_eq!(
13426                crate::resume::validate(home.path(), &state.id).unwrap().id,
13427                state.id
13428            );
13429            let queue = Queue::at(home.path().join("queue"));
13430            let mut controlled = Task::new(
13431                "resume verification".into(),
13432                state.instruction.clone(),
13433                state.repo.clone(),
13434                Source::Agent {
13435                    run: "talk".into(),
13436                    node: crate::queue::CHAT_NODE.into(),
13437                },
13438            );
13439            controlled.runs.push(state.id.clone());
13440            controlled.hold_machine(Some("verification resource unavailable".into()));
13441            queue.put(&mut controlled).unwrap();
13442            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13443            assert_eq!(resumed.status, TaskStatus::Queued);
13444            assert_eq!(
13445                resumed.resume_override.unwrap().pinned_run,
13446                Some(state.id.clone())
13447            );
13448            assert_eq!(resumed.attempts, 0);
13449
13450            // A genuinely unresolved final review still exhausts the budget.
13451            state.config.graph.review_rounds = 1;
13452            let mut unresolved = review_round(1);
13453            unresolved.blocking = 1;
13454            state.reviews = vec![unresolved];
13455            state.resource_block = None;
13456            state.save_under(home.path()).unwrap();
13457            assert!(exhausted_review_budget(&state));
13458            assert!(crate::resume::validate(home.path(), &state.id).is_err());
13459        }
13460    }
13461
13462    #[tokio::test]
13463    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
13464        if !crate::standalone_test(
13465            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
13466        ) {
13467            return;
13468        }
13469        let home = tempfile::tempdir().unwrap();
13470        let mut owner = stopped_public_run(RunStatus::Blocked);
13471        owner.save_under(home.path()).unwrap();
13472        let history = vec![owner.id.clone()];
13473        let repo = owner.repo.clone();
13474        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
13475        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
13476        let initial =
13477            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
13478        assert!(
13479            initial.is_pending(),
13480            "a busy record must not hold or resume the task"
13481        );
13482        owner.retired_to = Some("20260101-000001-bbbb".into());
13483        owner.save_under(home.path()).unwrap();
13484        drop(lock);
13485        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
13486            .await
13487            .expect("ownership lock released")
13488            .expect("read settled owner");
13489        assert!(
13490            result.is_none(),
13491            "the retired owner must not be resumed from a stale read"
13492        );
13493    }
13494
13495    #[tokio::test]
13496    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
13497        if !crate::standalone_test(
13498            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
13499        ) {
13500            return;
13501        }
13502        let home = tempfile::tempdir().unwrap();
13503        let mut owner = stopped_public_run(RunStatus::Blocked);
13504        let repo = tempfile::tempdir().unwrap();
13505        crate::git::git(repo.path(), &["init"]).await.unwrap();
13506        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
13507        owner.id = "20260101-000000-aaaa".into();
13508        owner.save_under(home.path()).unwrap();
13509        let mut successor = run_state(RunStatus::Blocked);
13510        successor.id = "20260101-000001-bbbb".into();
13511        successor.save_under(home.path()).unwrap();
13512        let runs = vec![owner.id.clone(), successor.id.clone()];
13513        assert_eq!(
13514            public_resume_owner(home.path(), &runs, &owner.repo)
13515                .await
13516                .unwrap()
13517                .unwrap()
13518                .id,
13519            owner.id
13520        );
13521        let subdir = owner.repo.join("nested");
13522        std::fs::create_dir(&subdir).unwrap();
13523        assert_eq!(
13524            public_resume_owner(home.path(), &runs, &subdir)
13525                .await
13526                .unwrap()
13527                .unwrap()
13528                .id,
13529            owner.id
13530        );
13531        #[cfg(unix)]
13532        {
13533            let alias = home.path().join("repo-alias");
13534            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
13535            assert_eq!(
13536                public_resume_owner(home.path(), &runs, &alias.join("nested"))
13537                    .await
13538                    .unwrap()
13539                    .unwrap()
13540                    .id,
13541                owner.id
13542            );
13543        }
13544        let different = tempfile::tempdir().unwrap();
13545        crate::git::git(different.path(), &["init"]).await.unwrap();
13546        assert!(
13547            public_resume_owner(home.path(), &runs, different.path())
13548                .await
13549                .is_err()
13550        );
13551        std::fs::remove_file(
13552            home.path()
13553                .join("runs")
13554                .join(&successor.id)
13555                .join("run.json"),
13556        )
13557        .unwrap();
13558        assert!(
13559            public_resume_owner(home.path(), &runs, &owner.repo)
13560                .await
13561                .is_err()
13562        );
13563    }
13564
13565    #[test]
13566    fn an_ordinary_release_keeps_a_resumable_run_available() {
13567        let mut released = task();
13568        released.start("stalled-run".to_owned());
13569        released.release();
13570        let unfinished = (!released.fresh_start)
13571            .then(|| Some("stalled-run".to_owned()))
13572            .flatten();
13573        assert_eq!(
13574            choose_starter(None, false, unfinished.as_deref()),
13575            Starter::Resume("stalled-run".to_owned()),
13576            "manual release must preserve the normal resume path"
13577        );
13578    }
13579
13580    #[test]
13581    fn resume_refusals_explain_admission_without_changing_task_or_run() {
13582        use crate::handover::{ResumeRefusal, resume_refusal_under};
13583        let home = tempfile::tempdir().unwrap();
13584        let mut exhausted = run_state(RunStatus::Blocked);
13585        exhausted.driver_exited = true;
13586        exhausted.config.graph.review_rounds = 3;
13587        exhausted.reviews = (1..=3).map(review_round).collect();
13588        for refusal in [
13589            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
13590            ResumeRefusal::Status(RunStatus::Ready),
13591            ResumeRefusal::Released("20261022-000000-aaaa".into()),
13592            ResumeRefusal::Retired("retirement-successor".into()),
13593            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
13594        ] {
13595            let mut state = exhausted.clone();
13596            let expected = match refusal {
13597                ResumeRefusal::Status(_) => {
13598                    state.status = RunStatus::Ready;
13599                    "status `ready`"
13600                }
13601                ResumeRefusal::Released(ref target) => {
13602                    state.released_to = Some(target.clone());
13603                    "execution was released"
13604                }
13605                ResumeRefusal::Retired(ref target) => {
13606                    state.retired_to = Some(target.clone());
13607                    "execution was retired"
13608                }
13609                ResumeRefusal::OwnershipTransferred(ref target) => {
13610                    state.pr_taken_over_by = Some(target.clone());
13611                    "PR ownership was transferred"
13612                }
13613                _ => "review budget exhausted (3/3 rounds used)",
13614            };
13615            assert_eq!(
13616                resume_refusal_under(&state, Some(home.path())),
13617                Some(refusal.clone())
13618            );
13619            assert_eq!(
13620                refusal.successor(),
13621                state
13622                    .released_to
13623                    .as_deref()
13624                    .or(state.retired_to.as_deref())
13625                    .or(state.pr_taken_over_by.as_deref())
13626            );
13627            state.save_under(home.path()).unwrap();
13628            let queue = Queue::at(home.path().join("queue"));
13629            let mut task = Task::new(
13630                "retained implementation".into(),
13631                state.instruction.clone(),
13632                state.repo.clone(),
13633                Source::Agent {
13634                    run: "talk".into(),
13635                    node: crate::queue::CHAT_NODE.into(),
13636                },
13637            );
13638            task.runs.push(state.id.clone());
13639            task.hold_machine(Some("stopped".into()));
13640            queue.put(&mut task).unwrap();
13641            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
13642            let before_run = serde_json::to_value(&state).unwrap();
13643            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
13644                .unwrap_err()
13645                .to_string();
13646            assert!(error.contains(expected), "{error}");
13647            assert!(!error.contains("only a stalled or blocked"), "{error}");
13648            if matches!(refusal, ResumeRefusal::Status(_)) {
13649                assert!(
13650                    error.contains("is final; there is nothing left to resume"),
13651                    "{error}"
13652                );
13653            }
13654            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
13655                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
13656                assert!(error.contains("review-only successor with a new review budget"));
13657                assert!(error.contains("does not resume this run"));
13658            }
13659            for target in [
13660                &state.released_to,
13661                &state.retired_to,
13662                &state.pr_taken_over_by,
13663            ]
13664            .into_iter()
13665            .flatten()
13666            {
13667                let short = if state.retired_to.as_ref() == Some(target) {
13668                    target.as_str()
13669                } else {
13670                    crate::run::short_of(target)
13671                };
13672                assert!(
13673                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
13674                    "{error}"
13675                );
13676                if short != target {
13677                    assert!(!error.contains(target), "full successor id leaked: {error}");
13678                }
13679            }
13680            assert_eq!(
13681                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
13682                before_task
13683            );
13684            assert_eq!(
13685                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
13686                    .unwrap(),
13687                before_run
13688            );
13689            let question = action_question(&state.id, resume_action(&state.id));
13690            for phrases in [&PHRASES_EN, &PHRASES_JA] {
13691                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
13692                    RunState::load_under(id, home.path())
13693                });
13694                let ActionDecision::Refuse(detail) = decision else {
13695                    panic!(
13696                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
13697                        state.id,
13698                        home.path().display()
13699                    );
13700                };
13701                assert!(detail.contains(expected), "{detail}");
13702            }
13703        }
13704        // Preserve predicate ordering, while keeping every recorded destination visible.
13705        exhausted.status = RunStatus::Ready;
13706        exhausted.released_to = Some("released".into());
13707        exhausted.retired_to = Some("retired".into());
13708        exhausted.pr_taken_over_by = Some("owner".into());
13709        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
13710        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
13711        let detail = reason.diagnostic(&exhausted);
13712        for target in ["released", "retired", "owner"] {
13713            assert!(detail.contains(&format!("magi show {target}")));
13714        }
13715    }
13716
13717    #[test]
13718    fn resume_action_ignores_question_checkpoints_in_another_home() {
13719        crate::run::pin_test_home();
13720        let home = tempfile::tempdir().unwrap();
13721        let mut state = run_state(RunStatus::Blocked);
13722        // The private directory reserves this fixture's identity even while
13723        // other tests write questions into the process-wide store.
13724        state.id = format!(
13725            "resume-context-{}",
13726            home.path().file_name().unwrap().to_str().unwrap()
13727        );
13728        state.driver_exited = true;
13729        state.config.graph.review_rounds = 1;
13730        state.reviews = vec![review_round(1)];
13731        state.save_under(home.path()).unwrap();
13732        let task = held_task_with(&state.id);
13733        let answer = action_question(&state.id, resume_action(&state.id));
13734        let mut checkpoint = approval_question(&state.id);
13735        let foreign = Questions::open();
13736        foreign.put(&mut checkpoint).unwrap();
13737        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
13738        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13739            RunState::load_under(id, home.path())
13740        });
13741        let matching: Vec<_> = foreign
13742            .list()
13743            .into_iter()
13744            .filter(|q| q.run == state.id && q.status.open())
13745            .collect();
13746        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
13747        assert!(
13748            matches!(decision, ActionDecision::Refuse(_)),
13749            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
13750            state.id,
13751            home.path().display(),
13752            crate::run::test_home().display()
13753        );
13754        assert_eq!(
13755            refusal,
13756            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
13757        );
13758        let local = Questions::at(home.path().join("questions"));
13759        for status in [
13760            ask::QuestionStatus::Open,
13761            ask::QuestionStatus::Answered,
13762            ask::QuestionStatus::Abandoned,
13763        ] {
13764            let mut question = checkpoint.clone();
13765            match status {
13766                ask::QuestionStatus::Open => {}
13767                ask::QuestionStatus::Answered => {
13768                    question
13769                        .answer(ask::Answer::Choice(question.choices[0].clone()))
13770                        .unwrap();
13771                }
13772                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
13773            }
13774            local.put(&mut question).unwrap();
13775            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13776                RunState::load_under(id, home.path())
13777            });
13778            if status.open() {
13779                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
13780            } else {
13781                assert!(
13782                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
13783                    "status={status:?}, decision={decision:?}"
13784                );
13785            }
13786        }
13787    }
13788
13789    #[test]
13790    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
13791        let home = tempfile::tempdir().unwrap();
13792        let mut state = run_state(RunStatus::Stalled);
13793        state.id = format!(
13794            "resume-driver-{}",
13795            home.path().file_name().unwrap().to_str().unwrap()
13796        );
13797        state.driver_claimed = Some(false);
13798        state.save_under(home.path()).unwrap();
13799        let task = held_task_with(&state.id);
13800        let question = action_question(&state.id, resume_action(&state.id));
13801        let decide = || {
13802            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
13803                RunState::load_under(id, home.path())
13804            })
13805        };
13806        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
13807        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
13808        assert_eq!(
13809            decide(),
13810            ActionDecision::Refuse("run already has a live driver".into())
13811        );
13812        drop(lease);
13813        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
13814    }
13815
13816    #[test]
13817    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
13818        let home = tempfile::tempdir().unwrap();
13819        let mut state = run_state(RunStatus::Blocked);
13820        state.driver_exited = true;
13821        state.config.graph.review_rounds = 1;
13822        state.reviews = vec![review_round(1)];
13823        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
13824        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
13825            let mut saved = state.clone();
13826            match checkpoint {
13827                "publication" => saved.pr_publication_pending = true,
13828                "approval" => {
13829                    saved.land_approval = Some(crate::run::LandApproval {
13830                        question: "approval".into(),
13831                        head: "head".into(),
13832                    })
13833                }
13834                "armed" => saved.land_armed_head = Some("head".into()),
13835                "landing" => saved.status = RunStatus::Landing,
13836                _ => {
13837                    let mut question = ask::Question::new(
13838                        saved.id.clone(),
13839                        "review".into(),
13840                        "review-1".into(),
13841                        "continue?".into(),
13842                        String::new(),
13843                        vec!["continue".into()],
13844                    );
13845                    ask::Questions::at(home.path().join("questions"))
13846                        .put(&mut question)
13847                        .unwrap();
13848                }
13849            }
13850            saved.save_under(home.path()).unwrap();
13851            assert!(
13852                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
13853                "{checkpoint}"
13854            );
13855            assert!(
13856                crate::resume::validate(home.path(), &saved.id).is_ok(),
13857                "{checkpoint}"
13858            );
13859        }
13860    }
13861
13862    #[test]
13863    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
13864        let mut state = run_state(RunStatus::Blocked);
13865        state.config.graph.review_rounds = 3;
13866        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
13867        assert!(exhausted_review_budget(&state));
13868
13869        // One round still unused: resuming can still ask a reviewer something.
13870        state.reviews.pop();
13871        assert!(!exhausted_review_budget(&state));
13872
13873        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
13874        // count: only a `Blocked` run re-enters the review loop on resume.
13875        let mut stalled = run_state(RunStatus::Stalled);
13876        stalled.config.graph.review_rounds = 1;
13877        stalled.reviews = vec![review_round(1)];
13878        assert!(!exhausted_review_budget(&stalled));
13879    }
13880
13881    fn review_round(round: usize) -> crate::run::ReviewRound {
13882        crate::run::ReviewRound {
13883            round,
13884            head: "deadbeef".to_owned(),
13885            verified_head: None,
13886            verified_at: None,
13887            reviews: Vec::new(),
13888            e2e: Vec::new(),
13889            verify_retried: false,
13890            e2e_deferred: false,
13891            e2e_defer_reason: None,
13892            fix: None,
13893            blocking: 0,
13894            answered: 1,
13895            expected: 1,
13896            clean: false,
13897            progressed: true,
13898            vote_split: false,
13899            reconsideration: Vec::new(),
13900            verdict: None,
13901        }
13902    }
13903
13904    #[test]
13905    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
13906        let mut run = RunState::new(
13907            PathBuf::from("/repo"),
13908            "main".to_owned(),
13909            "abc1234def".to_owned(),
13910            "add retries".to_owned(),
13911            Config::default(),
13912        );
13913        run.status = RunStatus::Judging;
13914        run.parked = true;
13915        let mut task = Task::new(
13916            "add retries".to_owned(),
13917            "add retries".to_owned(),
13918            PathBuf::from("/repo"),
13919            crate::queue::Source::Human,
13920        );
13921        task.status = TaskStatus::Failed;
13922        task.runs = vec![run.id.clone()];
13923        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
13924        assert!(with(&task, &run), "parked after judging is the case");
13925        let mut parked_task = task.clone();
13926        parked_task.status = TaskStatus::Parked;
13927        assert!(with(&parked_task, &run), "the Parked status is the case");
13928
13929        let mut not_parked = run.clone();
13930        not_parked.parked = false;
13931        not_parked.status = RunStatus::Stalled;
13932        assert!(!with(&task, &not_parked), "a stall is the conductor's");
13933
13934        let mut fresh = task.clone();
13935        fresh.fresh_start = true;
13936        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
13937
13938        let mut review = task.clone();
13939        review.review_branch = Some("magi/x/A".to_owned());
13940        assert!(!with(&review, &run), "review is ranked before resume");
13941
13942        let mut held = task.clone();
13943        held.status = TaskStatus::Held;
13944        assert!(!with(&held, &run), "a hold stays visible to the conductor");
13945
13946        let mut released = run.clone();
13947        released.released_to = Some("20260901-000000-new1".to_owned());
13948        assert!(!with(&task, &released), "nothing left to resume into");
13949
13950        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
13951            "unreadable"
13952        )));
13953    }
13954
13955    #[test]
13956    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
13957        let mut released = RunState::new(
13958            PathBuf::from("/repo"),
13959            "main".to_owned(),
13960            "abc1234def".to_owned(),
13961            "add retries".to_owned(),
13962            Config::default(),
13963        );
13964        released.status = RunStatus::Blocked;
13965        assert_eq!(
13966            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13967            Some(released.id.clone())
13968        );
13969        released.released_to = Some("20260901-000000-new1".to_owned());
13970        assert_eq!(
13971            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13972            None,
13973            "there is nothing left to resume it into"
13974        );
13975    }
13976
13977    #[test]
13978    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
13979        // Mirrors the failure this exists to close: a task's last run ended
13980        // `Blocked` with the review budget spent, `crate::conduct` chose
13981        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
13982        // evidence), and without this check `attempt` would go on treating
13983        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
13984        // review loop iterates zero times over an already-spent budget, so
13985        // the resumed run settles right back to `Blocked` having asked nobody
13986        // anything, and `Requeue`'s promised fresh competition never happens.
13987        let mut exhausted = RunState::new(
13988            PathBuf::from("/repo"),
13989            "main".to_owned(),
13990            "abc1234def".to_owned(),
13991            "add retries".to_owned(),
13992            Config::default(),
13993        );
13994        exhausted.status = RunStatus::Blocked;
13995        exhausted.config.graph.review_rounds = 1;
13996        exhausted.reviews = vec![review_round(1)];
13997
13998        assert_eq!(
13999            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
14000            None,
14001            "an exhausted `Blocked` run must not be offered as resumable"
14002        );
14003
14004        // A `Blocked` run with rounds still unused is genuinely worth
14005        // resuming, and must still be found.
14006        let mut has_budget_left = RunState::new(
14007            PathBuf::from("/repo"),
14008            "main".to_owned(),
14009            "abc1234def".to_owned(),
14010            "add retries".to_owned(),
14011            Config::default(),
14012        );
14013        has_budget_left.status = RunStatus::Blocked;
14014        has_budget_left.config.graph.review_rounds = 3;
14015        has_budget_left.reviews = vec![review_round(1)];
14016
14017        assert_eq!(
14018            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
14019                Ok(has_budget_left.clone())
14020            }),
14021            Some(has_budget_left.id.clone())
14022        );
14023    }
14024
14025    #[test]
14026    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
14027        let mut run = RunState::new(
14028            PathBuf::from("/repo"),
14029            "main".to_owned(),
14030            "abc1234def".to_owned(),
14031            "add retries".to_owned(),
14032            Config::default(),
14033        );
14034        run.status = RunStatus::Blocked;
14035        run.config.graph.review_rounds = 1;
14036        run.reviews = vec![review_round(1)];
14037        run.pr_publication_pending = true;
14038        assert_eq!(
14039            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
14040            Some(run.id.clone()),
14041            "a spent review budget must not turn a failed publication into a re-competition"
14042        );
14043    }
14044
14045    #[test]
14046    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
14047        let mut task = Task::new(
14048            "recover work".into(),
14049            "recover work".into(),
14050            PathBuf::from("/repo"),
14051            crate::queue::Source::Human,
14052        );
14053        let mut history = std::collections::BTreeMap::new();
14054        for index in 0..8 {
14055            let mut run = run_state(RunStatus::Blocked);
14056            run.id = format!("20260101-000000-{index:04}");
14057            run.base_commit = format!("upstream-{index}");
14058            // Seven empty newer attempts must not erase the old recovery owner.
14059            if index > 0 {
14060                run.candidates.clear();
14061            }
14062            task.runs.extend([run.id.clone(), run.id.clone()]);
14063            history.insert(run.id.clone(), run);
14064            task.requeue();
14065        }
14066        let check = |task: &Task, starter: &Starter, limit| {
14067            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
14068        };
14069        assert!(
14070            check(&task, &Starter::Start, 8)
14071                .unwrap()
14072                .contains("8 unretired")
14073        );
14074        assert!(check(&task, &Starter::Start, 9).is_none());
14075        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
14076        task.release_operator("owner", None);
14077        assert_eq!(task.attempts, 0);
14078        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14079        assert!(check(&restored, &Starter::Start, 8).is_some());
14080        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
14081        assert!(check(&restored, &Starter::Start, 0).is_none());
14082    }
14083
14084    #[test]
14085    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
14086        let tmp = tempfile::tempdir().unwrap();
14087        let mut task = Task::new(
14088            "recover selected PR".into(),
14089            "preserve implementation".into(),
14090            tmp.path().join("repo"),
14091            crate::queue::Source::Human,
14092        );
14093        let mut failed = run_state(RunStatus::Failed);
14094        failed.id = "20260101-000000-fail".into();
14095        failed.candidates.clear();
14096        failed.prep_complete = Some(false);
14097        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
14098        failed.startup = Some(crate::run::Startup {
14099            kind: "pr-recovery".into(),
14100            branch: Some("selected-public-head".into()),
14101            stage: "worktree-setup".into(),
14102            complete: false,
14103            failure: Some("setup modified a tracked file and failed".into()),
14104        });
14105        // Setup may fail before a candidate is recorded; its dirty worktree
14106        // still needs protection and consumes the independent retained bound.
14107        let worktree = failed.worktree_root().join("under-review");
14108        std::fs::create_dir_all(&worktree).unwrap();
14109        let retained_edit = worktree.join("implementation");
14110        std::fs::write(&retained_edit, "retained setup edit").unwrap();
14111        task.record_startup_failure(crate::run::StartupFailure {
14112            run: failed.id.clone(),
14113            stage: "worktree-setup".into(),
14114        });
14115        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14116        assert!(task.runs.is_empty() && task.passes.is_empty());
14117        assert_eq!(task.attempts, 0);
14118        let starter = Starter::Review("selected-public-head".into());
14119        assert!(
14120            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
14121                .unwrap()
14122                .contains("1 unretired")
14123        );
14124        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
14125        assert!(
14126            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
14127                .unwrap()
14128                .contains("Cannot verify")
14129        );
14130        // Older or mixed writers can link the same reservation in both lists.
14131        let mut mixed = task.clone();
14132        mixed.runs.push(failed.id.clone());
14133        mixed
14134            .startup_failures
14135            .push(task.startup_failures[0].clone());
14136        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
14137        failed.retired_to = Some("verified-recovery-owner".into());
14138        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
14139        assert!(
14140            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
14141                panic!("resuming the existing owner must not allocate a new attempt")
14142            })
14143            .is_none()
14144        );
14145        assert_eq!(
14146            std::fs::read_to_string(retained_edit).unwrap(),
14147            "retained setup edit"
14148        );
14149        assert!(task.runs.is_empty() && task.passes.is_empty());
14150        assert_eq!(task.attempts, 0);
14151    }
14152
14153    #[test]
14154    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
14155        let mut task = Task::new(
14156            "recover work".into(),
14157            "recover work".into(),
14158            PathBuf::from("/repo"),
14159            crate::queue::Source::Human,
14160        );
14161        let mut run = run_state(RunStatus::Superseded);
14162        run.candidates.clear();
14163        task.runs.push(run.id.clone());
14164        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
14165        run.retired_to = Some("authority".into());
14166        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14167        run.retired_to = None;
14168        run.released_to = Some("authority".into());
14169        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14170        assert!(
14171            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
14172                .unwrap()
14173                .contains("Cannot verify")
14174        );
14175        // Resuming an existing owner needs no new inventory or worktree budget.
14176        assert!(
14177            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
14178                panic!("resume must not load historical attempts")
14179            })
14180            .is_none()
14181        );
14182    }
14183
14184    #[test]
14185    fn retired_resume_requires_a_valid_same_repository_authority() {
14186        let mut source = run_state(RunStatus::Blocked);
14187        let mut empty = run_state(RunStatus::Blocked);
14188        empty.retired_to = Some(source.id.clone());
14189        let runs = vec![source.id.clone(), empty.id.clone()];
14190        let resolve = |source: &RunState, empty: &RunState| {
14191            unfinished_run_with(&runs, "fixture", |id| {
14192                if id == source.id {
14193                    Ok(source.clone())
14194                } else if id == empty.id {
14195                    Ok(empty.clone())
14196                } else {
14197                    bail!("unreadable authority")
14198                }
14199            })
14200        };
14201        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
14202        assert_eq!(
14203            choose_starter(None, false, resolve(&source, &empty).as_deref()),
14204            Starter::Resume(source.id.clone())
14205        );
14206        source.retired_to = Some(empty.id.clone());
14207        assert!(
14208            resolve(&source, &empty).is_none(),
14209            "cycles do not revive obsolete runs"
14210        );
14211        source.retired_to = None;
14212        source.repo = PathBuf::from("/another-repository");
14213        assert!(resolve(&source, &empty).is_none());
14214        source.repo = empty.repo.clone();
14215        source.released_to = Some("later".into());
14216        assert!(resolve(&source, &empty).is_none());
14217        empty.retired_to = Some("unlisted-run".into());
14218        assert!(resolve(&source, &empty).is_none());
14219    }
14220
14221    #[test]
14222    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
14223        // A task whose history holds an *older* run that still looks
14224        // resumable (say, a competition `Runner::review` was started
14225        // alongside after that older run went `Stalled`) and a *newest* run
14226        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
14227        // on this task must mean a fresh competition — falling back to the
14228        // stale, superseded `Stalled` run instead would resurrect history
14229        // nothing asked to revisit and silently defeat the requeue.
14230        let mut older_stalled = RunState::new(
14231            PathBuf::from("/repo"),
14232            "main".to_owned(),
14233            "abc1234def".to_owned(),
14234            "add retries".to_owned(),
14235            Config::default(),
14236        );
14237        older_stalled.status = RunStatus::Stalled;
14238
14239        let mut newest_exhausted = RunState::new(
14240            PathBuf::from("/repo"),
14241            "main".to_owned(),
14242            "abc1234def".to_owned(),
14243            "add retries".to_owned(),
14244            Config::default(),
14245        );
14246        newest_exhausted.status = RunStatus::Blocked;
14247        newest_exhausted.config.graph.review_rounds = 1;
14248        newest_exhausted.reviews = vec![review_round(1)];
14249
14250        assert_eq!(
14251            unfinished_run_with(
14252                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
14253                "t",
14254                |_| Ok(newest_exhausted.clone())
14255            ),
14256            None,
14257            "the newest run is exhausted, so nothing here is worth resuming - \
14258             least of all the older, already-superseded run"
14259        );
14260    }
14261
14262    #[test]
14263    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
14264        assert_eq!(
14265            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
14266                Err(anyhow::anyhow!("fixture is absent"))
14267            }),
14268            None
14269        );
14270    }
14271
14272    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
14273        let mut q = ask::Question::new(
14274            run.to_owned(),
14275            "implement".to_owned(),
14276            "impl-A".to_owned(),
14277            "continue?".to_owned(),
14278            String::new(),
14279            vec!["resume で続行する".to_owned(), "other".to_owned()],
14280        );
14281        q.actions.insert("resume で続行する".to_owned(), action);
14282        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
14283            .unwrap();
14284        q
14285    }
14286
14287    fn held_task_with(run: &str) -> Task {
14288        let mut t = task();
14289        t.runs = vec![run.to_owned()];
14290        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
14291        t
14292    }
14293
14294    fn resume_action(run: &str) -> ask::ChoiceAction {
14295        ask::ChoiceAction::Resume { run: run.into() }
14296    }
14297
14298    #[test]
14299    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
14300        let home = crate::run::test_home();
14301        for parked in [false, true] {
14302            let mut t = task();
14303            t.start("A".into());
14304            t.start("B".into());
14305            assert_eq!(t.runs, vec!["A", "B"]);
14306            t.start("A".into());
14307            let mut resumed = run_state(RunStatus::Blocked);
14308            resumed.id = "A".into();
14309            resumed.parked = parked;
14310            resumed.driver_exited = true;
14311            t.hold_machine(Some("resumed run stopped".into()));
14312            let q = action_question("A", resume_action("A"));
14313            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14314            assert_eq!(
14315                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
14316                    assert_eq!(id, "A");
14317                    Ok(resumed.clone())
14318                }),
14319                ActionDecision::Resume("A".into())
14320            );
14321            assert_eq!(
14322                action_standing(&t, &action_question("B", resume_action("B"))),
14323                ActionStanding::Stale
14324            );
14325            t.release_operator("cli", None);
14326            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
14327                assert_eq!(id, "A");
14328                Ok(resumed.clone())
14329            });
14330            assert_eq!(
14331                choose_starter(None, false, unfinished.as_deref()),
14332                Starter::Resume("A".into())
14333            );
14334            assert_eq!(t.runs, vec!["B", "A"]);
14335        }
14336    }
14337
14338    #[test]
14339    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
14340        let home = crate::run::test_home();
14341        let mut state = crate::land::tests::repair_state(true, true);
14342        state.status = RunStatus::Landing;
14343        state.parked = true;
14344        state.driver_exited = true;
14345        let mut q = ask::Question::new(
14346            state.id.clone(),
14347            land::APPROVAL_NODE.into(),
14348            "land".into(),
14349            "Merge?".into(),
14350            String::new(),
14351            vec![land::APPROVE.into(), land::HOLD.into()],
14352        );
14353        q.id = state.id.clone();
14354        state.land_approval = Some(crate::run::LandApproval {
14355            question: q.id.clone(),
14356            head: "current-head".into(),
14357        });
14358        assert!(land::upgrade_repair_choice(&mut q, &state));
14359        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14360        let mut task = held_task_with(&state.id);
14361        task.status = TaskStatus::Parked;
14362        assert_eq!(
14363            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14364            ActionDecision::Resume(state.id.clone())
14365        );
14366        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14367        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
14368        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
14369        assert_eq!(
14370            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14371            ActionDecision::Resume(state.id.clone()),
14372            "a repair answer newer than the manual hold resumes the existing owner"
14373        );
14374        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14375        for answered_at in [q.answered_at, None] {
14376            let mut older = q.clone();
14377            older.answered_at = answered_at;
14378            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
14379                panic!("a later manual hold must prevent dispatch")
14380            });
14381            let ActionDecision::Refuse(reason) = refused else {
14382                panic!("expected an actionable refusal, got {refused:?}");
14383            };
14384            assert!(reason.contains("later operator decision"));
14385            assert!(reason.contains(&format!("magi task release {}", task.id)));
14386        }
14387        task.operator_decided_at = None;
14388        let mut superseded = state.clone();
14389        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
14390        assert_eq!(
14391            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
14392            ActionDecision::Stale
14393        );
14394        for case in 1..4 {
14395            let mut changed = state.clone();
14396            match case {
14397                1 => changed.status = RunStatus::Blocked,
14398                2 => changed.released_to = Some("new-owner".into()),
14399                _ => changed.land_approval.as_mut().unwrap().head.clear(),
14400            }
14401            assert!(matches!(
14402                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
14403                ActionDecision::Refuse(_)
14404            ));
14405        }
14406        assert!(matches!(
14407            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
14408                "missing owner"
14409            )),
14410            ActionDecision::Refuse(_)
14411        ));
14412        task.runs.push("replacement".into());
14413        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14414        assert_eq!(
14415            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
14416                "old owner must not load"
14417            )),
14418            ActionDecision::Stale
14419        );
14420    }
14421
14422    #[test]
14423    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
14424        let mut state = crate::land::tests::repair_state(true, true);
14425        state.status = RunStatus::Landing;
14426        state.parked = true;
14427        state.driver_exited = true;
14428        let mut q = ask::Question::new(
14429            state.id.clone(),
14430            land::APPROVAL_NODE.into(),
14431            "land".into(),
14432            "Merge?".into(),
14433            String::new(),
14434            vec![land::APPROVE.into(), land::HOLD.into()],
14435        );
14436        q.id = state.id.clone();
14437        state.land_approval = Some(crate::run::LandApproval {
14438            question: q.id.clone(),
14439            head: "current-head".into(),
14440        });
14441        state.save().unwrap();
14442        land::upgrade_repair_choice(&mut q, &state);
14443        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14444        Questions::open().put(&mut q).unwrap();
14445        let tmp = tempfile::tempdir().unwrap();
14446        let queue = Queue::at(tmp.path().join("queue"));
14447        let mut task = held_task_with(&state.id);
14448        task.status = TaskStatus::Parked;
14449        queue.put(&mut task).unwrap();
14450        let empty = Arc::new(tokio::sync::Semaphore::new(0));
14451        let free = Arc::new(tokio::sync::Semaphore::new(1));
14452        assert!(matches!(
14453            claim_dispatch(&queue, &task, false, &empty, &free),
14454            Err(SkipReason::OrdinaryCapacity)
14455        ));
14456        assert!(matches!(
14457            claim_dispatch(&queue, &task, true, &free, &free),
14458            Err(SkipReason::CoolingDown)
14459        ));
14460        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
14461        assert!(claim.permit.is_some());
14462        assert!(matches!(
14463            claim_dispatch(&queue, &task, false, &free, &free),
14464            Err(SkipReason::ClaimUnavailable)
14465        ));
14466        drop(claim);
14467        Questions::open()
14468            .update(&q.id, |q| {
14469                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
14470                Ok(())
14471            })
14472            .unwrap();
14473        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
14474        assert!(claim.permit.is_none());
14475        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
14476    }
14477
14478    #[test]
14479    fn decide_action_resumes_only_the_latest_resumable_run() {
14480        let home = crate::run::test_home();
14481        let t = held_task_with("r1");
14482        let q = action_question("r1", resume_action("r1"));
14483        let load = |s: RunState| move |_: &str| Ok(s);
14484        assert_eq!(
14485            decide_action(
14486                &home,
14487                &t,
14488                &q,
14489                &PHRASES_EN,
14490                load(run_state(RunStatus::Blocked))
14491            ),
14492            ActionDecision::Resume("r1".into())
14493        );
14494        // Not the latest run of the task.
14495        let q_other = action_question("r1", resume_action("r0"));
14496        assert!(matches!(
14497            decide_action(
14498                &home,
14499                &t,
14500                &q_other,
14501                &PHRASES_EN,
14502                load(run_state(RunStatus::Blocked))
14503            ),
14504            ActionDecision::Refuse(_)
14505        ));
14506        // A finished run cannot make progress.
14507        assert!(matches!(
14508            decide_action(
14509                &home,
14510                &t,
14511                &q,
14512                &PHRASES_EN,
14513                load(run_state(RunStatus::Ready))
14514            ),
14515            ActionDecision::Refuse(_)
14516        ));
14517        // A released one either.
14518        let mut released = run_state(RunStatus::Blocked);
14519        released.released_to = Some("elsewhere".into());
14520        assert!(matches!(
14521            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
14522            ActionDecision::Refuse(_)
14523        ));
14524        // Unreadable state is a refusal, never a fresh competition.
14525        assert!(matches!(
14526            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
14527            ActionDecision::Refuse(_)
14528        ));
14529    }
14530
14531    #[test]
14532    fn decide_action_ignores_a_question_about_an_earlier_run() {
14533        let home = crate::run::test_home();
14534        let mut t = held_task_with("r1");
14535        t.runs.push("r2".to_owned());
14536        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14537        assert_eq!(
14538            decide_action(
14539                &home,
14540                &t,
14541                &action_question("r1", ask::ChoiceAction::Done),
14542                &PHRASES_EN,
14543                never
14544            ),
14545            ActionDecision::Stale
14546        );
14547    }
14548
14549    #[test]
14550    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
14551        let home = crate::run::test_home();
14552        let mut t = held_task_with("r1");
14553        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14554        assert_eq!(
14555            decide_action(
14556                &home,
14557                &t,
14558                &action_question("r1", ask::ChoiceAction::Requeue),
14559                &PHRASES_EN,
14560                never
14561            ),
14562            ActionDecision::Requeue
14563        );
14564        let done_q = action_question("r1", ask::ChoiceAction::Done);
14565        assert_eq!(
14566            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14567            ActionDecision::Done
14568        );
14569        t.mark_action_applied(&done_q.id);
14570        assert_eq!(
14571            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14572            ActionDecision::Skip
14573        );
14574
14575        // A plain answer (no action for that label) does nothing.
14576        let mut plain = action_question("r1", ask::ChoiceAction::Done);
14577        plain.actions.clear();
14578        assert_eq!(
14579            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
14580            ActionDecision::Skip
14581        );
14582        // A running task is left alone.
14583        let mut running = held_task_with("r1");
14584        running.status = TaskStatus::Running;
14585        assert_eq!(
14586            decide_action(
14587                &home,
14588                &running,
14589                &action_question("r1", ask::ChoiceAction::Done),
14590                &PHRASES_EN,
14591                never
14592            ),
14593            ActionDecision::Skip
14594        );
14595    }
14596
14597    #[test]
14598    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
14599        crate::run::pin_test_home();
14600        for legacy in [false, true] {
14601            let dir = tempfile::tempdir().unwrap();
14602            let queue = Queue::at(dir.path().join("queue"));
14603            let questions = Questions::at(dir.path().join("questions"));
14604            let run = "20260101-000000-hold";
14605            let mut task = held_task_with(run);
14606            task.status = TaskStatus::Parked;
14607            let mut q = ask::Question::new(
14608                run.into(),
14609                land::APPROVAL_NODE.into(),
14610                "land".into(),
14611                "Repair?".into(),
14612                String::new(),
14613                vec![land::REPAIR.into()],
14614            );
14615            q.actions.insert(land::REPAIR.into(), resume_action(run));
14616            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14617            // Deterministically order the answer before the actual manual hold.
14618            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14619            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
14620            questions.put(&mut q).unwrap();
14621            task.hold_manual(Some("Keep this PR paused".into()));
14622            if legacy {
14623                task.hold_source = None;
14624            }
14625            queue.put(&mut task).unwrap();
14626
14627            apply_task_choice_actions(&queue, &questions, dir.path());
14628            let after = queue.get(&task.id).unwrap();
14629            assert!(after.operator_held());
14630            assert_eq!(after.hold_source, task.hold_source);
14631            assert_eq!(after.operator_decided_at, task.operator_decided_at);
14632            assert_eq!(after.runs, task.runs);
14633            assert_eq!(after.instruction, task.instruction);
14634            assert!(after.resume_override.is_none());
14635            assert!(after.action_applied(&q.id));
14636            let reason = after.hold_reason.as_deref().unwrap();
14637            assert!(reason.starts_with("Keep this PR paused"));
14638            assert!(reason.contains("later operator decision"));
14639            assert!(reason.contains(&format!("magi task release {}", task.id)));
14640
14641            for recovery in [
14642                crate::conduct::Recovery::Review,
14643                crate::conduct::Recovery::Requeue,
14644            ] {
14645                crate::conduct::apply(
14646                    &queue,
14647                    &questions,
14648                    &crate::conduct::Verdict {
14649                        decisions: vec![crate::conduct::Decision {
14650                            id: task.id.clone(),
14651                            recovery: Some(recovery),
14652                            ..Default::default()
14653                        }],
14654                    },
14655                )
14656                .unwrap();
14657            }
14658            // Reconciliation is idempotent, and automatic recovery cannot
14659            // reopen this owner after it observes the rejected repair answer.
14660            apply_task_choice_actions(&queue, &questions, dir.path());
14661            let still_held = queue.get(&task.id).unwrap();
14662            assert!(still_held.operator_held());
14663            assert_eq!(still_held.hold_reason, after.hold_reason);
14664            assert_eq!(still_held.runs, task.runs);
14665            assert!(still_held.review_branch.is_none());
14666            assert!(!still_held.fresh_start);
14667            assert!(queue.next_runnable().is_none());
14668        }
14669    }
14670
14671    #[test]
14672    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
14673        for held in [false, true] {
14674            for retry in [false, true] {
14675                let dir = tempfile::tempdir().unwrap();
14676                let queue = Queue::at(dir.path().join("queue"));
14677                let questions = Questions::at(dir.path().join("questions"));
14678                let home = dir.path().join("home");
14679                let mut t = task();
14680                if held {
14681                    t.hold_machine(Some("driver state unknown".into()));
14682                }
14683                queue.put(&mut t).unwrap();
14684                let verdict = serde_json::from_value(serde_json::json!({
14685                    "decisions": [{
14686                        "id": t.id,
14687                        "question": "Driver state unknown; retry the checks or hold?",
14688                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
14689                        "actions": {
14690                            "daemon: recheck and retry": {"do": "requeue"},
14691                            "daemon: hold the task": {"do": "hold"}
14692                        }
14693                    }]
14694                }))
14695                .unwrap();
14696                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
14697                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14698                let mut q = questions.list().pop().unwrap();
14699                let choice = if retry {
14700                    "daemon: recheck and retry"
14701                } else {
14702                    "daemon: hold the task"
14703                };
14704                assert_eq!(q.actions.len(), 2);
14705                q.answer(ask::Answer::Choice(choice.into())).unwrap();
14706                questions.put(&mut q).unwrap();
14707
14708                // A Web answer does not remove the deputy's fresh lease.
14709                questions.beat(&q.id, ask::WaiterKind::Deputy);
14710                for _ in 0..2 {
14711                    resolve_blockers(&queue, &questions);
14712                    apply_task_choice_actions(&queue, &questions, &home);
14713                    let waiting = queue.get(&t.id).unwrap();
14714                    assert_eq!(waiting.status, TaskStatus::Blocked);
14715                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
14716                    assert!(waiting.answers.is_empty());
14717                    assert!(!waiting.action_applied(&q.id));
14718                    assert!(runnable(&queue).is_empty());
14719                    let free = Arc::new(tokio::sync::Semaphore::new(1));
14720                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
14721                }
14722                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14723
14724                // Releasing the blocker and applying the operation share one save.
14725                resolve_blockers(&queue, &questions);
14726                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14727                apply_task_choice_actions(&queue, &questions, &home);
14728                let after = queue.get(&t.id).unwrap();
14729                assert_eq!(
14730                    after.status,
14731                    if retry {
14732                        TaskStatus::Queued
14733                    } else {
14734                        TaskStatus::Held
14735                    }
14736                );
14737                assert!(after.action_applied(&q.id));
14738                assert_eq!(after.operator_held(), !retry);
14739                assert_eq!(after.answers.len(), 1);
14740
14741                // A later operator decision must not replay this answer.
14742                let mut changed = after;
14743                if retry {
14744                    changed.hold_manual(Some("later hold".into()));
14745                } else {
14746                    changed.release_operator("test", None);
14747                }
14748                let expected = changed.status;
14749                queue.put(&mut changed).unwrap();
14750                apply_task_choice_actions(&queue, &questions, &home);
14751                assert_eq!(queue.get(&t.id).unwrap().status, expected);
14752            }
14753        }
14754    }
14755
14756    #[test]
14757    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
14758        let dir = tempfile::tempdir().unwrap();
14759        let queue = Queue::at(dir.path().join("queue"));
14760        let questions = Questions::at(dir.path().join("questions"));
14761        let home = dir.path().join("home");
14762        let mut state = run_state(RunStatus::Blocked);
14763        state.id = "20260101-000000-act1".to_owned();
14764        state.save_under(&home).unwrap();
14765
14766        let mut t = held_task_with(&state.id);
14767        queue.put(&mut t).unwrap();
14768        let mut q = action_question(&state.id, resume_action(&state.id));
14769        questions.put(&mut q).unwrap();
14770
14771        apply_task_choice_actions(&queue, &questions, &home);
14772        let after = queue.get(&t.id).unwrap();
14773        assert_eq!(after.status, TaskStatus::Queued);
14774        assert!(!after.fresh_start);
14775        assert!(after.action_applied(&q.id));
14776        let pin = after.resume_override.clone().unwrap();
14777        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
14778        assert!(pin.forced);
14779
14780        // Held again later: the same answer does not release it a second time.
14781        let mut again = queue.get(&t.id).unwrap();
14782        again.hold_machine(Some("later".into()));
14783        queue.put(&mut again).unwrap();
14784        apply_task_choice_actions(&queue, &questions, &home);
14785        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14786    }
14787
14788    #[test]
14789    fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
14790        let dir = tempfile::tempdir().unwrap();
14791        let home = dir.path();
14792        let queue = Queue::at(home.join("queue"));
14793        let questions = Questions::at(home.join("questions"));
14794        let mut state = run_state(RunStatus::Blocked);
14795        state.save_under(home).unwrap();
14796        let mut task = held_task_with(&state.id);
14797        queue.put(&mut task).unwrap();
14798        let mut question = action_question(&state.id, ask::ChoiceAction::Done);
14799        questions.put(&mut question).unwrap();
14800
14801        apply_task_choice_actions(&queue, &questions, home);
14802
14803        let after = queue.get(&task.id).unwrap();
14804        assert_eq!(after.status, TaskStatus::Held);
14805        assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
14806        assert_eq!(after.runs, task.runs);
14807        assert!(after.completion_history.is_empty());
14808        assert!(!after.decision_effects.contains_key(&question.id));
14809        assert_eq!(
14810            RunState::load_under(&state.id, home).unwrap().status,
14811            RunStatus::Blocked
14812        );
14813    }
14814
14815    #[test]
14816    fn a_delivered_answer_is_still_acted_on_exactly_once() {
14817        let dir = tempfile::tempdir().unwrap();
14818        let queue = Queue::at(dir.path().join("queue"));
14819        let questions = Questions::at(dir.path().join("questions"));
14820        let home = dir.path().join("home");
14821        let mut state = run_state(RunStatus::Blocked);
14822        state.id = "20260101-000000-act2".to_owned();
14823        state.save_under(&home).unwrap();
14824
14825        let mut t = held_task_with(&state.id);
14826        queue.put(&mut t).unwrap();
14827        let mut q = action_question(&state.id, resume_action(&state.id));
14828        q.answer_delivered = true;
14829        questions.put(&mut q).unwrap();
14830
14831        // Delivered, and the agent then died: the task is still held, so the
14832        // chosen action applies.
14833        apply_task_choice_actions(&queue, &questions, &home);
14834        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14835        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
14836
14837        // Held again: the same answer does nothing a second time.
14838        let mut again = queue.get(&t.id).unwrap();
14839        again.hold_machine(Some("later".into()));
14840        queue.put(&mut again).unwrap();
14841        apply_task_choice_actions(&queue, &questions, &home);
14842        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14843    }
14844
14845    #[test]
14846    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
14847        let dir = tempfile::tempdir().unwrap();
14848        let queue = Queue::at(dir.path().join("queue"));
14849        let questions = Questions::at(dir.path().join("questions"));
14850        let home = dir.path().join("home");
14851        let mut state = run_state(RunStatus::Blocked);
14852        state.id = "20260101-000000-act3".to_owned();
14853        state.save_under(&home).unwrap();
14854        let mut t = held_task_with(&state.id);
14855        queue.put(&mut t).unwrap();
14856        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
14857        questions.put(&mut q).unwrap();
14858
14859        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
14860        apply_task_choice_actions(&queue, &questions, &home);
14861        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14862
14863        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14864        apply_task_choice_actions(&queue, &questions, &home);
14865        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14866    }
14867
14868    #[test]
14869    fn action_standing_tells_the_reasons_apart() {
14870        let mut t = held_task_with("r1");
14871        let q = action_question("r1", ask::ChoiceAction::Requeue);
14872        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14873        let mut plain = q.clone();
14874        plain.actions.clear();
14875        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
14876
14877        // Applied wins over everything, even a running task.
14878        t.mark_action_applied(&q.id);
14879        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
14880
14881        // A newer attempt running: the old question is Stale, not Busy.
14882        let mut t = held_task_with("r1");
14883        t.start("r2".to_owned());
14884        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
14885        // The same question about the latest run just waits.
14886        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
14887        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14888        t.status = TaskStatus::Blocked;
14889        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14890
14891        // A conductor question is keyed by the task, never stale.
14892        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
14893        c.node = crate::conduct::NODE.to_owned();
14894        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
14895        assert!(!ActionStanding::Busy.daemon_owns());
14896    }
14897
14898    #[test]
14899    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
14900        let dir = tempfile::tempdir().unwrap();
14901        let queue = Queue::at(dir.path().join("queue"));
14902        let questions = Questions::at(dir.path().join("questions"));
14903        let home = dir.path().join("home");
14904        // Execution finished before task settlement; Done is not a discard.
14905        let mut state = run_state(RunStatus::Ready);
14906        state.id = "20260101-000000-act4".to_owned();
14907        state.save_under(&home).unwrap();
14908        let mut t = held_task_with(&state.id);
14909        t.status = TaskStatus::Running;
14910        queue.put(&mut t).unwrap();
14911        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
14912        q.cwd = Some(dir.path().display().to_string());
14913        questions.put(&mut q).unwrap();
14914
14915        // While the task runs the daemon will not act, so the waiter still
14916        // delivers the word to the dead asker's seat ...
14917        let running = queue.get(&t.id).unwrap();
14918        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
14919        assert!(matches!(
14920            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
14921            crate::waiter::Action::Deliver(_)
14922        ));
14923        // ... and the daemon waits while the task runs, then applies once.
14924        apply_task_choice_actions(&queue, &questions, &home);
14925        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14926        let mut back = queue.get(&t.id).unwrap();
14927        back.hold_machine(Some("later".into()));
14928        queue.put(&mut back).unwrap();
14929        apply_task_choice_actions(&queue, &questions, &home);
14930        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
14931        let mut again = queue.get(&t.id).unwrap();
14932        again.hold_machine(Some("again".into()));
14933        queue.put(&mut again).unwrap();
14934        apply_task_choice_actions(&queue, &questions, &home);
14935        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14936    }
14937}