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    /// Per-task skip reasons observed by the latest completed dispatch scan.
140    /// Retained even when another task started in the same scan so skipped
141    /// candidates do not lose their observed blocker.
142    #[serde(default)]
143    pub dispatch_skips: std::collections::BTreeMap<String, String>,
144    /// Effective startup capabilities of the question recovery loops.
145    #[serde(default)]
146    pub question_recovery: Option<crate::question_delivery::Recovery>,
147    /// Independent-worker control protocol supported by this scheduler.
148    #[serde(default)]
149    pub worker_protocol: Option<u32>,
150}
151
152impl Status {
153    /// A fresh, idle status for this process.
154    #[must_use]
155    pub fn new() -> Self {
156        let now = Timestamp::now();
157        Self {
158            schema: SCHEMA,
159            pid: std::process::id(),
160            started_at: now,
161            updated_at: now,
162            idle: true,
163            current: Vec::new(),
164            completed: 0,
165            polls: 0,
166            dispatch_wait: None,
167            dispatch_skips: std::collections::BTreeMap::new(),
168            question_recovery: None,
169            worker_protocol: Some(1),
170        }
171    }
172}
173
174impl Default for Status {
175    fn default() -> Self {
176        Self::new()
177    }
178}
179
180/// How the loop should behave.
181#[derive(Debug, Clone, Serialize, Deserialize)]
182#[serde(default)]
183pub struct Opts {
184    /// Repository used by tasks that name none.
185    pub repo: PathBuf,
186    /// Explicit `magi.toml`, instead of the discovered layer stack.
187    pub config: Option<PathBuf>,
188    /// Queue poll interval.
189    pub poll: Duration,
190    /// Attempts a task gets before it is held for a human.
191    pub max_attempts: usize,
192    /// Drain what is runnable now, then return, instead of waiting for more.
193    pub once: bool,
194    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
195    pub merge: Option<String>,
196    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
197    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
198    /// `None` resolves to [`crate::run::default_worktree_root`] - the
199    /// operator's real `~/wt/<repo>` - the same way a run with no
200    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
201    /// that does not own that directory (a test, an embedding that manages
202    /// worktrees itself) must set this, or every idle tick reclaims worktrees
203    /// out from under whoever actually does.
204    pub worktrees_root: Option<PathBuf>,
205}
206
207impl Default for Opts {
208    fn default() -> Self {
209        Self {
210            repo: PathBuf::from("."),
211            config: None,
212            poll: POLL,
213            max_attempts: 2,
214            once: false,
215            merge: None,
216            worktrees_root: None,
217        }
218    }
219}
220
221impl Opts {
222    fn absolute(&self) -> Result<Self> {
223        let mut opts = self.clone();
224        opts.repo = std::path::absolute(&opts.repo)?;
225        opts.config = opts
226            .config
227            .as_deref()
228            .map(std::path::absolute)
229            .transpose()?;
230        opts.worktrees_root = opts
231            .worktrees_root
232            .as_deref()
233            .map(std::path::absolute)
234            .transpose()?;
235        Ok(opts)
236    }
237}
238
239/// How many runs a plain `usize` from config may drive concurrently, floored
240/// at one. A `0` in a config file would otherwise stall the loop entirely -
241/// no runnable task could ever start - which is never what an operator who
242/// wrote `0` meant.
243fn max_concurrent(n: usize) -> usize {
244    n.max(1)
245}
246
247/// Where the status file lives.
248#[must_use]
249pub fn status_path() -> PathBuf {
250    crate::run::home().join("daemon.json")
251}
252
253/// Publish the status file for this process.
254pub fn write_status(status: &Status) -> Result<()> {
255    write_status_to(&status_path(), status)
256}
257
258/// Publish a status to an explicit path.
259///
260/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
261/// on every health poll and must never see a half-written one.
262pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
263    if let Some(parent) = path.parent() {
264        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
265    }
266    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
267    let tmp = path.with_extension("json.tmp");
268    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
269    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
270    Ok(())
271}
272
273/// Delete the status file. Called on the way out so a clean exit reads as
274/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
275pub fn clear_status() {
276    clear_status_at(&status_path());
277}
278
279/// Delete a status file at an explicit path, so the loop's teardown and
280/// [`clear_status`] cannot drift apart: the loop is handed the path it
281/// published to, and a test can watch a temp file disappear.
282fn clear_status_at(path: &Path) {
283    let _ = std::fs::remove_file(path);
284}
285
286/// A cooperative stop, shared with whoever asked the loop to run.
287///
288/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
289/// Ctrl-C listener and the web UI keep others, and every clone points at the
290/// same flag. There is no channel because there is nothing to send — the only
291/// message is "stop", it is idempotent, and a flag cannot be missed by a
292/// receiver that was not listening yet.
293///
294/// A stop ends scheduler dispatch promptly. Its busy snapshot is observational:
295/// detached task workers keep their own lifetimes and ownership after this
296/// handle's scheduler exits.
297#[derive(Debug, Clone, Default)]
298pub struct Stop {
299    /// Set once, never cleared: a stop is not something an operator takes back
300    /// half way through, and a clearable flag would let a start racing a stop
301    /// resurrect a loop that is already unwinding.
302    stopped: Arc<AtomicBool>,
303    /// Live task workers observed by the scheduler's latest dispatch snapshot.
304    busy: Arc<std::sync::atomic::AtomicUsize>,
305    /// Wakes the idle wait. Without this a stop would not be seen until the
306    /// poll interval elapsed, and an operator tapping stop on a phone would
307    /// watch a button do nothing for five seconds.
308    wake: Arc<Notify>,
309    /// Handed to the run in flight, so a stop can also mean "park at the next
310    /// node boundary" instead of "finish the whole competition first".
311    pause: crate::graph::Pause,
312}
313
314impl Stop {
315    /// A stop nobody has asked for yet.
316    #[must_use]
317    pub fn new() -> Self {
318        Self::default()
319    }
320
321    /// Ask the loop to stop. Idempotent, and safe to call before the loop
322    /// starts: the flag is checked before the first poll.
323    pub fn stop(&self) {
324        self.stopped.store(true, Ordering::SeqCst);
325        // `notify_one` rather than `notify_waiters` because the loop may not be
326        // parked yet: this stores a permit, so a wait that registers a moment
327        // later returns at once instead of sleeping out the whole interval.
328        self.wake.notify_one();
329    }
330
331    /// Has a stop been asked for?
332    #[must_use]
333    pub fn stopped(&self) -> bool {
334        self.stopped.load(Ordering::SeqCst)
335    }
336
337    /// Whether a requested scheduler retirement still has an active snapshot.
338    /// Workers continue independently after the scheduler has retired.
339    #[must_use]
340    pub fn finishing(&self) -> bool {
341        self.stopped() && self.busy_now()
342    }
343
344    /// Ask the loop to stop *and* the run in flight to park at its next node
345    /// boundary.
346    ///
347    /// Unlike plain stop, explicit park asks workers to checkpoint at their
348    /// existing safe boundaries. Binary replacement never needs a park.
349    pub fn park(&self, cause: crate::run::ParkCause) {
350        self.pause.park_for(cause);
351        self.stop();
352    }
353
354    /// Has a park been asked for?
355    #[must_use]
356    pub fn parking(&self) -> bool {
357        self.pause.parked()
358    }
359
360    /// The pause handle to give a runner.
361    #[must_use]
362    pub fn pause(&self) -> crate::graph::Pause {
363        self.pause.clone()
364    }
365
366    /// Whether the scheduler's latest snapshot contains active task workers.
367    #[must_use]
368    pub fn busy_now(&self) -> bool {
369        self.busy.load(Ordering::SeqCst) > 0
370    }
371
372    /// Wait out one poll interval, returning early once a stop is asked for.
373    async fn idle(&self, poll: Duration) {
374        tokio::select! {
375            () = tokio::time::sleep(poll) => {}
376            () = self.wake.notified() => {}
377        }
378    }
379}
380
381/// The daemon's published state, read permissively.
382///
383/// This mirrors [`Status`], but is a separate declaration on purpose: every
384/// field defaults, so a status file from an older or newer magi still yields
385/// a usable reading — one this build has never heard of — instead of a parse
386/// error that hides the daemon entirely.
387#[derive(Debug, Clone, Default, Deserialize)]
388#[serde(default)]
389pub struct Reading {
390    /// Format version the daemon claims.
391    pub schema: u32,
392    /// Daemon process id, for an operator who wants to stop it.
393    pub pid: Option<u32>,
394    /// When that process started.
395    pub started_at: Option<Timestamp>,
396    /// Last heartbeat. Absent means the file is unusable, hence not running.
397    pub updated_at: Option<Timestamp>,
398    /// True when the queue had nothing runnable at the last poll.
399    pub idle: bool,
400    /// What the daemon is working on. Empty means idle; more than one entry
401    /// means more than one run is in flight at once.
402    ///
403    /// `deserialize_with` rather than the plain derive: a daemon started
404    /// before this field became a list is still out there writing the old
405    /// shape — a single `{"task":...,"run":...}` object, or its absence —
406    /// on every heartbeat until it is restarted, and a live process reading
407    /// that file during the rollout must still see it as running rather than
408    /// as absent. A bare type change here would fail the whole struct's
409    /// deserialization on a type mismatch, defeating the permissiveness this
410    /// type exists for.
411    #[serde(deserialize_with = "de_current")]
412    pub current: Vec<Current>,
413    /// Tasks this daemon process has finished.
414    pub completed: u64,
415    /// Queue polls this daemon process has made.
416    pub polls: u64,
417    /// Last no-start scan, retaining unknown reason keys from newer writers.
418    pub dispatch_wait: Option<DispatchWait>,
419    /// Per-task skip reasons observed by the latest completed dispatch scan.
420    #[serde(default)]
421    pub dispatch_skips: std::collections::BTreeMap<String, String>,
422    /// Effective startup capabilities of the question recovery loops.
423    #[serde(default)]
424    pub question_recovery: Option<crate::question_delivery::Recovery>,
425    /// Independent-worker control protocol, absent on legacy embedded loops.
426    pub worker_protocol: Option<u32>,
427}
428
429/// Accept the old single-`Current`-or-absent shape as well as the current
430/// list, so a reader never has to know which build wrote the file.
431fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
432where
433    D: serde::Deserializer<'de>,
434{
435    #[derive(Deserialize)]
436    #[serde(untagged)]
437    enum Shape {
438        Many(Vec<Current>),
439        One(Current),
440    }
441    Ok(
442        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
443            Shape::Many(v) => v,
444            Shape::One(c) => vec![c],
445        }),
446    )
447}
448
449impl Reading {
450    /// Seconds since the last heartbeat, or `None` when there has never been
451    /// one.
452    #[must_use]
453    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
454        self.updated_at
455            .map(|at| (now.as_second() - at.as_second()).max(0))
456    }
457
458    /// Whether the loop counts as running: a heartbeat no older than
459    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
460    /// progress hours after the daemon that owned it was killed.
461    #[must_use]
462    pub fn running(&self, now: Timestamp) -> bool {
463        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
464    }
465}
466
467/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
468/// usable there.
469///
470/// Missing, half-written and unparseable all collapse to `None`, because the
471/// only question a reader asks is whether a daemon is alive, and a file it
472/// cannot read is not evidence that one is.
473#[must_use]
474pub fn read_status(home: &Path) -> Option<Reading> {
475    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
476    serde_json::from_str(&body).ok()
477}
478
479struct ClaimObservation {
480    current: Current,
481    evidence: crate::run::LivenessEvidence,
482}
483
484fn observe_current_work(home: &Path, now: Timestamp) -> Vec<ClaimObservation> {
485    let mut observed: Vec<ClaimObservation> = Vec::new();
486    let reading = read_status(home).filter(|reading| reading.running(now));
487    let daemon_pid = reading.as_ref().and_then(|r| r.pid);
488    let heartbeat_age_secs = reading.as_ref().and_then(|r| r.age_secs(now));
489    if let Some(reading) = reading {
490        for claim in reading.current {
491            let task = (!claim.task.is_empty()).then(|| claim.task.clone());
492            let (worker_pid, worker_status, worker_lookup_error) = match claim.worker.as_deref() {
493                Some(worker_id) => match crate::worker::get(home, worker_id) {
494                    Ok(job)
495                        if matches!(
496                            job.status,
497                            crate::worker::Status::Finished | crate::worker::Status::Failed
498                        ) =>
499                    {
500                        // The worker positively reached a terminal status, so
501                        // this heartbeat snapshot is stale until the next poll.
502                        continue;
503                    }
504                    Ok(job) => (job.pid, Some(job.status), None),
505                    Err(error) => (None, None, Some(format!("{error:#}"))),
506                },
507                None => (None, None, None),
508            };
509            let evidence = crate::run::LivenessEvidence::DaemonHeartbeat {
510                daemon_pid,
511                heartbeat_age_secs,
512                worker_id: claim.worker.clone(),
513                worker_pid,
514                worker_status,
515                worker_lookup_error,
516                task,
517            };
518            observed.push(ClaimObservation {
519                current: claim,
520                evidence,
521            });
522        }
523    }
524    let workers = crate::worker::observe_active_detailed(home).and_then(|jobs| {
525        jobs.into_iter()
526            .filter(|entry| entry.job.kind == "task")
527            .map(|entry| {
528                let job = entry.job;
529                let request: TaskWorker = serde_json::from_value(job.payload).map_err(|_| {
530                    anyhow::anyhow!("invalid task worker payload metadata for worker {}", job.id)
531                })?;
532                let run = Queue::at(request.queue)
533                    .get(&request.task)
534                    .ok()
535                    .and_then(|task| task.execution_runs().last().cloned())
536                    .unwrap_or_default();
537                let task_label = (!request.task.is_empty()).then(|| request.task.clone());
538                let current = Current {
539                    worker: Some(job.id.clone()),
540                    task: request.task,
541                    run,
542                };
543                let evidence = crate::run::LivenessEvidence::WorkerClaim {
544                    worker_id: job.id,
545                    pid: job.pid,
546                    status: job.status,
547                    reason: entry.reason,
548                    task: task_label,
549                    daemon_pid: None,
550                };
551                Ok(ClaimObservation { current, evidence })
552            })
553            .collect::<Result<Vec<_>>>()
554    });
555    match workers {
556        Ok(workers) => {
557            for mut worker in workers {
558                if let Some(existing) = observed.iter_mut().find(|claim| {
559                    claim.current.task == worker.current.task
560                        && claim.current.run == worker.current.run
561                        && claim.current.worker == worker.current.worker
562                }) {
563                    if let crate::run::LivenessEvidence::WorkerClaim {
564                        daemon_pid: ref mut target_daemon_pid,
565                        ..
566                    } = worker.evidence
567                    {
568                        *target_daemon_pid = daemon_pid;
569                    }
570                    existing.evidence = worker.evidence;
571                } else {
572                    observed.push(worker);
573                }
574            }
575        }
576        Err(error) => {
577            // This API gates destructive cleanup. Unknown worker ownership
578            // protects every known task/run instead of pretending it is idle.
579            let detail = format!("{error:#}");
580            tracing::error!("cannot determine active workers: {detail}");
581            let evidence = crate::run::LivenessEvidence::WorkerStoreUnreadable { error: detail };
582            observed.extend(
583                Queue::at(home.join("queue"))
584                    .list()
585                    .into_iter()
586                    .map(|task| ClaimObservation {
587                        current: Current {
588                            worker: None,
589                            task: task.id.clone(),
590                            run: task.execution_runs().last().cloned().unwrap_or_default(),
591                        },
592                        evidence: evidence.clone(),
593                    }),
594            );
595            observed.extend(
596                crate::run::list_ids_in(&home.join("runs"))
597                    .into_iter()
598                    .map(|run| ClaimObservation {
599                        current: Current {
600                            worker: None,
601                            task: String::new(),
602                            run,
603                        },
604                        evidence: evidence.clone(),
605                    }),
606            );
607        }
608    }
609    observed
610}
611
612/// Read-only evidence of runs owned by a live daemon or independent worker.
613///
614/// CLI, sandboxed conversation controls and Web cleanup share this observation.
615/// A stale daemon heartbeat does not invalidate a worker's OS-held lease.
616/// Starting reservations and unknown worker state remain protected; observing
617/// them never creates, reconciles or archives files in the worker store.
618/// Callers interested in one identity use [`is_working_on`] or
619/// [`is_working_on_task`].
620#[must_use]
621pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
622    observe_current_work(home, now)
623        .into_iter()
624        .map(|entry| entry.current)
625        .collect()
626}
627
628/// Structured evidence for a live daemon or worker claim on `run`, if any.
629#[must_use]
630pub fn claim_for_run(
631    home: &Path,
632    run: &str,
633    now: Timestamp,
634) -> Option<crate::run::LivenessEvidence> {
635    observe_current_work(home, now)
636        .into_iter()
637        .find(|entry| entry.current.run == run)
638        .map(|entry| entry.evidence)
639}
640
641/// Whether a live daemon is working on this run at this moment.
642#[must_use]
643pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
644    claim_for_run(home, run, now).is_some()
645}
646
647/// Admission may ignore only this process's confirmed worker reservation.
648/// Keep anonymous/legacy daemon claims and every other worker, even for the
649/// same task. The run's execution lease and process identity are checked by
650/// the caller under the owner lock as well.
651pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
652    Ok(other_claim_for_run(home, run, now)?.is_some())
653}
654
655/// Same exclusion rule as [`is_working_on_other`], returning the concrete claim
656/// evidence when another owner (or conservative protection) claims `run`.
657pub(crate) fn other_claim_for_run(
658    home: &Path,
659    run: &str,
660    now: Timestamp,
661) -> Result<Option<crate::run::LivenessEvidence>> {
662    // A helper or test may inherit an identity from a different run store.
663    // That identity grants no exception here; retain all ownership evidence.
664    let same_home = std::env::var_os("MAGI_WORKER_HOME")
665        .is_some_and(|worker_home| Path::new(&worker_home) == home);
666    let caller = if same_home {
667        crate::worker::current_job(home)?
668    } else {
669        None
670    }
671    .filter(|job| {
672        job.kind == "task"
673            && job.status == crate::worker::Status::Running
674            && job.pid == Some(std::process::id())
675    });
676    let caller_id = caller.as_ref().map(|job| job.id.as_str());
677    Ok(observe_current_work(home, now)
678        .into_iter()
679        .find(|entry| {
680            entry.current.run == run
681                && !(caller_id.is_some() && entry.current.worker.as_deref() == caller_id)
682        })
683        .map(|entry| entry.evidence))
684}
685
686#[cfg(test)]
687fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
688    claims
689        .iter()
690        .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
691}
692
693/// Whether a live daemon is working on a run whose short id is this one.
694///
695/// For a worktree that has no run record to compare against at all -
696/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
697/// id is not available to hand to [`is_working_on`]. The short id is: a run's
698/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
699/// and it is exactly the gap between the daemon claiming a task and
700/// `RunState::new` saving the first `run.json` that this exists to protect -
701/// a run genuinely in flight but invisible to a scan of `runs/`.
702#[must_use]
703pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
704    current_work(home, now)
705        .iter()
706        .any(|c| crate::run::short_of(&c.run) == short)
707}
708
709/// Whether a live daemon is working on this task at this moment.
710#[must_use]
711pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
712    current_work(home, now).iter().any(|c| c.task == task)
713}
714
715/// Remove claim files whose owner is provably dead, or that have simply
716/// outlived `older_than`, and return the task ids swept.
717///
718/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
719/// destructor, and the orphaned `.lock` file would make its task permanently
720/// unclaimable — the backlog would stop for good at exactly the task that was
721/// in flight when the machine went down.
722///
723/// The pid recorded in the lock is the authority whenever it can be read at
724/// all; age is only a fallback for when it cannot be.
725///
726/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
727///   full stop — dead sweeps the lock immediately, regardless of age; alive
728///   protects it, regardless of age. This is what lets a lock be reclaimed in
729///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
730///   before this daemon even started, next to a `queued` task, no longer has
731///   to sit for six hours before anything notices its owner is gone.
732/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
733///   falls back to `older_than`, since there is nothing else to check.
734///
735/// Age must never override a *positive* liveness confirmation. `sweep`
736/// polls concurrently with independently running task workers. A worker may
737/// legitimately run longer than `older_than`; its live pid must still protect
738/// its claim. Age alone must never turn that claim into a second task attempt,
739/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
740/// to a second attempt — two `Runner`s writing the same `run.json` and the
741/// same worktree at once. `pid_alive` answering "alive" for anything it
742/// cannot determine (a live process, a pid this build cannot check, one
743/// under another account) is exactly what keeps that path from ever
744/// firing on a guess.
745///
746/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
747/// output unreadable must not be license to guess, and the risk of an
748/// unparseable lock outliving a genuinely dead owner is bounded by an order
749/// of magnitude above any plausible run rather than by a positive check.
750///
751/// Runs on every poll, not only at startup — a daemon up for days must keep
752/// noticing a lock some other, now-dead, daemon left behind just as readily
753/// as one it trips over on the way up.
754pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
755    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
756}
757
758/// [`sweep_stale_claims`] with its process-query boundary supplied by the
759/// caller. This keeps the lock policy testable where process listing is
760/// unavailable, while production still uses the platform query above.
761fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
762where
763    F: Fn(u32) -> bool,
764{
765    let this_process = std::process::id();
766    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
767        .into_iter()
768        .flatten()
769        .flatten()
770        .map(|e| e.path())
771        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
772        .filter(|p| {
773            match std::fs::read_to_string(p)
774                .ok()
775                .and_then(|body| body.trim().parse::<u32>().ok())
776            {
777                // This process wrote it and is asking the question right
778                // now, so it is definitionally still alive - settled without
779                // spawning a helper process at all.
780                Some(pid) if pid == this_process => false,
781                Some(pid) => !pid_alive(pid),
782                None => p
783                    .metadata()
784                    .and_then(|m| m.modified())
785                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
786                    .is_ok_and(|age| age >= older_than),
787            }
788        })
789        .filter(|p| std::fs::remove_file(p).is_ok())
790        .filter_map(|p| {
791            p.file_stem()
792                .and_then(|s| s.to_str())
793                .map(std::borrow::ToOwned::to_owned)
794        })
795        .collect();
796    swept.sort_unstable();
797    swept
798}
799
800/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
801/// no live daemon's heartbeat naming it? Deterministic — no model call, and
802/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
803/// shown.
804fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
805    task.status == TaskStatus::Running
806        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
807        && !is_working_on_task(home, &task.id, now)
808}
809
810/// Every task [`is_stalled`] right now — "止まったタスク" in
811/// `crate::conduct`'s vocabulary.
812fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
813    queue
814        .list()
815        .into_iter()
816        .filter(|t| is_stalled(t, home, now))
817        .collect()
818}
819
820/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
821/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
822/// `Failed`-and-so-also-runnable: a task that already attempted and lost
823/// belongs in [`finished_tasks`], where the question is a recovery, not a
824/// dependency.
825fn queued_tasks(queue: &Queue) -> Vec<Task> {
826    queue
827        .list()
828        .into_iter()
829        .filter(|t| t.status == TaskStatus::Queued)
830        .collect()
831}
832
833/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
834/// タスク" in `crate::conduct`'s vocabulary.
835fn finished_tasks(queue: &Queue) -> Vec<Task> {
836    queue
837        .list()
838        .into_iter()
839        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
840        .collect()
841}
842
843/// Deterministically resolve `Task::blocked_by`: a dependency task that
844/// reached `Done`, or a question that was answered, is removed — no model
845/// involved, on every poll. An answered question's content is copied onto
846/// the task ([`Task::record_answer`]) before its id is dropped, so it
847/// reaches the next `crate::conduct` prompt and the next run's instruction
848/// (see [`instruction_for`]) rather than only clearing the block.
849///
850/// A `blocked_by` id that names neither an existing task nor an existing
851/// question - `magi task rm` (or an operator by hand) deleted it while this
852/// task was still waiting - is caught before any of that: it can never
853/// become `Done` or `Answered`, so the ordinary loop below would otherwise
854/// leave the task `blocked` forever with nothing to notice. Such a task is
855/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
856/// which puts it in front of `crate::triage::run_once`'s own walk the next
857/// time it runs - see that module's doc for why the choice is "ask a human",
858/// never "assume the missing dependency was satisfied and unblock anyway".
859fn resolve_blockers(queue: &Queue, questions: &Questions) {
860    for listed in queue.list() {
861        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
862            continue;
863        }
864        let Ok(_claim) = queue.claim(&listed.id) else {
865            continue;
866        };
867        let Ok(mut task) = queue.get(&listed.id) else {
868            continue;
869        };
870        if task.status != TaskStatus::Blocked {
871            continue;
872        }
873        // A dependency deleted on purpose is released, not held - and before
874        // the missing check, so a pass that races the delete (or a claim that
875        // made `Queue::remove` skip this task) settles it quietly.
876        let deleted = queue.apply_deleted_blockers(&mut task, questions);
877        if !deleted.is_empty() {
878            record(queue, &mut task);
879            for id in &deleted {
880                queue.note_dependency_deleted(&task, id);
881            }
882            if task.status != TaskStatus::Blocked {
883                continue;
884            }
885        }
886        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
887        if !missing.is_empty() {
888            let language = language_of(&task, Path::new("."));
889            let mut cause = missing.clone();
890            cause.sort();
891            cause.dedup();
892            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
893            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
894                &task.blocked_by,
895                &missing,
896                &language,
897            )));
898            record(queue, &mut task);
899            continue;
900        }
901        // A conductor question nobody answered in time is retired by the
902        // waiter, and nothing else would ever move the task it blocks.
903        if let Some(q) = task.blocked_by.iter().find_map(|id| {
904            let crate::queue::Dependency::Question(full) =
905                crate::queue::dependency(queue, questions, id)
906            else {
907                return None;
908            };
909            questions.get_for_effects(&full).ok().filter(|q| {
910                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
911            })
912        }) {
913            let language = language_of(&task, Path::new("."));
914            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
915            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
916            record(queue, &mut task);
917            continue;
918        }
919        let mut changed = false;
920        for id in task.blocked_by.clone() {
921            let resolved = crate::queue::dependency(queue, questions, &id);
922            if let crate::queue::Dependency::Task(full) = &resolved {
923                if queue
924                    .get(full)
925                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
926                {
927                    task.unblock(&id);
928                    changed = true;
929                }
930                continue;
931            }
932            if let crate::queue::Dependency::Question(full) = resolved
933                && let Ok(q) = questions.get_for_effects(&full)
934                && q.status == ask::QuestionStatus::Answered
935            {
936                // The action sweep releases conductor blockers atomically
937                // with their selected operation. A fresh deputy lease must
938                // never leave an answered hold temporarily runnable.
939                if q.node == crate::conduct::NODE
940                    && q.chosen_action().is_some()
941                    && !task.action_applied(&q.id)
942                {
943                    continue;
944                }
945                let answer = match &q.answer {
946                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
947                    None => String::new(),
948                };
949                task.record_answer(q.summary.clone(), answer);
950                task.unblock(&id);
951                changed = true;
952            }
953        }
954        if changed {
955            record(queue, &mut task);
956        }
957    }
958}
959
960/// The `hold_reason` of a task whose conductor question went unanswered.
961fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
962    if crate::lang::is_japanese(language) {
963        format!(
964            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
965            q.short(),
966            q.summary
967        )
968    } else {
969        format!(
970            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
971            q.short(),
972            q.summary
973        )
974    }
975}
976
977/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
978/// for several unrelated reasons, and the waiter must not read them alike.
979#[derive(Debug, Clone, Copy, PartialEq, Eq)]
980pub(crate) enum ActionStanding {
981    /// The answer carries no action: the waiter delivers it as before.
982    NoAction,
983    /// The daemon will apply it (not applied, task idle, current attempt).
984    Pending,
985    /// Already applied (`Task::actions_applied`): the daemon has acted, so
986    /// delivering the word to the old seat would run it beside the new work.
987    Applied,
988    /// The question is about an earlier attempt than the task's latest.
989    Stale,
990    /// The task is running / blocked / done: the daemon defers for now.
991    Busy,
992}
993
994impl ActionStanding {
995    /// The daemon has acted or will act: the waiter must not deliver.
996    pub(crate) fn daemon_owns(self) -> bool {
997        matches!(self, Self::Pending | Self::Applied | Self::Stale)
998    }
999}
1000
1001/// Classify `q`'s chosen action against `task`. `Stale` is judged before
1002/// `Busy`: a question about an earlier attempt must be stopped even while a
1003/// newer competition is running.
1004pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
1005    if task.stale_question(q) {
1006        ActionStanding::Stale
1007    } else if q.chosen_action().is_none() {
1008        ActionStanding::NoAction
1009    } else if task.action_applied(&q.id) {
1010        ActionStanding::Applied
1011    } else if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
1012        ActionStanding::Stale
1013    } else if matches!(
1014        task.status,
1015        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
1016    ) {
1017        ActionStanding::Busy
1018    } else {
1019        ActionStanding::Pending
1020    }
1021}
1022
1023/// What [`decide_action`] concluded about one answered question.
1024#[derive(Debug, Clone, PartialEq, Eq)]
1025enum ActionDecision {
1026    /// Nothing to do now (no action, already applied, or the task is busy).
1027    Skip,
1028    /// Continue the named run instead of competing again.
1029    Resume(String),
1030    /// Requeue as a fresh competition.
1031    Requeue,
1032    /// Hold the task by explicit operator choice.
1033    Hold,
1034    /// Close the task as done.
1035    Done,
1036    /// The question is about an earlier attempt than the task's latest; it
1037    /// is recorded as handled and changes nothing.
1038    Stale,
1039    /// The action cannot be carried out; hold the task and say why. Never
1040    /// falls back to something else, because the operator chose this one.
1041    Refuse(String),
1042}
1043
1044/// Decide what the choice answered on `q` means for `task`. `load` reads a
1045/// run's state, as with [`unfinished_run_with`]. `home` must name that same
1046/// store for driver leases and question checkpoints.
1047///
1048/// `Resume` only fires on the task's *latest* run, and only while that run
1049/// could actually make progress ([`RunStatus::resumable`], not released, review
1050/// budget left); an answer naming anything else is refused rather than
1051/// reinterpreted as a fresh competition.
1052fn decide_action<F>(
1053    home: &Path,
1054    task: &Task,
1055    q: &ask::Question,
1056    p: &Phrases,
1057    load: F,
1058) -> ActionDecision
1059where
1060    F: FnOnce(&str) -> Result<RunState>,
1061{
1062    if task.stale_question(q) {
1063        return ActionDecision::Stale;
1064    }
1065    let Some(action) = q.chosen_action() else {
1066        return ActionDecision::Skip;
1067    };
1068    if task.action_applied(&q.id)
1069        || matches!(
1070            task.status,
1071            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
1072        )
1073    {
1074        return ActionDecision::Skip;
1075    }
1076    // A question about an earlier attempt must not act on a newer one. A
1077    // conductor question is keyed by the task id, not a run, so it is exempt.
1078    if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
1079        return ActionDecision::Stale;
1080    }
1081    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
1082    let stopping = q.node == land::APPROVAL_NODE
1083        && q.resolution()
1084            .as_deref()
1085            .is_some_and(crate::merge_decision::stops);
1086    // An answer is the owner's decision as of when it was given: a manual hold
1087    // placed before it (even after the question was asked) was seen and
1088    // overruled by it, while a hold or release after it supersedes it.
1089    let decision_at = q.answered_at.unwrap_or(q.asked_at);
1090    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
1091        return if repair || stopping {
1092            ActionDecision::Refuse(format!(
1093                "{} 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 {}`",
1094                if repair { "repair" } else { "stop" },
1095                q.id,
1096                q.run,
1097                task.id
1098            ))
1099        } else {
1100            ActionDecision::Stale
1101        };
1102    }
1103    match action {
1104        a if a.maintenance() => ActionDecision::Skip,
1105        ask::ChoiceAction::RecoverBase { .. }
1106        | ask::ChoiceAction::ResumeRun { .. }
1107        | ask::ChoiceAction::ReleaseTask { .. }
1108        | ask::ChoiceAction::RerunChecks { .. }
1109        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
1110        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
1111        ask::ChoiceAction::Hold => ActionDecision::Hold,
1112        ask::ChoiceAction::Done => ActionDecision::Done,
1113        ask::ChoiceAction::Resume { run } => {
1114            if task.execution_runs().last() != Some(run) {
1115                return ActionDecision::Refuse((p.resume_not_latest)(
1116                    q.short(),
1117                    ask::short_id(run),
1118                ));
1119            }
1120            match load(run) {
1121                Ok(s) if stopping => {
1122                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1123                        || !s
1124                            .land_approval
1125                            .as_ref()
1126                            .is_some_and(|binding| binding.question == q.id)
1127                    {
1128                        ActionDecision::Stale
1129                    } else if s.liveness_under(home, false) == Liveness::Live {
1130                        ActionDecision::Skip
1131                    } else if s.status == RunStatus::Landing
1132                        && !s.released()
1133                        && s.retired_to.is_none()
1134                    {
1135                        ActionDecision::Resume(run.clone())
1136                    } else {
1137                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1138                    }
1139                }
1140                Ok(s)
1141                    if q.node == land::APPROVAL_NODE
1142                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1143                {
1144                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1145                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1146                    {
1147                        // A live/manual driver already consumed or superseded
1148                        // this answer. Do not hold its fresh approval wait.
1149                        ActionDecision::Stale
1150                    } else if s.liveness_under(home, false) == Liveness::Live {
1151                        ActionDecision::Skip
1152                    } else if s.status != RunStatus::Landing
1153                        || s.released()
1154                        || s.reviews.is_empty()
1155                        || !implementers_match(task, &s)
1156                        || !s
1157                            .land_approval
1158                            .as_ref()
1159                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1160                    {
1161                        ActionDecision::Refuse(format!(
1162                            "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",
1163                            q.id, run, run
1164                        ))
1165                    } else {
1166                        ActionDecision::Resume(run.clone())
1167                    }
1168                }
1169                Ok(s) => {
1170                    let assessment = s.assess_liveness_under(home, None, Timestamp::now());
1171                    if assessment.verdict == Liveness::Live {
1172                        ActionDecision::Refuse(assessment.live_driver_refusal())
1173                    } else {
1174                        match crate::handover::resume_refusal_under(&s, Some(home)) {
1175                            None => ActionDecision::Resume(run.clone()),
1176                            Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1177                                q.short(),
1178                                ask::short_id(run),
1179                                &reason.diagnostic(&s),
1180                            )),
1181                        }
1182                    }
1183                }
1184                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1185                    q.short(),
1186                    ask::short_id(run),
1187                    &format!("{e:#}"),
1188                )),
1189            }
1190        }
1191    }
1192}
1193
1194/// The fixed prose the daemon writes into [`Task::last_error`] and
1195/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1196/// `triage::Wording` and `land::Words`: only English and Japanese are
1197/// translated, anything else falls back to English.
1198///
1199/// Rendered when the reason is *generated*, so a reason keeps the language it
1200/// was written in if the setting changes later. The notification frame
1201/// (`Task <id> is held:`) is not here and stays English.
1202///
1203/// Deliberately **not** translated, because other code reads them back by
1204/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1205/// and `gate red`. IDs, node names, paths and external error text are embedded
1206/// as they are.
1207struct Phrases {
1208    /// `{}` = status label, then the detail.
1209    graph_stopped: fn(&str, &str) -> String,
1210    quorum_lost: &'static str,
1211    /// Followed by the seats' names.
1212    quota_took_out: &'static str,
1213    /// Followed by the status label.
1214    run_ended: &'static str,
1215    /// Followed by the question's short id.
1216    waiting_for_answer: &'static str,
1217    recovered_running: &'static str,
1218    no_run_to_recover: &'static str,
1219    could_not_start: &'static str,
1220    resume_not_latest: fn(&str, &str) -> String,
1221    resume_cannot_progress: fn(&str, &str, &str) -> String,
1222    resume_unreadable: fn(&str, &str, &str) -> String,
1223    /// A takeover refusal: the operator-facing text. English is the error's own
1224    /// `Display`; a translation keeps the machine detail apart in parentheses.
1225    handover_refused: fn(&crate::handover::Refused) -> String,
1226    /// Appended to a refused handover's hold reason (leading space included).
1227    handover_hint: &'static str,
1228    /// (seats that never answered, review rounds) for the review loop's
1229    /// "refusing to call it clean" stop.
1230    reviewers_never_answered: fn(usize, usize) -> String,
1231}
1232
1233const PHRASES_EN: Phrases = Phrases {
1234    graph_stopped: |status, detail| {
1235        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1236    },
1237    quorum_lost: "the judging panel lost its quorum",
1238    quota_took_out: "; quota took out ",
1239    run_ended: "run ended ",
1240    waiting_for_answer: " - waiting for operator answer to question ",
1241    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1242    no_run_to_recover: "task was `running` with no live daemon and no readable \
1243                        run to recover; held for a human to check what happened",
1244    could_not_start: "could not start the run: ",
1245    resume_not_latest: |q, run| {
1246        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1247    },
1248    resume_cannot_progress: |q, run, reason| {
1249        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1250    },
1251    resume_unreadable: |q, run, e| {
1252        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1253    },
1254    handover_refused: |r| r.to_string(),
1255    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1256    reviewers_never_answered: |missing, rounds| {
1257        format!(
1258            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1259             refusing to call it clean"
1260        )
1261    },
1262};
1263
1264const PHRASES_JA: Phrases = Phrases {
1265    graph_stopped: |status, detail| {
1266        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1267    },
1268    quorum_lost: "審査パネルが定足数を失いました",
1269    quota_took_out: "。クォータで脱落: ",
1270    run_ended: "run 終了: ",
1271    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1272    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1273    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1274                        何が起きたか人が確認するため保留にしました",
1275    could_not_start: "run を開始できませんでした: ",
1276    resume_not_latest: |q, run| {
1277        format!(
1278            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1279        )
1280    },
1281    resume_cannot_progress: |q, run, reason| {
1282        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1283    },
1284    resume_unreadable: |q, run, e| {
1285        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1286    },
1287    handover_refused: |r| {
1288        use crate::handover::Refused;
1289        match r {
1290            Refused::Foreign { branch, path, why } => format!(
1291                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1292                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1293                 から、やり直してください(詳細: {why})"
1294            ),
1295            Refused::Unsafe { branch, path, why } => format!(
1296                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1297                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1298                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1299            ),
1300            Refused::ReleaseFailed { branch, path, run } => format!(
1301                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1302                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1303                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1304            ),
1305        }
1306    },
1307    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1308    reviewers_never_answered: |missing, rounds| {
1309        format!(
1310            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1311             クリーンとは認めません"
1312        )
1313    },
1314};
1315
1316fn phrases(language: &str) -> &'static Phrases {
1317    if crate::lang::is_japanese(language) {
1318        &PHRASES_JA
1319    } else {
1320        &PHRASES_EN
1321    }
1322}
1323
1324/// The language of the repository a task belongs to, read best-effort for the
1325/// paths that have no run (and so no config of their own) to ask. An unreadable
1326/// config is English, not an error: a hold reason must still get written.
1327fn language_of(task: &Task, fallback: &Path) -> String {
1328    crate::lang::of_repo(&repo_for(task, fallback))
1329}
1330
1331/// The task an answered question speaks for: the one whose runs include the
1332/// question's run, or - for a conductor question, filed under the task's own
1333/// id - the task with that id.
1334pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1335    if q.node == crate::conduct::NODE {
1336        return tasks.iter().find(|t| t.id == q.run);
1337    }
1338    tasks.iter().find(|t| t.runs.contains(&q.run))
1339}
1340
1341/// Legacy conductor prose never becomes a maintenance command by inference.
1342/// Replace unsupported open labels under the question lock before dispatch.
1343fn repair_choice_offers(questions: &Questions) {
1344    let ownership = crate::task_chat::InquiryOwnership::default();
1345    for q in questions
1346        .list_for_effects_in(&ownership)
1347        .into_iter()
1348        .filter(|q| {
1349            q.status.open()
1350                && q.node == crate::conduct::NODE
1351                && q.choices
1352                    .iter()
1353                    .any(|c| crate::choice_effect::describe(q, c).is_none())
1354        })
1355    {
1356        let _ = questions.update_in(&q.id, &ownership, |current| {
1357            if current.status.open() {
1358                crate::choice_effect::executable_conductor(current);
1359                if let Some(deputy) = &mut current.deputy {
1360                    deputy.brief = crate::deputy::brief(
1361                        &current.run,
1362                        &current.detail,
1363                        &current.choices,
1364                        &current.actions,
1365                    );
1366                }
1367            }
1368            Ok(())
1369        });
1370    }
1371}
1372
1373/// Apply answered typed choices. Only the daemon calls this in production;
1374/// deputies settle the question and never execute its actions.
1375pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1376    apply_maintenance_choices(queue, questions, home).await;
1377    apply_task_choice_actions(queue, questions, home);
1378}
1379
1380/// Apply bounded maintenance effects independently of question ownership: a
1381/// release watcher need not have a queue task, and a predecessor is another run.
1382async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1383    let ownership = crate::task_chat::InquiryOwnership::default();
1384    for q in questions.list_for_effects_in(&ownership) {
1385        // Read again under the same fence used by explicit settlement.
1386        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1387            continue;
1388        };
1389        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1390            continue;
1391        };
1392        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1393            continue;
1394        };
1395        // Receipt paths use question IDs, whose format is independent of run
1396        // IDs. Apply the question store's filename safety rule to both eras.
1397        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1398            continue;
1399        }
1400        if queue.list().iter().any(|task| {
1401            (task.id == q.run
1402                || task.runs.contains(&q.run)
1403                || q.routed_task.as_deref() == Some(&task.id))
1404                && task.stale_question(&q)
1405        }) {
1406            continue;
1407        }
1408        if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1409            let tasks = queue.list();
1410            let owner = crate::task_chat::task_of(&q, &tasks);
1411            if let Some(owner) = owner
1412                && q.routed_task
1413                    .as_deref()
1414                    .is_none_or(|routed| routed == owner)
1415            {
1416                let result = crate::base_recovery_control::recover(
1417                    queue,
1418                    home,
1419                    crate::base_recovery_control::Request {
1420                        run: run.clone(),
1421                        head: stop.head.clone(),
1422                        actor: "decisions".into(),
1423                        request: q.id.clone(),
1424                        decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1425                        expected_stop: Some((stop.clone(), *episode)),
1426                        evidence_digest: None,
1427                    },
1428                )
1429                .await;
1430                if let Err(error) = result {
1431                    tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1432                    notices::raise_in(home, Notice::warn(
1433                        &format!("base-recovery:{}", q.id),
1434                        format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1435                    ).link(Link::Run { id: run.clone() }));
1436                }
1437            }
1438            continue;
1439        }
1440        let dir = home.join("choice-actions");
1441        if std::fs::create_dir_all(&dir).is_err() {
1442            continue;
1443        }
1444        let Ok(lock) = std::fs::OpenOptions::new()
1445            .create(true)
1446            .truncate(false)
1447            .write(true)
1448            .open(dir.join(format!("{}.lock", q.id)))
1449        else {
1450            continue;
1451        };
1452        if crate::pr_head::try_lock_file(&lock).is_err() {
1453            continue;
1454        }
1455        let fresh = !home
1456            .join("choice-actions")
1457            .join(format!("{}.json", q.id))
1458            .exists();
1459        let result = async {
1460            let receipt = dir.join(format!("{}.json", q.id));
1461            if receipt.exists() {
1462                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1463                anyhow::ensure!(
1464                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1465                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1466                );
1467                return Ok::<_, anyhow::Error>(());
1468            }
1469            // Never retry an uncertain external effect. The receipt is written
1470            // before calling gh, exactly like release_watch's rerun record.
1471            let record = |status: &str| -> anyhow::Result<()> {
1472                let tmp = receipt.with_extension("tmp");
1473                std::fs::write(
1474                    &tmp,
1475                    serde_json::to_vec(&serde_json::json!({
1476                        "action": action, "status": status,
1477                    }))?,
1478                )?;
1479                std::fs::rename(tmp, &receipt)?;
1480                Ok(())
1481            };
1482            let applied = async {
1483                match action {
1484                    ask::ChoiceAction::ResumeRun { run } => {
1485                        crate::resume::validate(home, run)?;
1486                        record("started")?;
1487                        let decided = q.answered_at.unwrap_or(q.asked_at);
1488                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1489                            crate::resume::validate_unqueued(home, run)?;
1490                            crate::resume::start(home, run.clone()).await?;
1491                        }
1492                    }
1493                    ask::ChoiceAction::ReleaseTask {
1494                        task,
1495                        held_at,
1496                        reason,
1497                    } => {
1498                        anyhow::ensure!(
1499                            queue.resolve_id(task)? == *task,
1500                            "task action requires an exact task ID"
1501                        );
1502                        let _claim = queue.claim(task)?;
1503                        let mut task = queue.get(task)?;
1504                        if task.action_applied(&q.id) {
1505                            return Ok(());
1506                        }
1507                        // Filing this conductor question temporarily wraps the
1508                        // original hold in a Blocked state. Restore only that
1509                        // exact blocker on the local copy before checking the
1510                        // hold binding; unrelated waits never authorize release.
1511                        if q.node == crate::conduct::NODE
1512                            && q.run == task.id
1513                            && task.status == TaskStatus::Blocked
1514                            && task.blocked_from == Some(TaskStatus::Held)
1515                            && task.blocked_by.as_slice() == [q.id.as_str()]
1516                        {
1517                            task.unblock(&q.id);
1518                        }
1519                        anyhow::ensure!(
1520                            task.status == TaskStatus::Held
1521                                && task.held_at == Some(*held_at)
1522                                && task.hold_reason.as_deref() == reason.as_deref()
1523                                && task
1524                                    .operator_decided_at
1525                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1526                            "task no longer has the hold this question names"
1527                        );
1528                        task.release_operator("choice", Some(&q.id));
1529                        task.mark_action_applied(&q.id);
1530                        queue.put(&mut task)?;
1531                    }
1532                    ask::ChoiceAction::AbandonRun { run } => {
1533                        record("started")?;
1534                        crate::driver::abandon_proven_dead(home, run)?;
1535                    }
1536                    ask::ChoiceAction::RerunChecks {
1537                        repo,
1538                        pr,
1539                        head,
1540                        runs,
1541                    } => {
1542                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1543                            .await?;
1544                    }
1545                    _ => unreachable!(),
1546                }
1547                Ok::<_, anyhow::Error>(())
1548            }
1549            .await;
1550            match applied {
1551                Ok(()) => record("applied"),
1552                Err(e) => {
1553                    record(&format!("refused or failed: {e:#}"))?;
1554                    Err(e)
1555                }
1556            }
1557        }
1558        .await;
1559        // Retire the originating blocker as well as the target operation.
1560        // A foreign resume leaves its issuer held instead of competing beside
1561        // the execution just started. Other successful maintenance lets the
1562        // original task retry its normal, guarded path.
1563        if home
1564            .join("choice-actions")
1565            .join(format!("{}.json", q.id))
1566            .exists()
1567            && let Some(listed) = task_of_question(&queue.list(), &q)
1568            && !listed.action_applied(&q.id)
1569            && let Ok(_claim) = queue.claim(&listed.id)
1570            && let Ok(mut origin) = queue.get(&listed.id)
1571        {
1572            if !origin.operator_held()
1573                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1574                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1575            {
1576                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1577                    origin.hold_machine(Some(format!(
1578                        "Maintenance choice {} settled; inspect its target before releasing this task",
1579                        q.id
1580                    )));
1581                } else {
1582                    origin.unblock(&q.id);
1583                }
1584            }
1585            origin.mark_action_applied(&q.id);
1586            let _ = queue.put(&mut origin);
1587        }
1588        if let Err(e) = result
1589            && fresh
1590        {
1591            notices::raise_in(
1592                home,
1593                Notice::warn(
1594                    &format!("action:{}", q.id),
1595                    format!("Choice action {} was not completed: {e:#}", q.id),
1596                )
1597                .link(if q.run_names_task() {
1598                    Link::Task { id: q.run.clone() }
1599                } else {
1600                    Link::Run { id: q.run.clone() }
1601                }),
1602            );
1603        }
1604    }
1605}
1606
1607/// Rerun the named failed workflow runs of a pull request, each at most once
1608/// per `request` (a question id, or a chat operation identity). The head,
1609/// lifecycle and failed state are re-read from the forge first; `started` is
1610/// called once those checks pass and before the first external call, and the
1611/// ledger entry is written before every `gh` call, so an uncertain result is
1612/// never repeated automatically.
1613pub(crate) async fn rerun_checks_once(
1614    home: &Path,
1615    request: &str,
1616    repo: &Path,
1617    pr: &str,
1618    head: &str,
1619    runs: &[String],
1620    started: impl FnOnce() -> anyhow::Result<()>,
1621) -> anyhow::Result<()> {
1622    use crate::release_watch::{GhForge, ReleaseForge};
1623    anyhow::ensure!(
1624        !runs.is_empty()
1625            && runs.len() <= 20
1626            && runs
1627                .iter()
1628                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1629            && !pr.starts_with('-'),
1630        "invalid rerun targets"
1631    );
1632    let snap = GhForge.snapshot(repo, pr).await?;
1633    anyhow::ensure!(
1634        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1635        "pull request head or lifecycle changed"
1636    );
1637    anyhow::ensure!(
1638        runs.iter().all(|r| snap
1639            .checks
1640            .iter()
1641            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1642        "named workflow is no longer failed on this pull request"
1643    );
1644    started()?;
1645    let dir = home.join("choice-actions");
1646    std::fs::create_dir_all(&dir)?;
1647    let rerun_lock = std::fs::OpenOptions::new()
1648        .create(true)
1649        .truncate(false)
1650        .write(true)
1651        .open(dir.join("reruns.lock"))?;
1652    crate::pr_head::try_lock_file(&rerun_lock)?;
1653    let ledger = dir.join("reruns.json");
1654    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1655        serde_json::from_slice(&std::fs::read(&ledger)?)?
1656    } else {
1657        Default::default()
1658    };
1659    for run in runs {
1660        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1661        if !recorded.insert(key) {
1662            continue;
1663        }
1664        let tmp = ledger.with_extension("tmp");
1665        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1666        std::fs::rename(tmp, &ledger)?;
1667        GhForge.rerun(repo, run).await?;
1668    }
1669    Ok(())
1670}
1671
1672/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1673///
1674/// Runs on every poll before the conductor looks at the queue. The task is
1675/// re-read under its claim, so a task somebody completed or held by hand in
1676/// the meantime is judged on what it is now. `Resume` releases the task and
1677/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1678/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1679/// ordinary `unfinished_run` logic resumes that same run.
1680pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1681    let tasks = queue.list();
1682    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1683    for q in questions.list_for_effects_in(&ownership) {
1684        // Read again under the same fence used by explicit settlement.
1685        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1686            continue;
1687        };
1688        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1689            continue;
1690        };
1691        // Dismissal is committed by the question writer, never a resume.
1692        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1693            continue;
1694        }
1695        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1696            continue;
1697        }
1698        let Some(listed) = task_of_question(&tasks, &q) else {
1699            if q.node == land::APPROVAL_NODE
1700                && q.resolution().as_deref().is_some_and(|choice| {
1701                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1702                })
1703            {
1704                notices::raise_in(
1705                    home,
1706                    Notice::warn(
1707                        &format!("repair-owner:{}", q.id),
1708                        format!(
1709                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1710                            q.run, q.run
1711                        ),
1712                    ).link(Link::Run { id: q.run.clone() }),
1713                );
1714            }
1715            continue;
1716        };
1717        if listed.action_applied(&q.id) {
1718            continue;
1719        }
1720        let Ok(_claim) = queue.claim(&listed.id) else {
1721            continue;
1722        };
1723        let Ok(mut task) = queue.get(&listed.id) else {
1724            continue;
1725        };
1726        // Work only on this local copy until the action can be committed.
1727        // In particular, a fresh lease below leaves the persisted task blocked.
1728        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1729            let blockers: Vec<_> = task
1730                .blocked_by
1731                .iter()
1732                .filter(|id| {
1733                    crate::queue::dependency(queue, questions, id)
1734                        == crate::queue::Dependency::Question(q.id.clone())
1735                })
1736                .cloned()
1737                .collect();
1738            if !blockers.is_empty() {
1739                for id in blockers {
1740                    task.unblock(&id);
1741                }
1742                let answer = match &q.answer {
1743                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1744                    None => String::new(),
1745                };
1746                task.record_answer(q.summary.clone(), answer);
1747            }
1748        }
1749        let language = language_of(&task, Path::new("."));
1750        let mut decision = decide_action(home, &task, &q, phrases(&language), |id| {
1751            RunState::load_under(id, home)
1752        });
1753        let completion = if matches!(decision, ActionDecision::Done) {
1754            match crate::task_completion::prepare_close(
1755                &task,
1756                home,
1757                CompletionActor::DaemonSettle,
1758                Some(format!(
1759                    "Question {}: {} — {}",
1760                    q.id,
1761                    q.summary,
1762                    q.resolution().unwrap_or_default()
1763                )),
1764                false,
1765            ) {
1766                Ok(context) => Some(context),
1767                Err(error) => {
1768                    decision = ActionDecision::Refuse(error.to_string());
1769                    None
1770                }
1771            }
1772        } else {
1773            None
1774        };
1775        let ran = matches!(
1776            decision,
1777            ActionDecision::Resume(_)
1778                | ActionDecision::Requeue
1779                | ActionDecision::Hold
1780                | ActionDecision::Done
1781        );
1782        if ran && asker_may_still_read(questions, &q, home) {
1783            // The asking process or its seat can still take the word; act
1784            // once it has gone quiet. Bound on the remaining window: the
1785            // check is not atomic with the write below, so an asker that
1786            // takes the word in between (at most one poll, never more than
1787            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1788            // and `Task::actions_applied` under the claim keeps the action to
1789            // one application. The waiter does not deliver an answer that
1790            // carries an action (`waiter::decide_owned`), so it cannot race.
1791            continue;
1792        }
1793        let done = matches!(decision, ActionDecision::Done);
1794        // Resume owes an execution pass; only these task-local effects finish
1795        // in this write. Stale/refused actions never acquire an effect receipt.
1796        let completed = matches!(
1797            decision,
1798            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1799        );
1800        match decision {
1801            ActionDecision::Skip => continue,
1802            ActionDecision::Resume(run) => {
1803                task.release_operator("choice", Some(&q.id));
1804                task.resume_override = Some(crate::queue::OperatorResume {
1805                    question_id: q.id.clone(),
1806                    at: Timestamp::now(),
1807                    conductor_rehold: None,
1808                    forced: true,
1809                    pinned_run: Some(run),
1810                });
1811            }
1812            ActionDecision::Stale => {}
1813            ActionDecision::Requeue => {
1814                task.release_operator("choice-requeue", Some(&q.id));
1815                task.requeue();
1816            }
1817            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1818            ActionDecision::Done => {
1819                task.succeed(completion.expect("done passed completion admission"));
1820            }
1821            ActionDecision::Refuse(why) => {
1822                let _ =
1823                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1824                if task.operator_held() {
1825                    // A rejected answer does not release the operator's hold
1826                    // or reclassify it as recoverable by the conductor.
1827                    task.hold_reason = Some(match task.hold_reason.take() {
1828                        Some(reason) => format!("{reason}\n\n{why}"),
1829                        None => why,
1830                    });
1831                } else {
1832                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1833                    task.hold_machine(Some(why));
1834                }
1835                notices::raise(
1836                    Notice::warn(
1837                        &format!("action:{}", q.id),
1838                        "An answered task action could not be applied; the task stays held.",
1839                    )
1840                    .link(Link::Task {
1841                        id: task.id.clone(),
1842                    }),
1843                );
1844            }
1845        }
1846        task.mark_action_applied(&q.id);
1847        if completed {
1848            task.decision_effects.insert(
1849                q.id.clone(),
1850                format!("decision: {}", q.resolution().expect("answered action")),
1851            );
1852        }
1853        // The applied id travels with the transition, so a failed save loses
1854        // neither and the answer is acted on at the next poll.
1855        record(queue, &mut task);
1856        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1857            supersede_prior_runs(&task, home);
1858        }
1859        // Delivery is only a note of who has read the answer; the task's own
1860        // mark above is the authority. Best effort.
1861        let _ = questions.update_in(&q.id, &ownership, |r| {
1862            r.answer_delivered = true;
1863            Ok(())
1864        });
1865    }
1866}
1867
1868/// Whether something may still read the answer to `q`: a fresh lease, or the
1869/// asking seat still listed as active in its run (its CLI can outlive the
1870/// `magi ask` that was killed).
1871fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1872    let now = Timestamp::now();
1873    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1874        return true;
1875    }
1876    q.node != crate::conduct::NODE
1877        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1878            s.seats_active()
1879                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1880        })
1881}
1882
1883/// Retire an unanswered conductor question after its task no longer refers to
1884/// it. Conductor questions use the task id in `Question::run`, so run-based
1885/// cleanup cannot observe a manual release or completion.
1886///
1887/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1888/// own question also carries a `run`, and a run id that happens to collide
1889/// with some task's id is not this loop's business — only a conductor
1890/// question actually uses the task id that way. One `Questions::list()` scan
1891/// is taken up front and matched against the in-memory task set, rather than
1892/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1893fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1894    let tasks = queue.list();
1895    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1896    let by_id: std::collections::BTreeMap<&str, &Task> =
1897        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1898    let referenced: Vec<&str> = tasks
1899        .iter()
1900        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1901        .collect();
1902
1903    for mut question in questions.list_for_effects_in(&ownership) {
1904        if !question.status.open()
1905            || question.node != crate::conduct::NODE
1906            || questions.held_reply_in(&question.id, &ownership)
1907        {
1908            continue;
1909        }
1910        // Keep questions a task still names, including when the reference
1911        // moved to a dependent task.
1912        // Preserve even ambiguous references: retiring a possibly referenced
1913        // question is unsafe until the operator disambiguates it.
1914        if referenced
1915            .iter()
1916            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1917        {
1918            continue;
1919        }
1920        let Some(task) = by_id.get(question.run.as_str()) else {
1921            continue;
1922        };
1923        question.abandon(format!(
1924            "task {} no longer waits for this answer",
1925            task.short()
1926        ));
1927        if let Err(e) = questions.put_in(&mut question, &ownership) {
1928            tracing::warn!(
1929                "could not retire question {} for task {}: {e:#}",
1930                question.short(),
1931                task.short()
1932            );
1933        }
1934    }
1935}
1936
1937/// What a finished run tells the queue about the task it came from.
1938///
1939/// A struct rather than a fourth and fifth boolean argument: the two flags
1940/// answer different questions about the same run, and a call site passing
1941/// `(…, true, false)` is one transposition away from refunding attempts
1942/// forever.
1943#[derive(Debug, Clone, Copy)]
1944pub struct Verdict {
1945    /// Where the graph stopped.
1946    pub status: RunStatus,
1947    /// The run opened a pull request.
1948    pub left_pr: bool,
1949    /// At least one seat was lost to a rate limit.
1950    pub quota_hit: bool,
1951    /// The run parked at a node boundary because it was asked to.
1952    pub parked: bool,
1953    /// The run never produced a single candidate a judge could look at.
1954    ///
1955    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1956    /// still have another candidate worth judging, in which case the loss was
1957    /// not the reason nothing came of the run. This is `true` only when the
1958    /// implement wave ended with nothing viable at all.
1959    pub no_viable_candidates: bool,
1960}
1961
1962/// Record a finished run against the task it came from.
1963///
1964/// Kept pure and separate from the loop because this mapping *is* the retry
1965/// policy, and a policy that can only be exercised by spawning a graph is a
1966/// policy nobody checks. The table:
1967///
1968/// | run status                           | task becomes        | attempt spent |
1969/// |---------------------------------------|---------------------|---------------|
1970/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1971/// | `Merged`, `Ready`                      | `Done`               | yes          |
1972/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1973/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1974/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1975/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1976/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1977/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1978/// | `Blocked` with a PR                    | `Held`               | yes          |
1979/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1980/// | `VerifiedNoop`                          | `Held`               | yes          |
1981/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1982///
1983/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1984/// deliberately: every candidate agreeing there is nothing to write is not a
1985/// machine fact about a rate limit, it is an unverified claim about the
1986/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1987/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1988/// claim could be wrong (a misread instruction, a stale check), and closing
1989/// the task automatically on an implementer's say-so would be the exact
1990/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1991/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1992/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1993/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1994/// claim regardless of whether the one already-spent attempt is refunded, and
1995/// [`Task::release`] resets the count to zero anyway the moment a human looks
1996/// at the evidence and lets it run again.
1997///
1998/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1999/// twice, together. A quorum lost to rate limits is a property of the machine
2000/// and not of the task, so the attempt is refunded and a reset quota picks
2001/// the work up where it stopped — and that is just as true when every
2002/// implement seat lost the same race and `after_implement` bails with nothing
2003/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
2004/// machine fact. The `no_viable_candidates` guard is what keeps that row
2005/// narrow: a `Failed` run that produced a real candidate which then lost for
2006/// some other reason still spends the attempt, exactly like the quorum lost
2007/// to judges that answered with the wrong shape is ordinary flakiness, and
2008/// refunding *that* takes the bound off the retry loop entirely: run e633
2009/// stalled with `quota: []` after two judges wrote unusable JSON, was
2010/// refunded, and the next attempt paid for a fresh hour-long implement wave
2011/// before it could fail the same way. `max_attempts` exists precisely so
2012/// that cannot repeat forever.
2013///
2014/// A non-terminal status means `execute` returned while the graph was still
2015/// mid-flight, which is a bug rather than a verdict; it is treated as a
2016/// failure so that a task cannot loop on it either.
2017///
2018/// `left_pr` splits the `Blocked` row, and it is the difference between a run
2019/// that failed and a run that finished into a gate. See [`Task::handed_off`].
2020pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
2021    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN, None)
2022}
2023
2024/// [`settle`], with the daemon's own fixed prose in `p`'s language.
2025fn settle_in(
2026    task: &mut Task,
2027    verdict: Verdict,
2028    detail: &str,
2029    max_attempts: usize,
2030    p: &Phrases,
2031    state: Option<&RunState>,
2032) {
2033    // A parked run is the operator's own doing, and its work is intact on
2034    // disk. The task goes back in line with its attempt refunded so the next
2035    // loop resumes the same run - which `one_task` prefers over competing
2036    // again - and so that swapping the binary a few times cannot exhaust a
2037    // budget meant for agents that actually misbehaved.
2038    if verdict.parked {
2039        task.park(detail);
2040        return;
2041    }
2042    let completion = |task: &Task| match state {
2043        Some(state) => CompletionContext::from_run(
2044            CompletionActor::DaemonSettle,
2045            Some(detail.to_owned()),
2046            task,
2047            state,
2048        ),
2049        None => CompletionContext::new(
2050            CompletionActor::DaemonSettle,
2051            Some(detail.to_owned()),
2052            &crate::run::home(),
2053            task,
2054        ),
2055    };
2056    match verdict.status {
2057        RunStatus::Merged | RunStatus::Ready
2058            if task.pr_recovery.as_ref().is_some_and(|s| {
2059                s.disposition != Some(crate::pr_recovery::Disposition::Review)
2060            }) =>
2061        {
2062            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()));
2063        }
2064        RunStatus::Merged | RunStatus::Ready => task.succeed(completion(task)),
2065        RunStatus::AlreadyInBase => task.already_landed(detail, completion(task)),
2066        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
2067        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
2068            task.stall(detail)
2069        }
2070        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
2071        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
2072        RunStatus::Blocked => task.fail(detail, max_attempts),
2073        RunStatus::VerifiedNoop if state.is_none_or(RunState::all_candidates_verified_noop) => {
2074            task.handed_off(detail)
2075        }
2076        RunStatus::VerifiedNoop => task.fail(detail, max_attempts),
2077        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
2078    }
2079}
2080
2081/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
2082/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
2083/// itself has actually finished *and* its own last attempt is provably why:
2084/// this loads that run and requires `Merged`/`Ready` before touching
2085/// anything earlier in `runs`, since `Task::succeed` can also be called
2086/// directly on a task whose last attempt never landed at all.
2087///
2088/// Called right after whatever call set `task.status` to
2089/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
2090/// `reclaim`'s, but also every other place a task can be closed by hand
2091/// without the loop ever settling it itself: `magi task done`
2092/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
2093/// (`web::queue_done`). Closing a task by hand — after confirming a manual
2094/// GitHub merge, say, exactly the workflow this repository's own
2095/// "Landing a run's winner by hand" documents — is just as much "this task's
2096/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
2097/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
2098/// forever, which is the exact backlog this status exists to clear. `pub`
2099/// for those two out-of-module callers; everything else about this stays
2100/// internal bookkeeping.
2101///
2102/// A run something is still actually driving is left alone: a
2103/// task cannot be `Done` while one of its *own* attempts is still in flight,
2104/// so a live one at this point can only be an unrelated process — a manual
2105/// `--resume` of this old, now-moot run — and rewriting under it would just
2106/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
2107/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
2108/// pair `run_report`/`run_detail` use for the same question elsewhere:
2109/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
2110/// --resume` invoked by hand outside it, which `liveness` also checks via
2111/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
2112/// (already terminal in some other way, or itself mid-run) is left untouched
2113/// too.
2114///
2115/// Best-effort, like the rest of this module's bookkeeping: a load or save
2116/// failure here is a `tracing::warn`, not a failed settle, and the next time
2117/// this same task's completion is recorded — or a daemon restart replays
2118/// `reclaim_orphaned_running` — is another chance to catch up. There is no
2119/// separate reconciliation pass; if that gap ever matters in practice, one
2120/// can be added then.
2121///
2122/// `home` is a parameter, not the process-global [`crate::run::home`], for
2123/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
2124/// calls this with `ui.home`, which is `crate::run::home()` in a real
2125/// process but a fixture's own directory under test — falling through to
2126/// the global there would read and write through whichever home some other
2127/// test in the same binary happened to pin into that `OnceLock` first, not
2128/// the run this call actually means.
2129pub fn supersede_prior_runs(task: &Task, home: &Path) {
2130    if task
2131        .completion_history
2132        .last()
2133        .is_some_and(|event| event.discard)
2134    {
2135        return;
2136    }
2137    let now = Timestamp::now();
2138    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
2139    // right behind a `Merged`/`Ready` verdict) from one set directly by
2140    // `magi task done`/its web equivalent/the conductor on a task whose last
2141    // recorded attempt never actually landed - that requires reading the
2142    // run itself, which is exactly what this does before trusting anything
2143    // in `runs` is safe to relabel.
2144    let last_run_succeeded = task
2145        .runs
2146        .last()
2147        .and_then(|id| RunState::load_under(id, home).ok())
2148        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
2149    for id in task.superseded_attempts(last_run_succeeded) {
2150        let mut state = match RunState::load_under(id, home) {
2151            Ok(s) => s,
2152            Err(e) => {
2153                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
2154                continue;
2155            }
2156        };
2157        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
2158            continue;
2159        }
2160        let daemon_claims = is_working_on(home, id, now);
2161        if state.liveness(daemon_claims) == Liveness::Live {
2162            continue;
2163        }
2164        state.status = RunStatus::Superseded;
2165        if let Err(e) = state.save_under(home) {
2166            tracing::warn!("could not mark run {id} superseded: {e:#}");
2167        }
2168    }
2169}
2170
2171/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
2172/// finish the moment it was called, because one of its earlier attempts was
2173/// still live then - a `magi run --resume` invoked by hand on an old run,
2174/// most likely.
2175///
2176/// That skip is correct at the time (rewriting under a run something is
2177/// still actively saving would just be undone), but recording a completion
2178/// does not schedule another settlement, so without this nothing would look at it
2179/// again: if that manual process later ends anywhere other than
2180/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
2181/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
2182/// backlog this status exists to clear. Called on the same idle-only
2183/// cadence as [`janitor`], next to it rather than folded into it: this
2184/// walks `queue` and `janitor` never otherwise needs one.
2185///
2186/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
2187/// more than one attempt, every pass: each call is a handful of local file
2188/// reads bounded by that task's own attempt count, the same order of cost
2189/// [`clean::fold_due`] already pays scanning every run on disk on the same
2190/// cadence, and a task already fully resolved costs one failed liveness
2191/// check turned no-op the moment its lingering attempt is no longer live.
2192fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2193    for task in queue.list() {
2194        if task.status != TaskStatus::Done || task.runs.len() < 2 {
2195            continue;
2196        }
2197        supersede_prior_runs(&task, home);
2198    }
2199}
2200
2201/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
2202/// task ends up held.
2203///
2204/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
2205/// dead daemon never got back to) share this, so the two cannot drift into
2206/// disagreeing about which held tasks get a diagnostic.
2207fn settle_and_diagnose(
2208    task: &mut Task,
2209    verdict: Verdict,
2210    detail: &str,
2211    max_attempts: usize,
2212    state: &RunState,
2213) {
2214    let mut verdict = verdict;
2215    let mut detail = detail;
2216    if verdict.status == RunStatus::VerifiedNoop && !state.all_candidates_verified_noop() {
2217        // Never allow an inconsistent or unsupported `VerifiedNoop` run state
2218        // to bypass settlement into a no-change handoff, and never rewrite the
2219        // historical run record on disk: settle the task as an ordinary failure.
2220        verdict.status = RunStatus::Failed;
2221        verdict.quota_hit = false;
2222        detail = "no-change result lacks verified evidence";
2223    }
2224    let p = phrases(&state.config.graph.language);
2225    // Shared by normal completion and crash recovery, under the task claim.
2226    // No new attempt can own the task until the old driver has exited.
2227    if let Some(d) = &state.merge_decision {
2228        use crate::merge_decision as md;
2229        if task
2230            .execution_runs()
2231            .last()
2232            .is_some_and(|id| id != &state.id)
2233        {
2234            return;
2235        }
2236        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2237            task.succeed(CompletionContext::from_run(
2238                CompletionActor::DaemonSettle,
2239                Some(format!("Owner merge decision {}: {}", d.question, d.choice)),
2240                task,
2241                state,
2242            ));
2243        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2244            if state.liveness(false) != Liveness::Dead {
2245                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2246                return;
2247            }
2248            let replacement = md::Replacement {
2249                question: d.question.clone(),
2250                run: state.id.clone(),
2251                pr: d.target.pr.clone(),
2252                agent: agent.to_owned(),
2253                context: format!(
2254                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2255                    d.target.pr,
2256                    state.id,
2257                    serde_json::to_string(&state.reviews).unwrap_or_default()
2258                ),
2259            };
2260            task.requeue();
2261            task.pr_recovery = None;
2262            task.review_of = None;
2263            task.replacement = Some(replacement);
2264        } else {
2265            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2266                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2267            } 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())) }));
2268        }
2269        task.mark_action_applied(&d.question);
2270        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2271            task.decision_effects
2272                .insert(d.question.clone(), format!("decision: {}", d.choice));
2273        }
2274        if let Some(pass) = state.passes.last() {
2275            task.record_pass_at(
2276                &state.id,
2277                pass.index,
2278                Some(pass.started_at),
2279                task.attempts,
2280                None,
2281            );
2282        }
2283        return;
2284    }
2285    if let Some(replacement) = &task.replacement
2286        && !state.parked
2287        && state.resource_block.is_none()
2288        && (state.viable().is_empty()
2289            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2290    {
2291        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)));
2292        return;
2293    }
2294    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2295        let mut agents: Vec<_> = state
2296            .quota
2297            .iter()
2298            .filter(|q| {
2299                q.cause == crate::agent::QuotaCause::Authentication
2300                    && state
2301                        .passes
2302                        .last()
2303                        .is_none_or(|pass| q.at >= pass.started_at)
2304            })
2305            .map(|q| q.agent.as_str())
2306            .collect();
2307        agents.sort_unstable();
2308        agents.dedup();
2309        if !agents.is_empty() {
2310            task.stall(detail);
2311            task.notice_cause("agent-authentication", None, None);
2312            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2313            return;
2314        }
2315    }
2316    let attempts_before = task.attempts;
2317    // A run that stopped because a shared resource stayed busy was never a
2318    // failure of the task or of an agent. Earlier nodes may have run; only
2319    // the blocked operation lacks a result. The attempt is
2320    // refunded and the task is held by the machine, under a reason `triage`
2321    // can re-check, so the same run resumes with the same agents once the
2322    // resource is free. A park request still wins (it is the operator's).
2323    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2324        let disk_checked_at = task.disk_checked_at;
2325        task.notice_cause(
2326            &format!("resource:{}:{}", block.kind, block.node),
2327            None,
2328            None,
2329        );
2330        task.last_error = Some(detail.to_owned());
2331        task.diagnostic = None;
2332        task.attempts = task.attempts.saturating_sub(1);
2333        if block.kind == "agent authentication" {
2334            task.hold_machine(Some(format!(
2335                "[authentication] {}; no attempt was spent",
2336                block.detail
2337            )));
2338        } else if block.kind == "agent usage limit" {
2339            // Usage limits keep the existing cooldown-and-resume policy.
2340            if let Some(agent) = &state.config.graph.selected_implementer {
2341                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.")));
2342            } else {
2343                task.status = TaskStatus::Failed;
2344                task.last_error = Some(block.detail.clone());
2345            }
2346        } else if block.kind == "disk pressure" {
2347            task.hold_machine(Some(format!(
2348                "{}{}",
2349                crate::disk::RUNNING_PRESSURE,
2350                block.detail
2351            )));
2352        } else {
2353            task.hold_machine(Some(format!(
2354                "{}{}; no attempt was spent; resume to retry the affected operation",
2355                crate::cache::RESOURCE_HOLD,
2356                block.description()
2357            )));
2358        }
2359        if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2360            && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2361        {
2362            task.mark_disk_capacity();
2363            task.disk_checked_at = disk_checked_at;
2364        }
2365        if let Some(pass) = state.passes.last() {
2366            task.record_pass_at(
2367                &state.id,
2368                pass.index,
2369                Some(pass.started_at),
2370                attempts_before,
2371                None,
2372            );
2373        }
2374        return;
2375    }
2376    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2377        state.parked
2378            && state.status == RunStatus::Landing
2379            && state
2380                .pr_pushed_head
2381                .as_ref()
2382                .is_none_or(|h| h == &hold.head)
2383            && task.execution_runs().last() == Some(&state.id)
2384    }) {
2385        // Settlement and crash recovery share this idempotency key. A later
2386        // explicit resume is a new pass and may refund its own attempt once.
2387        let pass = state.passes.last().map_or(0, |p| p.index);
2388        if !task
2389            .passes
2390            .iter()
2391            .any(|p| p.run == state.id && p.pass_index == pass)
2392        {
2393            task.attempts = task.attempts.saturating_sub(1);
2394        }
2395        task.hold_machine(Some(format!(
2396            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2397            hold.question
2398        )));
2399        task.last_error = Some(detail.to_owned());
2400        task.diagnostic = None;
2401        task.record_pass_at(
2402            &state.id,
2403            pass,
2404            state.passes.last().map(|p| p.started_at),
2405            attempts_before,
2406            Some(crate::run::ParkCause::Question),
2407        );
2408        return;
2409    }
2410    let unresolved = task.hold_notice_cause.clone();
2411    let head_e2e_stop = crate::head_e2e_stop::conclusive(state)
2412        .filter(|_| !verdict.parked && !verdict.quota_hit && task.pr_recovery.is_none());
2413    let mut reconsumed_head_e2e = false;
2414    if state.base_sync_blocked() {
2415        // No automatic retry may turn a retained sync stop into a new competition.
2416        task.hold_machine(Some(detail.to_owned()));
2417        task.last_error = Some(detail.to_owned());
2418    } else if state.land_sync_exhausted() {
2419        task.hold_machine(Some(format!("{detail} {}", state.land_sync_next_action())));
2420        task.last_error = Some(detail.to_owned());
2421    } else if !verdict.parked
2422        && task
2423            .pr_recovery
2424            .as_ref()
2425            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2426        && matches!(
2427            verdict.status,
2428            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2429        )
2430    {
2431        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2432            task.succeed(CompletionContext::from_run(
2433                CompletionActor::DaemonSettle,
2434                Some(detail.to_owned()),
2435                task,
2436                state,
2437            ));
2438        } else {
2439            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()));
2440        }
2441    } else if !verdict.parked
2442        && task.pr_recovery.is_some()
2443        && matches!(
2444            verdict.status,
2445            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2446        )
2447        && !verdict.quota_hit
2448    {
2449        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.")));
2450    } else if let Some(stop) = head_e2e_stop.clone() {
2451        // Conclusive current-head E2E red settles directly to one actionable
2452        // machine hold instead of cycling through runnable `Failed` passes.
2453        // Refund only when this pass provably reconsumed an earlier stop with
2454        // no new verification events, idempotently across reclaim/re-settle.
2455        if crate::head_e2e_stop::reconsumed_without_new_verification(state, &stop) {
2456            reconsumed_head_e2e = true;
2457            let pass = state.passes.last().map_or(0, |p| p.index);
2458            if !task
2459                .passes
2460                .iter()
2461                .any(|p| p.run == state.id && p.pass_index == pass)
2462            {
2463                task.attempts = task.attempts.saturating_sub(1);
2464            }
2465        }
2466        let reason = crate::head_e2e_stop::hold_reason(task, state, &stop, None);
2467        task.hold_head_e2e(stop, reason, detail.to_owned());
2468    } else {
2469        settle_in(task, verdict, detail, max_attempts, p, Some(state));
2470    }
2471    if !verdict.parked
2472        && !verdict.quota_hit
2473        && !reconsumed_head_e2e
2474        && matches!(
2475            verdict.status,
2476            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2477        )
2478    {
2479        task.recovery_failed(state);
2480    }
2481    if state.prep_failure.is_some() {
2482        // Minting a run whose candidates could not be prepared is not work
2483        // on a newly approved attempt. Keep the unresolved outcome anchor.
2484        task.hold_notice_cause = unresolved;
2485        task.startup_notice_cause("startup-candidates");
2486    }
2487    // Written here, where the refund (or not) is decided, so the history is a
2488    // fact and not a later guess from the run's status.
2489    if let Some(pass) = state.passes.last() {
2490        let parked = match &pass.end {
2491            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2492            _ => None,
2493        };
2494        task.record_pass_at(
2495            &state.id,
2496            pass.index,
2497            Some(pass.started_at),
2498            attempts_before,
2499            parked,
2500        );
2501    }
2502    if task.status == TaskStatus::Held {
2503        if state.base_sync_blocked() {
2504            task.base_sync_notice(state);
2505        } else if state.land_sync_exhausted() {
2506            task.land_sync_notice(state);
2507        } else if let Some(stop) = &head_e2e_stop {
2508            task.head_e2e_notice(stop);
2509        } else if state.prep_failure.is_none() {
2510            task.notice_cause(
2511                label(verdict.status),
2512                Some(&state.id),
2513                state.passes.last().map(|p| p.index),
2514            );
2515        }
2516        task.diagnostic = diagnostic(state);
2517        note_open_question(task, &state.id, p);
2518    }
2519}
2520
2521/// If `task` is held with a `magi ask` question still open on `run`, name the
2522/// question in [`Task::hold_reason`] rather than leaving the hold reading
2523/// only [`describe`]'s run summary.
2524///
2525/// This is the shape task 20260928-191407-05fd left underspecified: an
2526/// implementer settled a verified no-op and filed a question for the
2527/// operator, and the hold that followed said nothing about the question
2528/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2529/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2530/// marker) and must keep seeing it unchanged.
2531///
2532/// Best-effort: an unreadable question store must not stop a run from
2533/// settling, so this is a no-op rather than a propagated error when
2534/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2535fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2536    let Some(home) = crate::run::try_home() else {
2537        return;
2538    };
2539    let open = Questions::at(home.join("questions")).open_for(run);
2540    let Some(q) = open.first() else {
2541        return;
2542    };
2543    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2544    decisions.sort_unstable();
2545    task.notice_cause(
2546        &format!("questions:{}", decisions.join(",")),
2547        Some(run),
2548        None,
2549    );
2550    let base = task.hold_reason.clone().unwrap_or_default();
2551    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2552}
2553
2554/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2555/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2556/// by some other means entirely, like a manual `magi run` resume that
2557/// finishes the graph outside the queue's bookkeeping.
2558///
2559/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2560/// `settle` is separate from `attempt`: a task recovered this way must land
2561/// exactly where a live daemon would have put it — the same policy table,
2562/// not a second one that quietly drifts from it — and that is only checkable
2563/// without spawning a real run.
2564fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2565    if let Some(request) = task.sync_only.clone() {
2566        crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2567        return;
2568    }
2569    match last_run {
2570        Some(state) => {
2571            let verdict = Verdict {
2572                status: state.status,
2573                left_pr: state.pr.is_some(),
2574                quota_hit: state.quota.iter().any(|loss| {
2575                    state
2576                        .passes
2577                        .last()
2578                        .is_none_or(|pass| loss.at >= pass.started_at)
2579                }),
2580                parked: state.parked,
2581                no_viable_candidates: state.viable().is_empty(),
2582            };
2583            let detail = format!(
2584                "{}{}",
2585                phrases(&state.config.graph.language).recovered_running,
2586                describe(&state)
2587            );
2588            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2589        }
2590        None => {
2591            // No run, so no config of its own: `language` is the task's
2592            // repository's setting, read by the caller.
2593            let why = phrases(language).no_run_to_recover;
2594            task.last_error = Some(why.to_owned());
2595            // The phone shows `hold_reason`, so a task held by the machine
2596            // says why there too and not only in `last_error`.
2597            task.notice_cause("missing-run", None, None);
2598            task.hold_machine(Some(why.to_owned()));
2599        }
2600    }
2601}
2602
2603/// Find every task left at `running` that no live process is actually
2604/// driving, and settle each one against whatever its last run became.
2605///
2606/// # Why a claim is proof, not a guess
2607///
2608/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2609/// `running`, and the guard is held for the task's whole time in that status:
2610/// `attempt` does not return, and the loop does not move past the scope
2611/// holding the claim, until the run has settled. So a `running` task whose
2612/// lock is gone cannot have a live owner — this process or any other —
2613/// without needing a staleness threshold or a pid check the way
2614/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2615/// task that never got as far as `running` at all. Taking the claim here is
2616/// the whole test: it either fails, because something really does hold it
2617/// and the task is left alone, or it succeeds, which is the proof — and it is
2618/// kept for the rest of the decision so nothing else can start a competing
2619/// run while this one is being written.
2620///
2621/// Called on every poll, not only at startup, for the reason
2622/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2623/// keep noticing this, not only on the one morning it happened to restart.
2624fn reclaim_orphaned_running(
2625    queue: &Queue,
2626    max_attempts: usize,
2627    live_workers: &std::collections::BTreeSet<String>,
2628) -> Vec<String> {
2629    let mut reclaimed = Vec::new();
2630    for listed in queue.list() {
2631        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2632            continue;
2633        }
2634        let Ok(_claim) = queue.claim(&listed.id) else {
2635            continue;
2636        };
2637        // Re-read under the claim: a release or an edit landed by a human
2638        // between the listing above and the claim just taken must not be
2639        // clobbered by a decision based on the stale copy.
2640        let Ok(mut task) = queue.get(&listed.id) else {
2641            continue;
2642        };
2643        if task.status != TaskStatus::Running {
2644            continue;
2645        }
2646        let last_run = task
2647            .execution_runs()
2648            .last()
2649            .and_then(|id| RunState::load(id).ok());
2650        // `execute` normally abandons a run's own open questions the moment
2651        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2652        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2653        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2654        // with the question still `open`, because the process died before
2655        // reaching that call. `reclaim` itself stays pure on purpose (see its
2656        // own doc), so the same cleanup runs here instead, against the run
2657        // this reclaim is already reading. `settle_run` costs nothing when
2658        // `execute` already got there first.
2659        if let Some(state) = &last_run
2660            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2661        {
2662            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2663        }
2664        let language = if last_run.is_none() {
2665            language_of(&task, Path::new("."))
2666        } else {
2667            String::new()
2668        };
2669        reclaim(&mut task, last_run, max_attempts, &language);
2670        if task.status == TaskStatus::Done {
2671            supersede_prior_runs(&task, &crate::run::home());
2672        }
2673        record(queue, &mut task);
2674        reclaimed.push(task.id.clone());
2675    }
2676    reclaimed
2677}
2678
2679/// Find every run whose `run.json` is provably dead — every seat it still
2680/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2681/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2682/// not merely "no daemon claims it" — and fail it, clearing the leftover
2683/// active seats so the run stops reading as `implementing` (or whichever
2684/// node) forever.
2685///
2686/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2687/// `running`, using whatever `run.json` already says — but nothing in that
2688/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2689/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2690/// never got back to sits exactly where it was left: `active` full of seats
2691/// nobody will ever answer for, `status` stuck on whatever node was in
2692/// flight. `magi show` already tells an operator this in prose (`no live
2693/// daemon claims this run right now`); this is what makes that fact durable
2694/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2695/// stay stuck once nothing is driving it.
2696///
2697/// Runs on every poll, not only at startup, for the reason
2698/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2699/// daemon up for days must keep noticing a run some other, now-dead, daemon
2700/// left behind just as readily as one it trips over on the way up.
2701///
2702/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2703/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2704/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2705/// `runs` directory instead: `home` here is a parameter precisely so a test
2706/// can point it away from the operator's real history (see [`drive`]'s own
2707/// doc), and a scan that fell through to the global home anyway would walk
2708/// whichever directory some *other* process or test pinned into that
2709/// `OnceLock` first — mutating runs this call was never handed.
2710fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2711    reclaim_abandoned_runs_with(
2712        home,
2713        now,
2714        crate::proc::pid_status,
2715        crate::proc::process_started_at,
2716    )
2717}
2718
2719/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2720/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2721/// for the identical reason: this sweep's real damage (wiping a run's active
2722/// seats and failing it) has to be provable against an injected answer in a
2723/// test, not just the real process table.
2724fn reclaim_abandoned_runs_with<F, G>(
2725    home: &Path,
2726    now: Timestamp,
2727    query: F,
2728    identity: G,
2729) -> Vec<String>
2730where
2731    F: Fn(u32) -> Option<bool>,
2732    G: Fn(u32) -> Option<String>,
2733{
2734    let mut abandoned = Vec::new();
2735    for entry in std::fs::read_dir(home.join("runs"))
2736        .into_iter()
2737        .flatten()
2738        .flatten()
2739    {
2740        let id = entry.file_name().to_string_lossy().into_owned();
2741        if !crate::run::is_run_id(&id) {
2742            continue;
2743        }
2744        // Serialize the proof and save with claims and takeover: a new
2745        // execution must not be overwritten after the liveness observation.
2746        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2747            continue;
2748        };
2749        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2750        // that module's docs for why a run this cannot parse is left alone
2751        // rather than guessed at. A different schema number is not that: this
2752        // touches only `status` and `active`, never a field whose meaning a
2753        // schema bump changed, so an old record's values serve this exactly
2754        // as well as a current one's (see `clean::read_state`'s own doc for
2755        // the same reasoning applied to folding).
2756        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2757            continue;
2758        };
2759        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2760            continue;
2761        };
2762        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2763            continue;
2764        }
2765        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2766        // it", which is also the normal, healthy shape of a manual `magi
2767        // run` / `magi review` sharing this same home — this scan walks
2768        // every run on disk, not only ones this daemon itself started. Such
2769        // a run's active seats can legitimately sit past their own timeout
2770        // for a little while (the CLI finishing up, its result still being
2771        // collected) without the process driving it having died. `liveness`
2772        // is what actually tells the two apart, by corroborating
2773        // `driver_pid` against the process it names — see its own doc. Only
2774        // its strongest, provable answer licenses wiping this run's active
2775        // seats and failing it out from under whatever is still running it.
2776        let daemon_claims = is_working_on(home, &id, now);
2777        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2778            != crate::run::Liveness::Dead
2779        {
2780            continue;
2781        }
2782        state.abandon("daemon");
2783        if let Err(e) = state.save_under(home) {
2784            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2785            continue;
2786        }
2787        // This run never passes through `Runner::execute` again, so its end
2788        // is announced here.
2789        if let Some(notice) = notices::run_ended(&state) {
2790            notices::raise_in(home, notice);
2791        }
2792        // The seat that asked is gone for good now, exactly like any other
2793        // door `graph::Runner::settle_questions` closes the moment `status`
2794        // lands somewhere non-resumable - see that method's own doc. Nothing
2795        // else reaches this one before the next `janitor()` startup pass
2796        // (`clean::abandon_settled_questions`), and a daemon that stays up
2797        // for days must not leave an open question badging the operator
2798        // until it happens to restart.
2799        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2800            tracing::warn!("abandon questions for {id}: {e:#}");
2801        }
2802        abandoned.push(id);
2803    }
2804    abandoned
2805}
2806
2807#[derive(Debug, Clone, Serialize, Deserialize)]
2808struct TaskWorker {
2809    opts: Opts,
2810    queue: PathBuf,
2811    task: String,
2812    #[serde(default)]
2813    lane: PermitKind,
2814    #[serde(default)]
2815    standalone: bool,
2816}
2817
2818#[doc(hidden)]
2819pub struct TaskWorkerLease {
2820    pub job: crate::worker::Job,
2821    dir: PathBuf,
2822    lease: Option<crate::worker::Lease>,
2823}
2824
2825impl TaskWorkerLease {
2826    pub fn release_lease(&mut self) {
2827        self.lease = None;
2828    }
2829}
2830
2831impl Drop for TaskWorkerLease {
2832    fn drop(&mut self) {
2833        self.release_lease();
2834        let _ = std::fs::remove_dir_all(&self.dir);
2835    }
2836}
2837
2838/// Reserve a task worker without launching a process, for integration tests.
2839#[doc(hidden)]
2840pub fn live_task_fixture(home: &Path, task: &str) -> Result<TaskWorkerLease> {
2841    let request = TaskWorker {
2842        opts: Opts::default(),
2843        queue: home.join("queue"),
2844        task: task.to_owned(),
2845        lane: PermitKind::default(),
2846        standalone: true,
2847    };
2848    let (job, lease) = crate::worker::running_fixture(
2849        home,
2850        &format!("task:{task}"),
2851        serde_json::to_value(request)?,
2852    )?;
2853    Ok(TaskWorkerLease {
2854        dir: home.join("workers").join("jobs").join(&job.id),
2855        job,
2856        lease: Some(lease),
2857    })
2858}
2859
2860fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2861    Ok(crate::worker::active(home)?
2862        .into_iter()
2863        .filter(|job| job.kind == "task")
2864        .collect())
2865}
2866
2867fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2868    task_jobs(home)?
2869        .into_iter()
2870        .filter_map(
2871            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2872                Ok(request) if !request.standalone => Some(Ok(job)),
2873                Ok(_) => None,
2874                Err(error) => Some(Err(error.into())),
2875            },
2876        )
2877        .collect()
2878}
2879
2880/// Whether an independent scheduler can be controlled without its web parent.
2881#[must_use]
2882pub fn managed(home: &Path) -> bool {
2883    match crate::worker::active(home) {
2884        Err(error) => {
2885            tracing::error!("cannot determine scheduler ownership: {error:#}");
2886            true
2887        }
2888        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2889        Ok(_) => {
2890            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2891                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2892        }
2893    }
2894}
2895
2896/// Start a detached, singleton scheduler using this executable generation.
2897pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2898    anyhow::ensure!(
2899        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2900        "the scheduler is stopping; wait for retirement before starting it again"
2901    );
2902    crate::worker::spawn(
2903        home,
2904        "scheduler",
2905        "scheduler",
2906        serde_json::to_value(opts.absolute()?)?,
2907    )
2908    .await
2909}
2910
2911fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2912    home.join("worker-parks").join(format!("{}.json", job.id))
2913}
2914
2915fn request_task_park(
2916    home: &Path,
2917    job: &crate::worker::Job,
2918    cause: crate::run::ParkCause,
2919) -> Result<()> {
2920    let path = park_request_path(home, job);
2921    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2922    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2923    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2924}
2925
2926/// Stop dispatch immediately; only an explicit park reaches existing workers.
2927pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2928    if control == crate::worker::Control::Park {
2929        for job in owned_task_jobs(home)? {
2930            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2931        }
2932    }
2933    crate::worker::request(home, "scheduler", control)
2934}
2935
2936/// Resolve what a restart would replace without signalling the scheduler.
2937pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
2938    if let Some(job) = crate::worker::active(home)?
2939        .into_iter()
2940        .find(|job| job.kind == "scheduler")
2941    {
2942        return serde_json::from_value(job.payload)
2943            .context("read detached scheduler options")
2944            .map(Some);
2945    }
2946    if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2947        && crate::worker::try_lease(home, "scheduler")?.is_none()
2948    {
2949        let path = home.join("scheduler-options.json");
2950        let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2951        return serde_json::from_slice(&body)
2952            .context("decode detached scheduler options")
2953            .map(Some);
2954    }
2955    Ok(None)
2956}
2957
2958/// Replace the scheduler, leaving all active task and conversation jobs alone.
2959pub async fn restart_detached(home: &Path) -> Result<()> {
2960    let Some(opts) = scheduler_restart_options(home)? else {
2961        return Ok(());
2962    };
2963    request_control(home, crate::worker::Control::Stop)?;
2964    loop {
2965        let reserved = crate::worker::active(home)?
2966            .iter()
2967            .any(|job| job.kind == "scheduler");
2968        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2969            break;
2970        }
2971        tokio::time::sleep(Duration::from_millis(100)).await;
2972    }
2973    spawn_detached(home, &opts).await?;
2974    Ok(())
2975}
2976
2977/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2978pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2979    let opts: Opts = serde_json::from_value(payload)?;
2980    let _ = home;
2981    serve_until(opts, Stop::new()).await
2982}
2983
2984/// Execute and settle one task with the queue claim owned by this process.
2985pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2986    let request: TaskWorker = serde_json::from_value(payload)?;
2987    let queue = Queue::at(request.queue);
2988    let key = format!("task:{}", request.task);
2989    let job = task_jobs(home)?
2990        .into_iter()
2991        .find(|job| job.key == key)
2992        .context("task worker reservation is missing")?;
2993    let park_path = park_request_path(home, &job);
2994    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2995    // our durable reservation. Never execute before that ownership hand-off.
2996    let _claim = loop {
2997        match queue.claim(&request.task) {
2998            Ok(claim) => break claim,
2999            // Only contention (the claim file exists) is worth waiting out; an
3000            // I/O failure must end this worker instead of pinning its lane.
3001            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
3002                return Err(e.context("claim the task for its worker"));
3003            }
3004            Err(_) => {
3005                sweep_stale_claims(&queue, STALE_CLAIM);
3006                tokio::time::sleep(Duration::from_millis(50)).await;
3007            }
3008        }
3009    };
3010    let mut task = queue.get(&request.task)?;
3011    if !task.status.runnable()
3012        || (!request.standalone
3013            && request.lane
3014                != permit_kind(
3015                    land_resume_state(&task) == LandResume::Ready,
3016                    task.immediate,
3017                    task.urgent,
3018                ))
3019    {
3020        return Ok(());
3021    }
3022    let stop = Stop::new();
3023    let watcher = {
3024        let home = home.to_path_buf();
3025        let stop = stop.clone();
3026        let park_path = park_path.clone();
3027        tokio::spawn(async move {
3028            loop {
3029                if crate::worker::control(&home, &key).ok().flatten().is_some() {
3030                    let cause = std::fs::read(&park_path)
3031                        .ok()
3032                        .and_then(|body| serde_json::from_slice(&body).ok())
3033                        .unwrap_or(crate::run::ParkCause::Operator);
3034                    stop.park(cause);
3035                    return;
3036                }
3037                tokio::time::sleep(Duration::from_millis(200)).await;
3038            }
3039        })
3040    };
3041    let quota = if request.standalone {
3042        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
3043    } else {
3044        let status = Arc::new(Mutex::new(Status::new()));
3045        Box::pin(attempt(
3046            &request.opts,
3047            &queue,
3048            &status,
3049            &stop,
3050            crate::graph::Pause::new(),
3051            &mut task,
3052        ))
3053        .await
3054    };
3055    watcher.abort();
3056    let _ = std::fs::remove_file(park_path);
3057    persist_cooldown(home, &quota).await?;
3058    Ok(())
3059}
3060
3061/// Launch the standalone task worker with a claim-to-reservation handoff.
3062/// Returns only after the worker owns a durable execution reservation.
3063pub async fn spawn_claimed(
3064    home: &Path,
3065    opts: &Opts,
3066    queue: &Queue,
3067    task: &Task,
3068    claim: crate::queue::Claim,
3069) -> Result<crate::worker::Job> {
3070    let request = TaskWorker {
3071        opts: opts.absolute()?,
3072        queue: std::path::absolute(queue.root())?,
3073        task: task.id.clone(),
3074        lane: permit_kind(
3075            land_resume_state(task) == LandResume::Ready,
3076            task.immediate,
3077            task.urgent,
3078        ),
3079        standalone: true,
3080    };
3081    let job = crate::worker::spawn(
3082        home,
3083        "task",
3084        &format!("task:{}", task.id),
3085        serde_json::to_value(request)?,
3086    )
3087    .await?;
3088    drop(claim);
3089    Ok(job)
3090}
3091
3092/// Transfer a standalone caller's claim only after the detached worker is live,
3093/// then follow that worker to its final (non-automatically-retrying) outcome.
3094pub async fn run_detached_claimed(
3095    opts: &Opts,
3096    queue: &Queue,
3097    task: &mut Task,
3098    claim: crate::queue::Claim,
3099) -> Result<()> {
3100    let home = crate::run::home();
3101    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
3102    loop {
3103        // Reconcile execution leases even without a scheduler. A dead worker
3104        // must become a reported failure, never an infinite persisted wait.
3105        crate::worker::active(&home)?;
3106        let current = crate::worker::get(&home, &job.id)?;
3107        if matches!(
3108            current.status,
3109            crate::worker::Status::Finished | crate::worker::Status::Failed
3110        ) {
3111            *task = queue.get(&task.id)?;
3112            anyhow::ensure!(
3113                current.status != crate::worker::Status::Failed,
3114                "task worker failed: {}",
3115                current.result.as_deref().unwrap_or("unknown failure")
3116            );
3117            return Ok(());
3118        }
3119        tokio::time::sleep(Duration::from_millis(200)).await;
3120    }
3121}
3122
3123async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
3124    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
3125        let _lease = loop {
3126            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
3127                break lease;
3128            }
3129            tokio::time::sleep(Duration::from_millis(10)).await;
3130        };
3131        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
3132            let path = home.join("task-quota-cooldown.json");
3133            let temporary = path.with_extension("json.tmp");
3134            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
3135            std::fs::rename(temporary, path)?;
3136        }
3137    }
3138    Ok(())
3139}
3140
3141fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
3142    match std::fs::read(home.join("task-quota-cooldown.json")) {
3143        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
3144        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
3145        Err(error) => Err(error.into()),
3146    }
3147}
3148
3149/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
3150///
3151/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
3152/// sets, so there is one loop body rather than two that drift apart the first
3153/// time the retry policy changes on only one of them.
3154pub async fn serve(opts: Opts) -> Result<()> {
3155    tracing::info!(
3156        "automatic update and restart requires magi web; standalone serve does not restart"
3157    );
3158    serve_until(opts, Stop::new()).await
3159}
3160
3161/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
3162///
3163/// A stop retires dispatch promptly, including while a worker launch is being
3164/// acknowledged. Already reserved workers own their attempts independently and
3165/// finish with their started executable. Explicit park additionally forwards
3166/// durable park requests; neither scheduler retirement nor update does so.
3167///
3168/// While the queue is empty the stop is honoured within one wakeup rather than
3169/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
3170/// caller that taps stop does not sit through the remainder of a sleep.
3171pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
3172    let opts = opts.absolute()?;
3173    let home = crate::run::home();
3174    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
3175        .context("another scheduler already owns this home")?;
3176    if let Some(reading) = read_status(&home)
3177        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
3178    {
3179        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
3180    }
3181    if !crate::worker::active(&home)?
3182        .iter()
3183        .any(|job| job.kind == "scheduler")
3184    {
3185        crate::worker::clear_control(&home, "scheduler")?;
3186    }
3187    std::fs::write(
3188        home.join("scheduler-options.json"),
3189        serde_json::to_vec(&opts)?,
3190    )?;
3191    let control = {
3192        let home = home.clone();
3193        let stop = stop.clone();
3194        tokio::spawn(async move {
3195            loop {
3196                match crate::worker::control(&home, "scheduler").ok().flatten() {
3197                    Some(crate::worker::Control::Park) => {
3198                        let _ = request_control(&home, crate::worker::Control::Park);
3199                        stop.park(crate::run::ParkCause::Operator);
3200                        break;
3201                    }
3202                    Some(crate::worker::Control::Stop) => {
3203                        stop.stop();
3204                        break;
3205                    }
3206                    None => {}
3207                }
3208                tokio::time::sleep(Duration::from_millis(100)).await;
3209            }
3210        })
3211    };
3212    let signal = {
3213        let stop = stop.clone();
3214        tokio::spawn(async move {
3215            if tokio::signal::ctrl_c().await.is_ok() {
3216                stop.stop();
3217                tracing::info!("scheduler shutdown requested; independent workers continue");
3218            }
3219        })
3220    };
3221
3222    let worktrees_root = opts
3223        .worktrees_root
3224        .clone()
3225        .unwrap_or_else(crate::run::default_worktree_root);
3226    let outcome = drive(
3227        &opts,
3228        &Queue::open(),
3229        &status_path(),
3230        &crate::run::home(),
3231        &worktrees_root,
3232        &stop,
3233    )
3234    .await;
3235
3236    signal.abort();
3237    control.abort();
3238    outcome
3239}
3240
3241/// The loop proper: setup, poll, teardown, with the queue and the status file
3242/// supplied rather than discovered.
3243///
3244/// All three of `home`, `worktrees_root` and the queue/status paths are
3245/// parameters rather than resolved here, for the same reason:
3246/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
3247/// so a unit test that pinned it would fight every other test in the binary,
3248/// and a loop that resolved its own worktree bay could only be exercised
3249/// against the operator's real `~/wt/<repo>` - publishing over a live
3250/// daemon's status file, claiming tasks out of a live backlog, and, since
3251/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
3252/// whatever the operator actually has on disk.
3253async fn drive(
3254    opts: &Opts,
3255    queue: &Queue,
3256    status_file: &Path,
3257    home: &Path,
3258    worktrees_root: &Path,
3259    stop: &Stop,
3260) -> Result<()> {
3261    // The status file is a *snapshot*, not a stream of events: a reader only
3262    // ever wants the latest values, and every tick rewrites the whole file
3263    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
3264    // while an mpsc channel would force the loop to re-send unchanged fields on
3265    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
3266    // for no gain. The lock is only ever held across a field assignment, never
3267    // across an await.
3268    let recovery_cfg = prepare(&opts.repo, opts).ok();
3269    let daemon_cfg = recovery_cfg
3270        .as_ref()
3271        .map(|c| c.daemon.clone())
3272        .unwrap_or_default();
3273    let reconciled = crate::driver::reconcile(home);
3274    if !reconciled.is_empty() {
3275        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3276    }
3277    let mut initial_status = Status::new();
3278    let owned = owned_task_jobs(home)?;
3279    initial_status.current = current_work(home, Timestamp::now())
3280        .into_iter()
3281        .filter(|current| {
3282            owned
3283                .iter()
3284                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3285        })
3286        .collect();
3287    initial_status.idle = initial_status.current.is_empty();
3288    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3289        recovery_cfg.as_ref(),
3290        daemon_cfg.max_deputies,
3291    ));
3292    let status = Arc::new(Mutex::new(initial_status));
3293    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3294    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3295
3296    // Read once at startup, not per task: how many runs this loop drives at
3297    // once is a property of the machine running it, not of whichever
3298    // repository a given task happens to name - see
3299    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
3300    // fact in the same sense the agent roster is.
3301    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3302
3303    tracing::info!(
3304        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3305        queue.root().display(),
3306        opts.poll.as_secs(),
3307        opts.max_attempts,
3308        concurrency,
3309        if daemon_cfg.pause_for_interrupts {
3310            ", interrupts enabled"
3311        } else {
3312            ""
3313        }
3314    );
3315
3316    let outcome = tokio::select! {
3317        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3318            max_concurrent: concurrency,
3319            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3320            recovery_cfg,
3321        }) => outcome,
3322        () = async {
3323            while !stop.stopped() {
3324                tokio::time::sleep(Duration::from_millis(25)).await;
3325            }
3326        } => {
3327            if stop.parking() {
3328                request_control(home, crate::worker::Control::Park)?;
3329            }
3330            Ok(())
3331        }
3332    };
3333
3334    stop.busy.store(0, Ordering::SeqCst);
3335    beat.abort();
3336    clear_status_at(status_file);
3337    outcome
3338}
3339
3340/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3341/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3342pub(crate) fn release_watch_settings_from_config(
3343    home: &Path,
3344    repo: &Path,
3345    cfg: &Config,
3346) -> (Vec<PathBuf>, u64) {
3347    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3348        .into_iter()
3349        .map(|r| r.path)
3350        .collect();
3351    // Repositories the daemon has worked in, wherever they live: a task may
3352    // name one outside `[repos] roots`, and its release PR must be watched too.
3353    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3354        .list()
3355        .into_iter()
3356        .map(|t| t.repo)
3357        .collect();
3358    let runs = home.join("runs");
3359    for id in crate::run::list_ids_in(&runs) {
3360        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3361            .ok()
3362            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3363            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3364        known.extend(repo);
3365    }
3366    for k in known {
3367        let k = k.canonicalize().unwrap_or(k);
3368        if k.join(".git").exists() && !paths.contains(&k) {
3369            paths.push(k);
3370        }
3371    }
3372    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3373    if !paths.contains(&own) {
3374        paths.push(own);
3375    }
3376    (paths, cfg.daemon.release_stall_minutes)
3377}
3378
3379/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3380const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3381
3382/// Refresh the status file on a fixed tick.
3383///
3384/// Separate from the loop because a run takes tens of minutes: a status file
3385/// written only between tasks would look stale for the whole of every run, and
3386/// a reader would report the daemon dead exactly while it was busiest.
3387async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3388    loop {
3389        tokio::time::sleep(HEARTBEAT).await;
3390        let snapshot = {
3391            let mut guard = lock(&status);
3392            guard.updated_at = Timestamp::now();
3393            guard.clone()
3394        };
3395        if let Err(e) = write_status_to(&path, &snapshot) {
3396            // A failed heartbeat must not take the daemon down: the loop is the
3397            // product, the status file is only the window onto it.
3398            tracing::warn!("could not refresh the daemon status file: {e:#}");
3399        }
3400    }
3401}
3402
3403/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3404/// if so, whether that wait is over.
3405#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3406enum LandResume {
3407    /// The task's last run is not parked on a land approval; schedule it
3408    /// like any other candidate.
3409    NotLanding,
3410    /// Parked in `land`, waiting on a question nobody has answered yet.
3411    /// Left alone: attempting it now would only re-observe the same pull
3412    /// request and park again, spending a `gh` call on a decision that has
3413    /// not changed since the last time this was checked.
3414    StillWaiting,
3415    /// Parked in `land`, and the question is settled - answered or
3416    /// abandoned. Resuming this is the one kind of candidate that must not
3417    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3418    Ready,
3419}
3420
3421/// Classify a runnable candidate by whether it is parked on a land-merge
3422/// approval. Read-only - no claim taken, nothing written - so it is cheap
3423/// enough to call on every candidate, every poll.
3424fn land_resume_state(task: &Task) -> LandResume {
3425    if task.sync_only.is_some() {
3426        return LandResume::NotLanding;
3427    }
3428    let Some(run_id) = task.execution_runs().last() else {
3429        return LandResume::NotLanding;
3430    };
3431    let Ok(state) = RunState::load(run_id) else {
3432        return LandResume::NotLanding;
3433    };
3434    if !state.parked {
3435        return LandResume::NotLanding;
3436    }
3437    if state.status == RunStatus::Landing
3438        && state.land_approval.as_ref().is_some_and(|binding| {
3439            ask::Questions::open()
3440                .get_for_effects(&binding.question)
3441                .is_ok_and(|q| {
3442                    q.run == state.id
3443                        && q.resolution()
3444                            .as_deref()
3445                            .is_some_and(crate::merge_decision::stops)
3446                })
3447        })
3448    {
3449        return LandResume::Ready;
3450    }
3451    if !implementers_match(task, &state) {
3452        return LandResume::NotLanding;
3453    }
3454    // Parked in `land` on the merge approval, or at `merge` on the owner's
3455    // word about a title/body the posting gate withheld. Told apart by the
3456    // run's own record, not by a status both can share.
3457    let node = if state.status == RunStatus::Landing {
3458        land::APPROVAL_NODE
3459    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3460        crate::github_text::ASK_NODE
3461    } else {
3462        return LandResume::NotLanding;
3463    };
3464    let store = ask::Questions::open();
3465    let waiting = store
3466        .list_for_effects()
3467        .into_iter()
3468        .filter(|q| &q.run == run_id && q.node == node)
3469        .max_by(|a, b| a.id.cmp(&b.id));
3470    let Some(mut q) = waiting else {
3471        return LandResume::Ready;
3472    };
3473    if !q.status.open() {
3474        // Repair spends agent resources and must obey concurrency and quota
3475        // waits; only a merge/hold decision may use the decision-only lane.
3476        if q.resolution().as_deref() == Some(land::REPAIR) {
3477            return if state.liveness(false) == Liveness::Live {
3478                LandResume::StillWaiting
3479            } else {
3480                LandResume::NotLanding
3481            };
3482        }
3483        return LandResume::Ready;
3484    }
3485    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3486    // nobody ever answered; land's approval bypasses that wait entirely (see
3487    // `land::approval_gate`), so the same deadline has to be enforced here
3488    // instead, or `graph.answer_timeout` silently stops meaning anything for
3489    // a land approval and a run can sit `StillWaiting` forever with nobody
3490    // told to look at it.
3491    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3492    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3493    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3494        q.abandon(format!(
3495            "no answer within {}s of asking",
3496            timeout.as_secs().max(1)
3497        ));
3498        // If this can't be persisted, do not treat the wait as settled on a
3499        // guess: fall through and try again next poll.
3500        if store.put(&mut q).is_ok() {
3501            return LandResume::Ready;
3502        }
3503    }
3504    LandResume::StillWaiting
3505}
3506
3507/// How often the loop rechecks for new work while something it already
3508/// started is still running, rather than sleeping out the whole
3509/// [`Opts::poll`] interval.
3510///
3511/// Short on purpose: this is what lets a land-merge approval that comes back
3512/// while another task is mid-competition be noticed and resumed within a
3513/// fraction of a second, not within the next multi-second poll.
3514const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3515
3516/// How often [`poll`] rechecks the shared build cache against its cap at a
3517/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3518/// waiting for the queue to run dry.
3519///
3520/// A queue that never empties means the `janitor` call at the bottom of this
3521/// loop's fully-idle branch can go unreached for as long as the backlog
3522/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3523/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3524/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3525/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3526/// backlog of short tasks does not pay for that walk on every poll.
3527const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3528
3529/// State of [`poll`]'s own interrupt-scheduling sequence - see
3530/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3531/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3532/// both kept free of `Task`'s non-identity fields on purpose: every decision
3533/// here turns only on task ids and which ones are in flight, so the "never
3534/// more than one run at once" and "exactly one resume" invariants can be
3535/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3536/// queue - which is exactly the coverage this feature's first two attempts
3537/// were missing.
3538///
3539/// Persisted after every transition, so scheduler replacement preserves the
3540/// interrupt's exclusive turn and the interrupted task's priority resume.
3541#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3542enum Interrupt {
3543    /// No interrupt sequence in progress. Ordinary dispatch applies.
3544    Idle,
3545    /// `interrupt_task` is runnable and exactly one other run is in flight;
3546    /// `parked` names that one task's id. Dispatch is withheld from
3547    /// everyone, including `interrupt_task` itself, until it has left
3548    /// flight - only then is `interrupt_task` let through.
3549    ///
3550    /// `parked` is a `Vec` rather than a bare id for symmetry with
3551    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3552    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3553    /// when exactly one run is in flight, so it is guaranteed to hold
3554    /// exactly one entry in practice - see that branch's own doc for why
3555    /// more than one is deliberately never attempted.
3556    Parking {
3557        parked: Vec<String>,
3558        interrupt_task: String,
3559    },
3560    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3561    /// withheld from everyone until it leaves flight - merged, failed, held,
3562    /// it makes no difference - at which point the sequence moves to
3563    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3564    /// going straight to `Idle` would hand `parked` back to ordinary
3565    /// priority-order dispatch, where a higher-priority task filed in the
3566    /// meantime could start ahead of it.
3567    Running {
3568        parked: Vec<String>,
3569        interrupt_task: String,
3570    },
3571    /// `interrupt_task` left flight; `parked` still names the one run this
3572    /// sequence owes a resume. Dispatch is withheld from everyone except
3573    /// that task - see [`interrupt_gate`] - so the resume this feature
3574    /// promises is never raced by, or run alongside, an unrelated candidate.
3575    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3576    /// own doc on abandonment - the moment it is no longer runnable at all.
3577    Resuming { parked: Vec<String> },
3578}
3579
3580/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3581/// and `runnable` are read-only snapshots of this tick's reality, and the
3582/// only side effect the caller still owes the world is asking whichever
3583/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3584/// site.
3585///
3586/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3587/// accepted rather than a narrower type because that is what [`poll`] already
3588/// has on hand from [`runnable`], and building a second, smaller list on
3589/// every tick just to satisfy this signature would cost more than it proves.
3590///
3591/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3592/// back to a task they are waiting on no longer being [`runnable`] - held,
3593/// blocked, deleted, or finished by some other means entirely, all of which
3594/// an operator can do to a task sitting in the queue with no claim on it at
3595/// all, at any moment, interrupt sequence or not. Without this check the
3596/// sequence would wait forever for a dispatch that can never come, and
3597/// `interrupt_gate` would withhold every other task in the queue right along
3598/// with it - a single `magi task hold` on the wrong id turning into a
3599/// daemon that never dispatches anything again.
3600fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3601    match state {
3602        Interrupt::Idle => {
3603            // Not just "something to interrupt": exactly one thing. More
3604            // than one run in flight only happens above the default
3605            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3606            // one resume, never run alongside anything else" only because
3607            // it is only ever seeded with exactly one id - see
3608            // `Interrupt::Resuming`'s own doc on why releasing more than one
3609            // parked id back to ordinary dispatch cannot be made safe
3610            // against that same setting's own extra concurrency slots.
3611            // Waiting here for the herd to settle to one is the
3612            // simplification this feature's own constraints ask for rather
3613            // than a second concurrency model to reconcile with the first.
3614            if in_flight.len() != 1 {
3615                return Interrupt::Idle;
3616            }
3617            match runnable.iter().find(|t| t.interrupt) {
3618                Some(t) => Interrupt::Parking {
3619                    parked: in_flight.to_vec(),
3620                    interrupt_task: t.id.clone(),
3621                },
3622                None => Interrupt::Idle,
3623            }
3624        }
3625        Interrupt::Parking {
3626            parked,
3627            interrupt_task,
3628        } => {
3629            if in_flight.iter().any(|id| parked.contains(id)) {
3630                // Still waiting for what was in flight to actually stop.
3631                Interrupt::Parking {
3632                    parked,
3633                    interrupt_task,
3634                }
3635            } else if in_flight.contains(&interrupt_task) {
3636                Interrupt::Running {
3637                    parked,
3638                    interrupt_task,
3639                }
3640            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3641                // The parked run(s) are gone, but the interrupt task has not
3642                // been dispatched yet on this tick - `interrupt_gate` is
3643                // what lets it through next.
3644                Interrupt::Parking {
3645                    parked,
3646                    interrupt_task,
3647                }
3648            } else {
3649                // The interrupt task itself is no longer runnable - see this
3650                // function's own doc on abandonment. The parked run(s) still
3651                // get their guaranteed resume; there is simply no interrupt
3652                // to run ahead of them any longer.
3653                Interrupt::Resuming { parked }
3654            }
3655        }
3656        Interrupt::Running {
3657            parked,
3658            interrupt_task,
3659        } => {
3660            if in_flight.contains(&interrupt_task) {
3661                Interrupt::Running {
3662                    parked,
3663                    interrupt_task,
3664                }
3665            } else {
3666                // The interrupt task's own run reached a terminal status,
3667                // whichever one - this is the *only* trigger that moves the
3668                // sequence on, driven straight off the same in-flight
3669                // bookkeeping `poll` already reaps every tick, not a second,
3670                // independent poll of anything.
3671                Interrupt::Resuming { parked }
3672            }
3673        }
3674        Interrupt::Resuming { parked } => {
3675            if in_flight.iter().any(|id| parked.contains(id)) {
3676                // One of the parked runs has been dispatched - the resume
3677                // this sequence owed is fulfilled. Whatever else is left in
3678                // `parked` (ordinarily nothing, at the default concurrency
3679                // of one) rejoins ordinary priority-order dispatch, same as
3680                // any other runnable task.
3681                Interrupt::Idle
3682            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3683                Interrupt::Resuming { parked }
3684            } else {
3685                // Abandonment (see this function's own doc): nothing left in
3686                // `parked` is even runnable any longer.
3687                Interrupt::Idle
3688            }
3689        }
3690    }
3691}
3692
3693/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3694/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3695/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3696/// indistinguishable from any other runnable task - exactly the "off does
3697/// nothing" this feature promises.
3698fn advance_interrupt_tick(
3699    enabled: bool,
3700    state: Interrupt,
3701    in_flight: &[String],
3702    runnable: &[Task],
3703) -> Interrupt {
3704    if !enabled {
3705        return Interrupt::Idle;
3706    }
3707    advance_interrupt(state, in_flight, runnable)
3708}
3709
3710/// Which of this tick's runnable candidates the interrupt sequence actually
3711/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3712/// each half is assertable on its own: this is the half that keeps a
3713/// competition and an interrupt from ever running at the same moment.
3714fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3715    match state {
3716        Interrupt::Idle => candidates,
3717        Interrupt::Parking {
3718            parked,
3719            interrupt_task,
3720        } => {
3721            if in_flight.iter().any(|id| parked.contains(id)) {
3722                Vec::new()
3723            } else {
3724                candidates
3725                    .into_iter()
3726                    .filter(|t| &t.id == interrupt_task)
3727                    .collect()
3728            }
3729        }
3730        Interrupt::Running { .. } => Vec::new(),
3731        // At most one: even if `parked` names more than one id (more than
3732        // one run was in flight when the sequence began, only possible
3733        // above the default `max_concurrent_runs = 1`), only the first match
3734        // is offered. Capping this to a single candidate - not merely to
3735        // `parked`'s own ids - is what makes "exactly one resume, never two
3736        // dispatched together" true regardless of how many ordinary slots
3737        // happen to be free this tick.
3738        Interrupt::Resuming { parked } => candidates
3739            .into_iter()
3740            .find(|t| parked.contains(&t.id))
3741            .into_iter()
3742            .collect(),
3743    }
3744}
3745
3746/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3747/// bundled into one parameter so `poll`'s own signature stays readable -
3748/// see [`drive`]'s call site for where these are actually read.
3749struct DispatchLimits {
3750    /// How many *ordinary* candidates run at once. See
3751    /// [`crate::config::Daemon::max_concurrent_runs`].
3752    max_concurrent: usize,
3753    /// See [`crate::config::Daemon::pause_for_interrupts`].
3754    pause_for_interrupts: bool,
3755    recovery_cfg: Option<Config>,
3756}
3757
3758/// Which semaphore, if any, dispatching a candidate should draw its permit
3759/// from.
3760///
3761/// Pure and separate from [`poll`]'s loop body for the same reason
3762/// [`advance_interrupt`] is: the choice between "decision-only land resume",
3763/// "owner-selected immediate lane", "spend the one urgent slot" and "spend an
3764/// ordinary slot" is explicit and directly unit-testable.
3765#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3766pub(crate) enum PermitKind {
3767    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3768    /// Checked first - a task can be both a land resume and marked
3769    /// [`Task::immediate`] or [`Task::urgent`], and the resume's own
3770    /// decision-only lane takes precedence.
3771    None,
3772    /// [`Task::immediate`]: owner-selected immediate execution lane.
3773    /// Consumes no semaphore permit and does not count against ordinary or
3774    /// urgent capacity, allowing multiple immediate tasks to dispatch even
3775    /// when both ordinary and urgent lanes are full. Kept distinct from
3776    /// [`PermitKind::None`] so decision-only resumes and immediate runs stay
3777    /// separable in persisted worker reservations and diagnostics.
3778    Immediate,
3779    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3780    /// (never in addition to trying) the ordinary pool. This is what lets
3781    /// an urgent task dispatch while every ordinary slot is already checked
3782    /// out, and what stops a second urgent task from opening a third run: it
3783    /// waits on this same one-slot semaphore rather than falling through to
3784    /// the ordinary one.
3785    Urgent,
3786    /// The ordinary `max_concurrent_runs` pool - unaffected by any of the
3787    /// above.
3788    #[default]
3789    Ordinary,
3790}
3791
3792impl PermitKind {
3793    pub(crate) fn label(self) -> &'static str {
3794        match self {
3795            Self::None => "decision",
3796            Self::Immediate => "immediate",
3797            Self::Urgent => "urgent",
3798            Self::Ordinary => "ordinary",
3799        }
3800    }
3801}
3802
3803/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3804/// own boolean, already computed by the caller from [`land_resume_state`].
3805/// Precedence: decision resume (`None`) > `Immediate` > `Urgent` > `Ordinary`.
3806fn permit_kind(priority: bool, immediate: bool, urgent: bool) -> PermitKind {
3807    if priority {
3808        PermitKind::None
3809    } else if immediate {
3810        PermitKind::Immediate
3811    } else if urgent {
3812        PermitKind::Urgent
3813    } else {
3814        PermitKind::Ordinary
3815    }
3816}
3817
3818fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3819    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3820        (0usize, 0usize),
3821        |(ordinary, urgent), request| match request.lane {
3822            PermitKind::Ordinary => (ordinary + 1, urgent),
3823            PermitKind::Urgent => (ordinary, urgent + 1),
3824            PermitKind::Immediate | PermitKind::None => (ordinary, urgent),
3825        },
3826    );
3827    (
3828        limit.saturating_sub(ordinary),
3829        1usize.saturating_sub(urgent),
3830    )
3831}
3832
3833/// Why a runnable candidate was not dispatched. This does not alter policy.
3834#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3835enum SkipReason {
3836    ClaimUnavailable,
3837    RereadFailed,
3838    NoLongerRunnable,
3839    WaitingOnLanding,
3840    CoolingDown,
3841    OrdinaryCapacity,
3842    UrgentCapacity,
3843    InterruptGate,
3844}
3845
3846impl SkipReason {
3847    fn key(self) -> &'static str {
3848        match self {
3849            Self::ClaimUnavailable => "claim_unavailable",
3850            Self::RereadFailed => "reread_failed",
3851            Self::NoLongerRunnable => "no_longer_runnable",
3852            Self::WaitingOnLanding => "waiting_on_landing",
3853            Self::CoolingDown => "cooling_down",
3854            Self::OrdinaryCapacity => "ordinary_capacity",
3855            Self::UrgentCapacity => "urgent_capacity",
3856            Self::InterruptGate => "interrupt_gate",
3857        }
3858    }
3859
3860    fn describe(self) -> &'static str {
3861        match self {
3862            Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3863            Self::RereadFailed => "could not re-read it",
3864            Self::NoLongerRunnable => "no longer runnable",
3865            Self::WaitingOnLanding => "waiting on landing",
3866            Self::CoolingDown => "quota cooldown",
3867            Self::OrdinaryCapacity => "no free ordinary slot",
3868            Self::UrgentCapacity => "urgent slot busy",
3869            Self::InterruptGate => "withheld by the interrupt sequence",
3870        }
3871    }
3872}
3873
3874/// A reason count from a completed dispatch scan.
3875#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3876pub struct DispatchReasonCount {
3877    /// Stable string key, so readers can preserve future reasons.
3878    pub reason: String,
3879    /// Candidates skipped for this reason.
3880    pub count: usize,
3881}
3882
3883/// Observations from a completed scan, not a fresh queue estimate.
3884#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3885pub struct DispatchWait {
3886    /// Runnable candidates before the interrupt gate.
3887    pub runnable: usize,
3888    /// Counts in descending order, with stable reason order for ties.
3889    pub reasons: Vec<DispatchReasonCount>,
3890}
3891
3892type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3893
3894fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3895    if runnable == 0 {
3896        return None;
3897    }
3898    let mut counts = std::collections::BTreeMap::new();
3899    for (_, reason) in skips {
3900        *counts.entry(*reason).or_insert(0usize) += 1;
3901    }
3902    let mut counts: Vec<_> = counts.into_iter().collect();
3903    counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3904    Some(DispatchWait {
3905        runnable,
3906        reasons: counts
3907            .into_iter()
3908            .map(|(reason, count)| DispatchReasonCount {
3909                reason: reason.key().to_owned(),
3910                count,
3911            })
3912            .collect(),
3913    })
3914}
3915
3916fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3917    before
3918        .iter()
3919        .filter(|id| !after.iter().any(|task| &task.id == *id))
3920        .map(|id| (id.clone(), SkipReason::InterruptGate))
3921        .collect()
3922}
3923
3924fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3925    if *previous == current {
3926        return false;
3927    }
3928    *previous = current;
3929    true
3930}
3931
3932/// Read-only task-level admission view shared by CLI (`magi task list` / `show`)
3933/// and Web (`TaskView`). Distinguishes configured mode, active persisted
3934/// reservation lane, and concrete blockers without ever mutating state.
3935#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3936pub struct TaskAdmission {
3937    /// Configured dispatch mode from the task record (`"immediate"`, `"urgent"`, `"ordinary"`).
3938    pub mode: &'static str,
3939    /// Persisted active worker reservation lane, if currently reserved/running
3940    /// (`"decision"`, `"immediate"`, `"urgent"`, `"ordinary"`).
3941    #[serde(default, skip_serializing_if = "Option::is_none")]
3942    pub reservation_lane: Option<&'static str>,
3943    /// True when the active worker reservation is standalone (`magi run`/`review`).
3944    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3945    pub standalone: bool,
3946    /// Admission state: `"next_poll"`, `"waiting"`, `"running"`, `"completed"`, `"unknown"`.
3947    pub state: &'static str,
3948    /// Human-readable admission status label (e.g. `"Immediate: next poll"`,
3949    /// `"Immediate: waiting — ..."`).
3950    pub label: String,
3951    /// Concrete blocker or unconfirmed-state diagnostic when waiting/unknown/resource-blocked.
3952    #[serde(default, skip_serializing_if = "Option::is_none")]
3953    pub blocker: Option<String>,
3954}
3955
3956/// One read-only snapshot of scheduler, worker, cooldown, and interrupt state
3957/// captured once per list or detail request.
3958#[derive(Debug, Clone)]
3959pub struct AdmissionSnapshot {
3960    now: Timestamp,
3961    daemon: std::result::Result<Option<Reading>, String>,
3962    scheduler_running: bool,
3963    active_workers:
3964        std::result::Result<std::collections::BTreeMap<String, (PermitKind, bool)>, String>,
3965    owned_in_flight: Vec<String>,
3966    owned_ordinary_count: usize,
3967    urgent_busy: bool,
3968    cache_service_active: bool,
3969    cooldown_until: std::result::Result<Option<Timestamp>, String>,
3970    interrupt: std::result::Result<Interrupt, String>,
3971}
3972
3973fn read_status_checked(home: &Path) -> std::result::Result<Option<Reading>, String> {
3974    let path = home.join("daemon.json");
3975    match std::fs::read_to_string(&path) {
3976        Ok(body) => serde_json::from_str(&body)
3977            .map(Some)
3978            .map_err(|e| format!("parse {}: {e}", path.display())),
3979        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
3980        Err(e) => Err(format!("read {}: {e}", path.display())),
3981    }
3982}
3983
3984fn read_interrupt_checked(home: &Path) -> std::result::Result<Interrupt, String> {
3985    let path = home.join("scheduler-interrupt.json");
3986    match std::fs::read(&path) {
3987        Ok(body) => {
3988            serde_json::from_slice(&body).map_err(|e| format!("parse {}: {e}", path.display()))
3989        }
3990        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Interrupt::Idle),
3991        Err(e) => Err(format!("read {}: {e}", path.display())),
3992    }
3993}
3994
3995fn skip_reason_label(key: &str) -> String {
3996    match key {
3997        "claim_unavailable" => "claimed by another process".to_owned(),
3998        "reread_failed" => "could not re-read task".to_owned(),
3999        "no_longer_runnable" => "no longer runnable".to_owned(),
4000        "waiting_on_landing" => "waiting on merge/posting approval".to_owned(),
4001        "cooling_down" => "quota cooldown".to_owned(),
4002        "ordinary_capacity" => "no free ordinary slot".to_owned(),
4003        "urgent_capacity" => "urgent slot busy".to_owned(),
4004        "interrupt_gate" => "withheld by active interrupt sequence".to_owned(),
4005        other => other.replace('_', " "),
4006    }
4007}
4008
4009/// Pure read-only companion to [`land_resume_state`]: reads `home` explicitly
4010/// and never abandons or writes any question file.
4011fn land_resume_state_readonly(task: &Task, home: &Path, now: Timestamp) -> LandResume {
4012    if task.sync_only.is_some() {
4013        return LandResume::NotLanding;
4014    }
4015    let Some(run_id) = task.execution_runs().last() else {
4016        return LandResume::NotLanding;
4017    };
4018    let Ok(state) = RunState::load_under(run_id, home) else {
4019        return LandResume::NotLanding;
4020    };
4021    if !state.parked {
4022        return LandResume::NotLanding;
4023    }
4024    let store = ask::Questions::at(home.join("questions"));
4025    if state.status == RunStatus::Landing
4026        && state.land_approval.as_ref().is_some_and(|binding| {
4027            store.get_for_effects(&binding.question).is_ok_and(|q| {
4028                q.run == state.id
4029                    && q.resolution()
4030                        .as_deref()
4031                        .is_some_and(crate::merge_decision::stops)
4032            })
4033        })
4034    {
4035        return LandResume::Ready;
4036    }
4037    if !implementers_match(task, &state) {
4038        return LandResume::NotLanding;
4039    }
4040    let node = if state.status == RunStatus::Landing {
4041        land::APPROVAL_NODE
4042    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
4043        crate::github_text::ASK_NODE
4044    } else {
4045        return LandResume::NotLanding;
4046    };
4047    let waiting = store
4048        .list_for_effects()
4049        .into_iter()
4050        .filter(|q| &q.run == run_id && q.node == node)
4051        .max_by(|a, b| a.id.cmp(&b.id));
4052    let Some(q) = waiting else {
4053        return LandResume::Ready;
4054    };
4055    if !q.status.open() {
4056        if q.resolution().as_deref() == Some(land::REPAIR) {
4057            return if is_working_on(home, &state.id, now) {
4058                LandResume::StillWaiting
4059            } else {
4060                LandResume::NotLanding
4061            };
4062        }
4063        return LandResume::Ready;
4064    }
4065    LandResume::StillWaiting
4066}
4067
4068impl AdmissionSnapshot {
4069    /// Capture scheduler, worker, cooldown, and interrupt state once, read-only.
4070    #[must_use]
4071    pub fn capture(home: &Path, now: Timestamp) -> Self {
4072        let daemon = read_status_checked(home);
4073        let scheduler_running = daemon
4074            .as_ref()
4075            .ok()
4076            .and_then(Option::as_ref)
4077            .is_some_and(|reading| reading.running(now));
4078        let mut cache_service_active = false;
4079        let mut owned_in_flight = Vec::new();
4080        let mut owned_ordinary_count = 0usize;
4081        let mut urgent_busy = false;
4082        let active_workers = match crate::worker::observe_active_detailed(home) {
4083            Ok(entries) => {
4084                let mut map = std::collections::BTreeMap::new();
4085                let mut parse_err = None;
4086                for entry in entries {
4087                    if entry.job.key == "service:daemon-cache" {
4088                        cache_service_active = true;
4089                        continue;
4090                    }
4091                    if entry.job.kind != "task" {
4092                        continue;
4093                    }
4094                    match serde_json::from_value::<TaskWorker>(entry.job.payload) {
4095                        Ok(request) => {
4096                            if !request.standalone {
4097                                owned_in_flight.push(request.task.clone());
4098                                match request.lane {
4099                                    PermitKind::Ordinary => owned_ordinary_count += 1,
4100                                    PermitKind::Urgent => urgent_busy = true,
4101                                    PermitKind::Immediate | PermitKind::None => {}
4102                                }
4103                            }
4104                            map.entry(request.task)
4105                                .and_modify(|existing: &mut (PermitKind, bool)| {
4106                                    if existing.1 && !request.standalone {
4107                                        *existing = (request.lane, request.standalone);
4108                                    }
4109                                })
4110                                .or_insert((request.lane, request.standalone));
4111                        }
4112                        Err(e) => {
4113                            parse_err = Some(format!(
4114                                "invalid task worker payload for {}: {e}",
4115                                entry.job.id
4116                            ));
4117                            break;
4118                        }
4119                    }
4120                }
4121                match parse_err {
4122                    Some(err) => Err(err),
4123                    None => Ok(map),
4124                }
4125            }
4126            Err(e) => Err(format!("{e:#}")),
4127        };
4128        let cooldown_until = read_cooldown(home).map_err(|e| format!("{e:#}"));
4129        let interrupt = read_interrupt_checked(home);
4130        Self {
4131            now,
4132            daemon,
4133            scheduler_running,
4134            active_workers,
4135            owned_in_flight,
4136            owned_ordinary_count,
4137            urgent_busy,
4138            cache_service_active,
4139            cooldown_until,
4140            interrupt,
4141        }
4142    }
4143
4144    fn format_waiting(task: &Task, reason: &str) -> String {
4145        if task.immediate {
4146            format!("Immediate: waiting — {reason}")
4147        } else if task.urgent {
4148            format!("Urgent: waiting — {reason}")
4149        } else {
4150            format!("Waiting — {reason}")
4151        }
4152    }
4153
4154    /// Evaluate admission for `task` using this pre-captured snapshot.
4155    /// Read-only: never mutates queue, run, worker, or question files.
4156    #[must_use]
4157    pub fn evaluate(
4158        &self,
4159        task: &Task,
4160        queue: &Queue,
4161        inv: Option<&crate::blockers::Inventory>,
4162        home: &Path,
4163    ) -> TaskAdmission {
4164        let mode = if task.immediate {
4165            "immediate"
4166        } else if task.urgent {
4167            "urgent"
4168        } else {
4169            "ordinary"
4170        };
4171
4172        if task.status == TaskStatus::Done {
4173            return TaskAdmission {
4174                mode,
4175                reservation_lane: None,
4176                standalone: false,
4177                state: "completed",
4178                label: "Completed".to_owned(),
4179                blocker: None,
4180            };
4181        }
4182
4183        if let Ok(workers) = &self.active_workers
4184            && let Some(&(lane, standalone)) = workers.get(&task.id)
4185        {
4186            let lane_label = lane.label();
4187            let base = if standalone {
4188                format!("Running (standalone, {lane_label} lane)")
4189            } else {
4190                format!("Running ({lane_label} lane)")
4191            };
4192            let resource_blocker = task
4193                .execution_runs()
4194                .last()
4195                .and_then(|run_id| RunState::load_under(run_id, home).ok())
4196                .and_then(|state| state.resource_wait)
4197                .map(|wait| {
4198                    if wait.holder.trim().is_empty() {
4199                        format!("waiting for {}", wait.kind)
4200                    } else {
4201                        format!("waiting for {} ({})", wait.kind, wait.holder)
4202                    }
4203                });
4204            let label = match &resource_blocker {
4205                Some(reason) => format!("{base} — {reason}"),
4206                None => base,
4207            };
4208            return TaskAdmission {
4209                mode,
4210                reservation_lane: Some(lane_label),
4211                standalone,
4212                state: "running",
4213                label,
4214                blocker: resource_blocker,
4215            };
4216        }
4217
4218        if task.status == TaskStatus::Running {
4219            if self.active_workers.is_err() {
4220                let reason = "worker state unreadable".to_owned();
4221                return TaskAdmission {
4222                    mode,
4223                    reservation_lane: None,
4224                    standalone: false,
4225                    state: "unknown",
4226                    label: Self::format_waiting(task, &reason),
4227                    blocker: Some(reason),
4228                };
4229            }
4230            return TaskAdmission {
4231                mode,
4232                reservation_lane: None,
4233                standalone: false,
4234                state: "running",
4235                label: "Running".to_owned(),
4236                blocker: None,
4237            };
4238        }
4239
4240        if task.status == TaskStatus::Blocked {
4241            let waits = inv.map(|i| i.waits_on(task)).unwrap_or_default();
4242            let reason = if !waits.is_empty() {
4243                format!("waiting on dependencies ({})", waits.join(", "))
4244            } else if let Some(block_reason) = &task.block_reason {
4245                format!("blocked ({block_reason})")
4246            } else if !task.blocked_by.is_empty() {
4247                let ids: Vec<_> = task
4248                    .blocked_by
4249                    .iter()
4250                    .map(|id| crate::run::short_of(id))
4251                    .collect();
4252                format!("waiting on dependencies ({})", ids.join(", "))
4253            } else {
4254                "blocked on unresolved dependencies".to_owned()
4255            };
4256            return TaskAdmission {
4257                mode,
4258                reservation_lane: None,
4259                standalone: false,
4260                state: "waiting",
4261                label: Self::format_waiting(task, &reason),
4262                blocker: Some(reason),
4263            };
4264        }
4265
4266        if task.status == TaskStatus::Held {
4267            let reason = match &task.machine_hold_cause {
4268                Some(crate::queue::MachineHoldCause::DiskCapacity { reason, .. }) => {
4269                    format!("disk admission ({reason})")
4270                }
4271                Some(crate::queue::MachineHoldCause::HeadE2e { .. }) => {
4272                    let detail = task
4273                        .hold_reason
4274                        .as_deref()
4275                        .unwrap_or("current head verify.e2e failed");
4276                    format!("head e2e hold ({detail})")
4277                }
4278                None if task.hold_source == Some(crate::queue::HoldSource::Machine) => {
4279                    let detail = task.hold_reason.as_deref().unwrap_or("held by daemon");
4280                    if let Some(rest) = detail.strip_prefix("[resource] ") {
4281                        format!("resource hold ({rest})")
4282                    } else if let Some(rest) = detail.strip_prefix("[config] ") {
4283                        format!("config hold ({rest})")
4284                    } else {
4285                        format!("machine hold ({detail})")
4286                    }
4287                }
4288                None => match task.hold_reason.as_deref() {
4289                    Some(reason) if !reason.trim().is_empty() => format!("held ({reason})"),
4290                    _ => "held (release required)".to_owned(),
4291                },
4292            };
4293            return TaskAdmission {
4294                mode,
4295                reservation_lane: None,
4296                standalone: false,
4297                state: "waiting",
4298                label: Self::format_waiting(task, &reason),
4299                blocker: Some(reason),
4300            };
4301        }
4302
4303        // Runnable (`Queued` | `Failed` | `Parked`): evaluate non-concurrency
4304        // gates first, never claiming dispatchability on unconfirmed state and
4305        // never attributing ordinary/urgent capacity waits to immediate tasks.
4306        if self.active_workers.is_err() {
4307            let reason = "worker state unreadable".to_owned();
4308            return TaskAdmission {
4309                mode,
4310                reservation_lane: None,
4311                standalone: false,
4312                state: "unknown",
4313                label: Self::format_waiting(task, &reason),
4314                blocker: Some(reason),
4315            };
4316        }
4317
4318        if queue.is_claimed(&task.id) {
4319            let reason = "claimed by another process".to_owned();
4320            return TaskAdmission {
4321                mode,
4322                reservation_lane: None,
4323                standalone: false,
4324                state: "waiting",
4325                label: Self::format_waiting(task, &reason),
4326                blocker: Some(reason),
4327            };
4328        }
4329
4330        if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, task) {
4331            let reason = format!("head e2e stop ({})", hold.reason);
4332            return TaskAdmission {
4333                mode,
4334                reservation_lane: None,
4335                standalone: false,
4336                state: "waiting",
4337                label: Self::format_waiting(task, &reason),
4338                blocker: Some(reason),
4339            };
4340        }
4341
4342        let resume = land_resume_state_readonly(task, home, self.now);
4343        if resume == LandResume::StillWaiting {
4344            let reason = "waiting on merge/posting approval".to_owned();
4345            return TaskAdmission {
4346                mode,
4347                reservation_lane: None,
4348                standalone: false,
4349                state: "waiting",
4350                label: Self::format_waiting(task, &reason),
4351                blocker: Some(reason),
4352            };
4353        }
4354        let priority = resume == LandResume::Ready;
4355        let effective_lane = permit_kind(priority, task.immediate, task.urgent);
4356
4357        match &self.interrupt {
4358            Err(_) => {
4359                let reason = "interrupt state unreadable".to_owned();
4360                return TaskAdmission {
4361                    mode,
4362                    reservation_lane: None,
4363                    standalone: false,
4364                    state: "unknown",
4365                    label: Self::format_waiting(task, &reason),
4366                    blocker: Some(reason),
4367                };
4368            }
4369            Ok(interrupt)
4370                if *interrupt != Interrupt::Idle
4371                    && interrupt_gate(interrupt, &self.owned_in_flight, vec![task.clone()])
4372                        .is_empty() =>
4373            {
4374                let reason = "withheld by active interrupt sequence".to_owned();
4375                return TaskAdmission {
4376                    mode,
4377                    reservation_lane: None,
4378                    standalone: false,
4379                    state: "waiting",
4380                    label: Self::format_waiting(task, &reason),
4381                    blocker: Some(reason),
4382                };
4383            }
4384            Ok(_) => {}
4385        }
4386
4387        if effective_lane != PermitKind::None {
4388            match &self.cooldown_until {
4389                Err(_) => {
4390                    let reason = "quota cooldown state unreadable".to_owned();
4391                    return TaskAdmission {
4392                        mode,
4393                        reservation_lane: None,
4394                        standalone: false,
4395                        state: "unknown",
4396                        label: Self::format_waiting(task, &reason),
4397                        blocker: Some(reason),
4398                    };
4399                }
4400                Ok(Some(until)) if self.now < *until => {
4401                    let secs = (until.as_second() - self.now.as_second()).max(1);
4402                    let reason = format!("quota cooldown ({secs}s remaining)");
4403                    return TaskAdmission {
4404                        mode,
4405                        reservation_lane: None,
4406                        standalone: false,
4407                        state: "waiting",
4408                        label: Self::format_waiting(task, &reason),
4409                        blocker: Some(reason),
4410                    };
4411                }
4412                Ok(_) => {}
4413            }
4414        }
4415
4416        if self.cache_service_active {
4417            let reason = "waiting for cache maintenance service".to_owned();
4418            return TaskAdmission {
4419                mode,
4420                reservation_lane: None,
4421                standalone: false,
4422                state: "waiting",
4423                label: Self::format_waiting(task, &reason),
4424                blocker: Some(reason),
4425            };
4426        }
4427
4428        if self.daemon.is_err() {
4429            let reason = "scheduler status unreadable".to_owned();
4430            return TaskAdmission {
4431                mode,
4432                reservation_lane: None,
4433                standalone: false,
4434                state: "unknown",
4435                label: Self::format_waiting(task, &reason),
4436                blocker: Some(reason),
4437            };
4438        }
4439
4440        if self.scheduler_running
4441            && let Ok(Some(reading)) = &self.daemon
4442            && let Some(skip_key) = reading.dispatch_skips.get(&task.id)
4443        {
4444            let stale_capacity_skip = match effective_lane {
4445                PermitKind::None | PermitKind::Immediate => {
4446                    matches!(skip_key.as_str(), "ordinary_capacity" | "urgent_capacity")
4447                }
4448                PermitKind::Urgent => skip_key == "ordinary_capacity",
4449                PermitKind::Ordinary => skip_key == "urgent_capacity",
4450            };
4451            if !stale_capacity_skip {
4452                let reason = skip_reason_label(skip_key);
4453                return TaskAdmission {
4454                    mode,
4455                    reservation_lane: None,
4456                    standalone: false,
4457                    state: "waiting",
4458                    label: Self::format_waiting(task, &reason),
4459                    blocker: Some(reason),
4460                };
4461            }
4462        }
4463
4464        if !self.scheduler_running {
4465            let reason = "scheduler not running".to_owned();
4466            return TaskAdmission {
4467                mode,
4468                reservation_lane: None,
4469                standalone: false,
4470                state: "waiting",
4471                label: Self::format_waiting(task, &reason),
4472                blocker: Some(reason),
4473            };
4474        }
4475
4476        match effective_lane {
4477            PermitKind::Immediate => TaskAdmission {
4478                mode,
4479                reservation_lane: None,
4480                standalone: false,
4481                state: "next_poll",
4482                label: "Immediate: next poll".to_owned(),
4483                blocker: None,
4484            },
4485            PermitKind::None => TaskAdmission {
4486                mode,
4487                reservation_lane: None,
4488                standalone: false,
4489                state: "next_poll",
4490                label: if task.immediate {
4491                    "Immediate: next poll".to_owned()
4492                } else {
4493                    "Decision resume: next poll".to_owned()
4494                },
4495                blocker: None,
4496            },
4497            PermitKind::Urgent => {
4498                if self.urgent_busy {
4499                    let reason = "urgent slot busy".to_owned();
4500                    TaskAdmission {
4501                        mode,
4502                        reservation_lane: None,
4503                        standalone: false,
4504                        state: "waiting",
4505                        label: Self::format_waiting(task, &reason),
4506                        blocker: Some(reason),
4507                    }
4508                } else {
4509                    TaskAdmission {
4510                        mode,
4511                        reservation_lane: None,
4512                        standalone: false,
4513                        state: "next_poll",
4514                        label: "Urgent: next poll".to_owned(),
4515                        blocker: None,
4516                    }
4517                }
4518            }
4519            PermitKind::Ordinary => {
4520                if self.owned_ordinary_count == 0 {
4521                    TaskAdmission {
4522                        mode,
4523                        reservation_lane: None,
4524                        standalone: false,
4525                        state: "next_poll",
4526                        label: "Ordinary: next poll".to_owned(),
4527                        blocker: None,
4528                    }
4529                } else {
4530                    TaskAdmission {
4531                        mode,
4532                        reservation_lane: None,
4533                        standalone: false,
4534                        state: "waiting",
4535                        label: "Queued (ordinary lane)".to_owned(),
4536                        blocker: None,
4537                    }
4538                }
4539            }
4540        }
4541    }
4542}
4543
4544struct DispatchClaim {
4545    task: Task,
4546    claim: crate::queue::Claim,
4547    lane: PermitKind,
4548    permit: Option<tokio::sync::OwnedSemaphorePermit>,
4549}
4550
4551/// Claim and re-read before choosing a lane: a queue listing may predate an
4552/// immediate or urgent toggle. All unsuccessful paths release the claim
4553/// without an attempt.
4554fn claim_dispatch(
4555    queue: &Queue,
4556    candidate: &Task,
4557    cooling_down: bool,
4558    ordinary: &Arc<tokio::sync::Semaphore>,
4559    urgent: &Arc<tokio::sync::Semaphore>,
4560) -> std::result::Result<DispatchClaim, SkipReason> {
4561    let claim = queue
4562        .claim(&candidate.id)
4563        .map_err(|_| SkipReason::ClaimUnavailable)?;
4564    let task = match queue.get(&candidate.id) {
4565        Ok(t) if t.status.runnable() => t,
4566        Ok(_) => return Err(SkipReason::NoLongerRunnable),
4567        Err(e) => {
4568            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
4569            return Err(SkipReason::RereadFailed);
4570        }
4571    };
4572    if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, &task) {
4573        let mut held = task;
4574        hold.apply(&mut held);
4575        record(queue, &mut held);
4576        return Err(SkipReason::NoLongerRunnable);
4577    }
4578    let resume = land_resume_state(&task);
4579    if resume == LandResume::StillWaiting {
4580        return Err(SkipReason::WaitingOnLanding);
4581    }
4582    let priority = resume == LandResume::Ready;
4583    if !priority && cooling_down {
4584        return Err(SkipReason::CoolingDown);
4585    }
4586    // Never borrow an ordinary slot when the single urgent slot is busy.
4587    // Immediate tasks consume neither ordinary nor urgent permits.
4588    // Keep scanning other candidates when either pool has no free slot.
4589    let lane = permit_kind(priority, task.immediate, task.urgent);
4590    let permit = match lane {
4591        PermitKind::None | PermitKind::Immediate => None,
4592        PermitKind::Urgent => Some(
4593            Arc::clone(urgent)
4594                .try_acquire_owned()
4595                .map_err(|_| SkipReason::UrgentCapacity)?,
4596        ),
4597        PermitKind::Ordinary => Some(
4598            Arc::clone(ordinary)
4599                .try_acquire_owned()
4600                .map_err(|_| SkipReason::OrdinaryCapacity)?,
4601        ),
4602    };
4603    // Persist the dispatch order under the claim, before config discovery or
4604    // coordination waits can reorder concurrent starts.
4605    let stamp = Timestamp::now();
4606    let mut task = task;
4607    task.dispatched_at = Some(stamp);
4608    if let Err(e) = queue.modify(&task.id, |t| {
4609        t.dispatched_at = Some(stamp);
4610        true
4611    }) {
4612        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
4613    }
4614    Ok(DispatchClaim {
4615        task,
4616        claim,
4617        lane,
4618        permit,
4619    })
4620}
4621
4622/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
4623/// teardown and cannot skip the teardown on an early return.
4624///
4625/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
4626/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
4627/// land approval that has since been answered is dispatched outside that
4628/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
4629/// the whole point of parking there is that it must not queue behind
4630/// whatever else the loop happens to be running, even at the default of one.
4631/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
4632/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
4633/// these exemptions is still subject to the interrupt gate below, urgent
4634/// included: a land-resume or urgent candidate is exactly as much "something
4635/// else running" as an ordinary one from the interrupt sequence's point of
4636/// view, and letting either slip through while a run is being parked, or
4637/// while the interrupt task itself has the floor, is precisely the second
4638/// run 75dd's own "at most one run, ever, at once" guarantee must never
4639/// allow - see [`Interrupt`]'s own doc.
4640#[derive(Serialize, Deserialize)]
4641struct ServiceWorker {
4642    opts: Opts,
4643    queue: PathBuf,
4644    worktrees_root: PathBuf,
4645    operation: String,
4646}
4647
4648fn load_conductor(home: &Path) -> Result<Conductor> {
4649    match std::fs::read(home.join("conductor-state.json")) {
4650        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
4651        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
4652        Err(error) => Err(error.into()),
4653    }
4654}
4655
4656fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
4657    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
4658        .into_iter()
4659        .map(|c| c.task)
4660        .collect();
4661    let stalled = stalled_tasks(queue, home, Timestamp::now());
4662    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
4663    let finished = finished_tasks(queue)
4664        .into_iter()
4665        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
4666        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
4667        .collect();
4668    let queued = queued_tasks(queue)
4669        .into_iter()
4670        .filter(|t| !live.contains(&t.id))
4671        .collect();
4672    (queued, stalled, finished)
4673}
4674
4675// Separate latest dispatch and worker receipts expose version handoff and skips
4676// without erasing the last completed scan or treating observations as authority.
4677fn retention_service_receipt(
4678    home: &Path,
4679    operation: &str,
4680    phase: &str,
4681    outcome: &str,
4682    detail: &str,
4683    cfg: Option<&Config>,
4684) {
4685    retention_service_receipt_with(
4686        home,
4687        operation,
4688        phase,
4689        outcome,
4690        detail,
4691        cfg,
4692        serde_json::Value::Null,
4693    );
4694}
4695
4696/// [`retention_service_receipt`] plus `extra`: an object whose fields (the
4697/// fold turn's per-outcome counts and cursor, a retention pass's failures) are
4698/// added to the same receipt file rather than to a store of their own.
4699fn retention_service_receipt_with(
4700    home: &Path,
4701    operation: &str,
4702    phase: &str,
4703    outcome: &str,
4704    detail: &str,
4705    cfg: Option<&Config>,
4706    extra: serde_json::Value,
4707) {
4708    if !matches!(operation, "housekeeping" | "disk-pressure" | "fold") {
4709        return;
4710    }
4711    let mut receipt = serde_json::json!({"checked_at": Timestamp::now(),
4712        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
4713        "operation": operation, "outcome": outcome, "detail": detail,
4714        "auto_fold": cfg.map(|c| c.disk.auto_fold),
4715        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
4716    if let (Some(receipt), serde_json::Value::Object(extra)) = (receipt.as_object_mut(), extra) {
4717        receipt.extend(extra);
4718    }
4719    if let Err(error) = crate::fold_evidence::atomic_write(
4720        &home.join(format!("source-eviction-{operation}-{phase}.json")),
4721        &serde_json::to_vec(&receipt).expect("service receipt"),
4722    ) {
4723        tracing::warn!("retention service receipt failed: {error:#}");
4724    }
4725}
4726
4727/// What a retention pass reported, for the service receipt: the same report
4728/// `retention.json` holds, reduced to what says whether the pass ran. On a
4729/// platform without process containment this carries the refusal.
4730fn retention_summary(report: &crate::retention::Report) -> serde_json::Value {
4731    let clip = |text: &String| text.chars().take(300).collect::<String>();
4732    serde_json::json!({"retention": {
4733        "checked_at": report.checked_at,
4734        "freed_bytes": report.freed_bytes,
4735        "retired": report.retired,
4736        "retained": report.retained.len(),
4737        "failure_count": report.failures.len(),
4738        "failures": report.failures.iter().take(8).map(clip).collect::<Vec<_>>(),
4739    }})
4740}
4741
4742/// Why the finished-run folding turn exists, and what keeps it safe.
4743///
4744/// `housekeeping` (which folds finished runs through `clean::fold_due`) has
4745/// only ever been admitted on a fully idle machine: it was written as "the
4746/// janitor, called when a task just ended" (e2c10827, "the disk is quiet ...
4747/// folding worktrees and pruning a cache mid-build would race the very compile
4748/// the prune exists to keep"), and the idle gate survived when the loop was
4749/// split into services. Nothing in that reasoning is about folding: it is
4750/// about the shared cache prune, `fold_orphaned_worktrees` (a run that has no
4751/// `run.json` yet is indistinguishable from an orphan) and `worktree_prune`,
4752/// which stay idle-only. Folding a *finished* run is already done beside live
4753/// runs of the same repository by `Runner::fold_losers`, `magi fold` and the
4754/// phone's fold route, because `graph::fold_run_when` takes the run's owner lock
4755/// and execution lease, a per-worktree output lease and the repository
4756/// coordination lease itself, acts on the run record it reloads once it holds
4757/// them (a handover in between cannot be undone), and `clean::eligibility`
4758/// refuses anything a live claim holds. So a queue that is never empty must not
4759/// mean runs are never folded (issue 1275): this turn is admitted exactly where
4760/// housekeeping is not, in bounded passes (`clean::BUSY_FOLD_BOUNDS`).
4761const FOLD_TURN_INTERVAL_SECS: u64 = 120;
4762
4763/// Idle housekeeping: no worker busy and nothing runnable.
4764fn housekeeping_eligible(busy: bool, runnable: bool) -> bool {
4765    !busy && !runnable
4766}
4767
4768/// Exactly the machines [`housekeeping_eligible`] never reaches (see
4769/// [`FOLD_TURN_INTERVAL_SECS`] for why folding may run beside live work),
4770/// and only with a startup configuration that has `auto_fold` on (like the
4771/// cache and fetch services, an unreadable one means no service).
4772fn fold_turn_eligible(busy: bool, runnable: bool, cfg: Option<&Config>) -> bool {
4773    !housekeeping_eligible(busy, runnable) && cfg.is_some_and(|cfg| cfg.disk.auto_fold)
4774}
4775
4776async fn start_service(
4777    home: &Path,
4778    opts: &Opts,
4779    queue: &Queue,
4780    worktrees_root: &Path,
4781    operation: &str,
4782    cfg: Option<&Config>,
4783    busy: bool,
4784) -> Result<()> {
4785    // Fetch policy is live configuration, unlike question recovery capacity.
4786    // Reload before both cadence and eligibility, including disabled -> enabled.
4787    let fetch_cfg = if operation == "fetch" {
4788        match prepare(&opts.repo, opts) {
4789            Ok(cfg) => Some(cfg),
4790            Err(error) => {
4791                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
4792                return Ok(());
4793            }
4794        }
4795    } else {
4796        None
4797    };
4798    let cfg = fetch_cfg.as_ref().or(cfg);
4799    let ticks = home.join("service-ticks");
4800    std::fs::create_dir_all(&ticks)?;
4801    let receipt = ticks.join(format!("daemon-{operation}"));
4802    let last = std::fs::read(&receipt)
4803        .ok()
4804        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
4805    let interval = match operation {
4806        "disk-pressure" => 30,
4807        "fold" => FOLD_TURN_INTERVAL_SECS,
4808        "chat-goals" => 60,
4809        "cache" => CACHE_CHECK_INTERVAL_SECS,
4810        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
4811        _ => opts.poll.as_secs().max(1),
4812    };
4813    let now = Timestamp::now();
4814    if !cache_check_due(last, now, interval) {
4815        retention_service_receipt(
4816            home,
4817            operation,
4818            "dispatch",
4819            "skipped",
4820            "cadence not due",
4821            cfg,
4822        );
4823        return Ok(());
4824    }
4825    let key = format!("service:daemon-{operation}");
4826    let active = crate::worker::active(home)?;
4827    if active.iter().any(|job| job.key == key) {
4828        retention_service_receipt(
4829            home,
4830            operation,
4831            "dispatch",
4832            "skipped",
4833            "service worker already active",
4834            cfg,
4835        );
4836        return Ok(());
4837    }
4838    // Both fold the same runs; the run's owner lock already makes a collision
4839    // harmless, but one of them at a time keeps the receipts unambiguous.
4840    let sibling = match operation {
4841        "housekeeping" => Some("service:daemon-fold"),
4842        "fold" => Some("service:daemon-housekeeping"),
4843        _ => None,
4844    };
4845    if sibling.is_some_and(|sibling| active.iter().any(|job| job.key == sibling)) {
4846        retention_service_receipt(
4847            home,
4848            operation,
4849            "dispatch",
4850            "skipped",
4851            "another finished-run folding service is active",
4852            cfg,
4853        );
4854        return Ok(());
4855    }
4856    let eligible = match operation {
4857        "conductor" => {
4858            let (queued, stalled, finished) = conductor_work(queue, home);
4859            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4860                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
4861        }
4862        "maintenance" => {
4863            queue.list().iter().any(|task| {
4864                crate::triage::disk_wait_eligible(task)
4865                    && task
4866                        .disk_checked_at
4867                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
4868            }) || Questions::at(home.join("questions"))
4869                .list_for_effects()
4870                .iter()
4871                .any(|q| {
4872                    q.chosen_action().is_some_and(|action| action.maintenance())
4873                        && !home
4874                            .join("choice-actions")
4875                            .join(format!("{}.json", q.id))
4876                            .exists()
4877                })
4878        }
4879        "housekeeping" => housekeeping_eligible(busy, !runnable(queue).is_empty()),
4880        "fold" => fold_turn_eligible(busy, !runnable(queue).is_empty(), cfg),
4881        "cache" => {
4882            !busy
4883                && !runnable(queue).is_empty()
4884                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
4885        }
4886        "disk-pressure" => busy,
4887        "fetch" => {
4888            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
4889        }
4890        "chat-goals" => crate::talk::Talks::at(home.join("talks"))
4891            .list()
4892            .iter()
4893            .any(|talk| {
4894                talk.status.open()
4895                    && talk.pending.is_empty()
4896                    && talk.pending_attachments.is_empty()
4897                    && talk.goals.iter().any(|goal| goal.active())
4898            }),
4899        _ => false,
4900    };
4901    if !eligible {
4902        retention_service_receipt(
4903            home,
4904            operation,
4905            "dispatch",
4906            "skipped",
4907            match operation {
4908                "housekeeping" => "active work or runnable task queue",
4909                "fold" if cfg.is_none() => "startup configuration unavailable",
4910                "fold" if cfg.is_some_and(|cfg| !cfg.disk.auto_fold) => "auto_fold disabled",
4911                "fold" => "idle machine; housekeeping owns finished-run folding",
4912                _ => "no active work; idle housekeeping owns scan",
4913            },
4914            cfg,
4915        );
4916        return Ok(());
4917    }
4918    retention_service_receipt(
4919        home,
4920        operation,
4921        "dispatch",
4922        "launching",
4923        "eligible and cadence due",
4924        cfg,
4925    );
4926    let request = ServiceWorker {
4927        opts: opts.absolute()?,
4928        queue: std::path::absolute(queue.root())?,
4929        worktrees_root: std::path::absolute(worktrees_root)?,
4930        operation: operation.to_owned(),
4931    };
4932    if let Err(error) = launch_service(home, &key, request).await {
4933        retention_service_receipt(
4934            home,
4935            operation,
4936            "dispatch",
4937            "error",
4938            &format!("worker launch: {error:#}"),
4939            cfg,
4940        );
4941        tracing::warn!(operation, "could not launch daemon service: {error:#}");
4942    }
4943    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
4944    Ok(())
4945}
4946
4947/// Hand `request` to a detached `daemon-service` worker reservation.
4948///
4949/// Unit tests have no `magi` executable to pin and exec as a worker, so they
4950/// may run the very same [`run_service_worker`] inline instead (and nothing
4951/// else differs: admission, cadence and receipts above are the production path).
4952async fn launch_service(home: &Path, key: &str, request: ServiceWorker) -> Result<()> {
4953    #[cfg(test)]
4954    if INLINE_SERVICES.with(std::cell::Cell::get) {
4955        return run_service_worker(home, serde_json::to_value(request)?).await;
4956    }
4957    crate::worker::spawn(home, "daemon-service", key, serde_json::to_value(request)?).await?;
4958    Ok(())
4959}
4960
4961#[cfg(test)]
4962thread_local! {
4963    static INLINE_SERVICES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
4964}
4965
4966/// One bounded pass of finished-run folding (`clean::fold_turn`) with its
4967/// per-outcome counts and cursor in the service receipt. It reserves no agent
4968/// seat and takes only the locks `graph::fold_run` takes for one run at a time.
4969async fn fold_service_turn(home: &Path, opts: &Opts) {
4970    let worker = |outcome: &str, detail: &str, cfg: Option<&Config>, extra| {
4971        retention_service_receipt_with(home, "fold", "worker", outcome, detail, cfg, extra);
4972    };
4973    let cfg = match prepare(&opts.repo, opts) {
4974        Ok(cfg) => cfg,
4975        Err(error) => {
4976            worker(
4977                "error",
4978                &format!("configuration: {error:#}"),
4979                None,
4980                serde_json::Value::Null,
4981            );
4982            return;
4983        }
4984    };
4985    if !cfg.disk.auto_fold {
4986        worker(
4987            "skipped",
4988            "auto_fold disabled",
4989            Some(&cfg),
4990            serde_json::Value::Null,
4991        );
4992        return;
4993    }
4994    worker(
4995        "running",
4996        "finished-run fold turn",
4997        Some(&cfg),
4998        serde_json::Value::Null,
4999    );
5000    let turn = clean::fold_turn(
5001        &home.join("runs"),
5002        home,
5003        &cfg.disk,
5004        Timestamp::now(),
5005        clean::BUSY_FOLD_BOUNDS,
5006    )
5007    .await;
5008    if turn.folded > 0 || turn.failed > 0 || turn.unreadable > 0 {
5009        tracing::info!(
5010            folded = turn.folded,
5011            failed = turn.failed,
5012            unreadable = turn.unreadable,
5013            "housekeep: finished-run fold turn"
5014        );
5015    }
5016    worker(
5017        "completed",
5018        "finished-run fold turn",
5019        Some(&cfg),
5020        serde_json::json!({ "fold": turn }),
5021    );
5022}
5023
5024/// Finite maintenance jobs survive scheduler replacement without duplicating
5025/// agent calls or cancelling an operation between its effect and receipt.
5026pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
5027    let request: ServiceWorker = serde_json::from_value(payload)?;
5028    let opts = &request.opts;
5029    let queue = Queue::at(request.queue);
5030    let questions = Questions::at(home.join("questions"));
5031    match request.operation.as_str() {
5032        "chat-goals" => {
5033            let talks = crate::talk::Talks::at(home.join("talks"));
5034            crate::chat_goal_runtime::sweep(&talks, false).await;
5035        }
5036        "maintenance" => {
5037            apply_maintenance_choices(&queue, &questions, home).await;
5038            triage::monitor_disk_waits(
5039                &queue,
5040                &questions,
5041                opts.config.as_deref(),
5042                Timestamp::now(),
5043            );
5044        }
5045        "conductor" => {
5046            let path = home.join("conductor-state.json");
5047            let mut conductor = load_conductor(home)?;
5048            let (queued, stalled, finished) = conductor_work(&queue, home);
5049            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
5050                && conductor.worth_a_look(&queue, &stalled, &finished)
5051            {
5052                let cfg = prepare(&opts.repo, opts)?;
5053                conductor
5054                    .maybe_run(
5055                        &cfg,
5056                        &opts.repo,
5057                        &queue,
5058                        &questions,
5059                        home,
5060                        &queued,
5061                        &stalled,
5062                        &finished,
5063                        opts.max_attempts,
5064                    )
5065                    .await;
5066                let temporary = path.with_extension("json.tmp");
5067                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
5068                std::fs::rename(temporary, path)?;
5069            }
5070        }
5071        "fetch" => {
5072            let cfg = prepare(&opts.repo, opts)?;
5073            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
5074                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
5075                tracing::debug!("fetch origins: {outcome:?}");
5076            }
5077        }
5078        "cache" => {
5079            if task_jobs(home)?.is_empty() {
5080                let mut checked = None;
5081                maybe_prune_cache_between_runs(
5082                    &opts.repo,
5083                    opts,
5084                    home,
5085                    &Stop::new(),
5086                    &mut checked,
5087                    Timestamp::now(),
5088                )
5089                .await;
5090            }
5091        }
5092        "disk-pressure" => {
5093            if let Ok(cfg) = prepare(&opts.repo, opts) {
5094                retention_service_receipt(
5095                    home,
5096                    "disk-pressure",
5097                    "worker",
5098                    "running",
5099                    "retention sweep",
5100                    Some(&cfg),
5101                );
5102                let report = crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
5103                retention_service_receipt_with(
5104                    home,
5105                    "disk-pressure",
5106                    "worker",
5107                    "retention swept",
5108                    "retention sweep finished; cache cleanup follows",
5109                    Some(&cfg),
5110                    retention_summary(&report),
5111                );
5112                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
5113                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
5114                }
5115                if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
5116                    tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
5117                }
5118                for current in current_work(home, Timestamp::now()) {
5119                    if let Ok(state) = RunState::load_under(&current.run, home)
5120                        && let Some(reason) = disk_gate(&state.repo, &state.config)
5121                    {
5122                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
5123                            job.key.strip_prefix("task:") == Some(current.task.as_str())
5124                        }) {
5125                            request_task_park(
5126                                home,
5127                                &job,
5128                                crate::run::ParkCause::Interrupt {
5129                                    reason: reason.clone(),
5130                                },
5131                            )?;
5132                        }
5133                        notices::raise_in(
5134                            home,
5135                            Notice::warn(
5136                                "disk:pressure",
5137                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
5138                            ),
5139                        );
5140                    }
5141                }
5142            } else {
5143                retention_service_receipt(
5144                    home,
5145                    "disk-pressure",
5146                    "worker",
5147                    "error",
5148                    "configuration could not be loaded",
5149                    None,
5150                );
5151            }
5152        }
5153        "fold" => fold_service_turn(home, opts).await,
5154        "housekeeping" => {
5155            if task_jobs(home)?.is_empty() {
5156                match prepare(&opts.repo, opts) {
5157                    Ok(cfg) => {
5158                        retention_service_receipt(
5159                            home,
5160                            "housekeeping",
5161                            "worker",
5162                            "running",
5163                            "retention sweep",
5164                            Some(&cfg),
5165                        );
5166                        let report =
5167                            crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
5168                        retention_service_receipt_with(
5169                            home,
5170                            "housekeeping",
5171                            "worker",
5172                            "retention swept",
5173                            "retention sweep finished; janitor follows",
5174                            Some(&cfg),
5175                            retention_summary(&report),
5176                        );
5177                    }
5178                    Err(error) => retention_service_receipt(
5179                        home,
5180                        "housekeeping",
5181                        "worker",
5182                        "error",
5183                        &format!("configuration: {error:#}"),
5184                        None,
5185                    ),
5186                }
5187                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
5188                resweep_superseded_attempts(&queue, home);
5189                triage_held(&queue, home, opts).await;
5190            } else {
5191                retention_service_receipt(
5192                    home,
5193                    "housekeeping",
5194                    "worker",
5195                    "skipped",
5196                    "task worker became active",
5197                    None,
5198                );
5199            }
5200        }
5201        operation => bail!("unknown daemon service {operation}"),
5202    }
5203    Ok(())
5204}
5205
5206/// Only a different request under the same key is a dispatch handoff race.
5207/// Our own unacknowledged reservation is a startup failure, not competing work:
5208/// stop dispatch without fencing it, so an already detached child may still run.
5209fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
5210    let key = format!("task:{}", request.task);
5211    let payload = serde_json::to_value(request)?;
5212    if crate::worker::active(home)?
5213        .iter()
5214        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
5215    {
5216        tracing::warn!(
5217            "task {} acquired a competing worker reservation: {error:#}",
5218            crate::run::short_of(&request.task)
5219        );
5220        return Ok(());
5221    }
5222    tracing::error!("task worker startup stopped dispatch: {error:#}");
5223    notices::raise_in(
5224        home,
5225        Notice::error(
5226            "loop:worker-startup",
5227            // Startup diagnostics may contain private child-process details;
5228            // keep them in the local error/log rather than the chat or notifier.
5229            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),
5230        ).link(Link::Task { id: request.task.clone() }),
5231    );
5232    Err(error).with_context(|| {
5233        format!(
5234            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
5235            crate::run::short_of(&request.task)
5236        )
5237    })
5238}
5239
5240async fn poll(
5241    opts: &Opts,
5242    queue: &Queue,
5243    status: &Arc<Mutex<Status>>,
5244    home: &Path,
5245    worktrees_root: &Path,
5246    stop: &Stop,
5247    limits: DispatchLimits,
5248) -> Result<()> {
5249    let mut attempted = Vec::new();
5250    let mut settling_once_services = false;
5251    let interrupt_path = home.join("scheduler-interrupt.json");
5252    let mut interrupt = match std::fs::read(&interrupt_path) {
5253        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
5254        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
5255        Err(error) => return Err(error.into()),
5256    };
5257    let mut previous = std::collections::BTreeSet::<String>::new();
5258    let mut previous_skips = DispatchSkips::new();
5259    while !stop.stopped() {
5260        let jobs: Vec<_> = crate::worker::active(home)?
5261            .into_iter()
5262            .filter(|job| job.kind == "task")
5263            .collect();
5264        let requests: Vec<_> = jobs
5265            .iter()
5266            .map(|job| {
5267                serde_json::from_value::<TaskWorker>(job.payload.clone())
5268                    .with_context(|| format!("read live task worker {}", job.id))
5269            })
5270            .collect::<Result<_>>()?;
5271        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
5272        let owned: std::collections::BTreeSet<_> = requests
5273            .iter()
5274            .filter(|r| !r.standalone)
5275            .map(|r| r.task.clone())
5276            .collect();
5277        let current: Vec<_> = requests
5278            .iter()
5279            .zip(&jobs)
5280            .filter(|(request, _)| !request.standalone)
5281            .map(|(request, job)| Current {
5282                worker: Some(job.id.clone()),
5283                task: request.task.clone(),
5284                run: queue
5285                    .get(&request.task)
5286                    .ok()
5287                    .and_then(|task| task.execution_runs().last().cloned())
5288                    .unwrap_or_default(),
5289            })
5290            .collect();
5291        {
5292            let mut snapshot = lock(status);
5293            snapshot.polls += 1;
5294            snapshot.completed += previous.difference(&owned).count();
5295            snapshot.current = current;
5296            snapshot.idle = owned.is_empty();
5297            snapshot.dispatch_wait = None;
5298        }
5299        previous = owned.clone();
5300        stop.busy.store(owned.len(), Ordering::SeqCst);
5301
5302        // Slots are reconstructed from durable reservations and OS-held worker
5303        // leases, not this scheduler's lifetime or mutable task urgency.
5304        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
5305        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
5306        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
5307        let mut permits = Vec::new();
5308        sweep_stale_claims(queue, STALE_CLAIM);
5309        reclaim_orphaned_running(queue, opts.max_attempts, &live);
5310        reclaim_abandoned_runs(home, Timestamp::now());
5311        let questions = Questions::at(home.join("questions"));
5312
5313        // Deterministic: no model, run before the conductor sees anything so
5314        // its input reflects the queue's current, already-resolved state.
5315        crate::task_chat::sweep(
5316            queue,
5317            &crate::talk::Talks::at(home.join("talks")),
5318            &questions,
5319            home,
5320        );
5321        if let Err(error) = crate::task_inquiry::Outbox::at(home)
5322            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
5323        {
5324            tracing::warn!("task inquiry delivery remains pending: {error:#}");
5325        }
5326        repair_choice_offers(&questions);
5327        resolve_blockers(queue, &questions);
5328        apply_task_choice_actions(queue, &questions, home);
5329        triage::apply_answers(queue, &questions);
5330        reconcile_task_questions(queue, &questions);
5331        let talks = crate::talk::Talks::at(home.join("talks"));
5332        crate::chat_notify::sweep(queue, &talks, home);
5333        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
5334        crate::chat_watch::sweep(home, &talks);
5335        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
5336            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
5337        }
5338        let mut turns = tokio::task::JoinSet::new();
5339        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
5340        // start_turns dispatches detached turns; no paid work lives in this set.
5341        while turns.join_next().await.is_some() {}
5342
5343        crate::consult::start_services(
5344            home,
5345            &opts.repo,
5346            limits.recovery_cfg.as_ref(),
5347            opts.config.as_deref(),
5348        )
5349        .await?;
5350        for operation in [
5351            "conductor",
5352            "maintenance",
5353            "housekeeping",
5354            "disk-pressure",
5355            "fold",
5356            "cache",
5357            "fetch",
5358            "chat-goals",
5359        ] {
5360            // Once an idle --once drain starts settling services, subsequent
5361            // scans only consume their effects. An expired cadence receipt
5362            // must not start another service and keep the drain alive.
5363            if settling_once_services {
5364                break;
5365            }
5366            if operation == "chat-goals" && stop.parking() {
5367                continue;
5368            }
5369            start_service(
5370                home,
5371                opts,
5372                queue,
5373                worktrees_root,
5374                operation,
5375                limits.recovery_cfg.as_ref(),
5376                !live.is_empty(),
5377            )
5378            .await?;
5379        }
5380        let latest = crate::worker::active(home)?;
5381        if latest.iter().any(|job| job.key == "service:daemon-cache")
5382            || latest
5383                .iter()
5384                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
5385        {
5386            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
5387            continue;
5388        }
5389        let candidates: Vec<Task> = runnable(queue)
5390            .into_iter()
5391            .filter(|task| !live.contains(&task.id))
5392            .filter(|task| !opts.once || !attempted.contains(&task.id))
5393            .collect();
5394        let in_flight: Vec<_> = owned.iter().cloned().collect();
5395        let prior_interrupt = std::mem::discriminant(&interrupt);
5396        interrupt = advance_interrupt_tick(
5397            limits.pause_for_interrupts,
5398            interrupt,
5399            &in_flight,
5400            &candidates,
5401        );
5402        // Same-variant transitions preserve their identities. Only an actual
5403        // transition needs a durable write, atomically before sending controls.
5404        if prior_interrupt != std::mem::discriminant(&interrupt) {
5405            let temporary = interrupt_path.with_extension("json.tmp");
5406            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
5407            std::fs::rename(temporary, &interrupt_path)?;
5408        }
5409        if let Interrupt::Parking {
5410            parked,
5411            interrupt_task,
5412        } = &interrupt
5413        {
5414            for job in jobs.iter().filter(|job| {
5415                parked
5416                    .iter()
5417                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
5418            }) {
5419                if crate::worker::control(home, &job.key)?.is_none() {
5420                    request_task_park(
5421                        home,
5422                        job,
5423                        crate::run::ParkCause::Interrupt {
5424                            reason: format!(
5425                                "task {} asked to run first",
5426                                crate::run::short_of(interrupt_task)
5427                            ),
5428                        },
5429                    )?;
5430                }
5431            }
5432        }
5433        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
5434        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
5435        let mut skips = interrupt_skips(&candidate_ids, &candidates);
5436        // Stable-partition immediate candidates ahead of non-immediate ones
5437        // for this poll scan only; shared `dispatch_order` stays unchanged so
5438        // upgrade-resume and ordinary priority ordering are preserved.
5439        let (mut immediate_candidates, other_candidates): (Vec<Task>, Vec<Task>) =
5440            candidates.into_iter().partition(|task| task.immediate);
5441        immediate_candidates.extend(other_candidates);
5442        let candidates = immediate_candidates;
5443        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
5444        let mut known_jobs: std::collections::BTreeSet<String> =
5445            jobs.iter().map(|job| job.id.clone()).collect();
5446        let mut started = false;
5447        let mut resync = false;
5448        for candidate in candidates {
5449            if stop.stopped() {
5450                break;
5451            }
5452            let DispatchClaim {
5453                task,
5454                claim,
5455                lane,
5456                permit,
5457            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
5458                Ok(claim) => claim,
5459                Err(reason) => {
5460                    skips.insert((candidate.id, reason));
5461                    continue;
5462                }
5463            };
5464            if crate::worker::active(home)?
5465                .iter()
5466                .any(|job| job.kind == "task" && !known_jobs.contains(&job.id))
5467            {
5468                drop(claim);
5469                resync = true;
5470                break;
5471            }
5472            let request = TaskWorker {
5473                opts: opts.absolute()?,
5474                queue: std::path::absolute(queue.root())?,
5475                task: task.id.clone(),
5476                lane,
5477                standalone: false,
5478            };
5479            // Keep the claim until spawn acknowledges the worker's durable
5480            // reservation. The worker then claims and re-reads before attempt.
5481            let job = match crate::worker::spawn(
5482                home,
5483                "task",
5484                &format!("task:{}", task.id),
5485                serde_json::to_value(&request)?,
5486            )
5487            .await
5488            {
5489                Ok(job) => job,
5490                Err(error) => {
5491                    task_worker_spawn_error(home, &request, error)?;
5492                    drop(claim);
5493                    resync = true;
5494                    break;
5495                }
5496            };
5497            known_jobs.insert(job.id);
5498            drop(claim);
5499            permits.extend(permit);
5500            attempted.push(task.id);
5501            started = true;
5502            // Interrupt transitions depend on the exact in-flight set (in
5503            // particular the transition from zero to one worker). Re-scan
5504            // before admitting another task, as for ordinary dispatch.
5505            if limits.pause_for_interrupts || lane != PermitKind::Immediate {
5506                break;
5507            }
5508        }
5509        if !resync && !stop.stopped() {
5510            let per_task_skips: std::collections::BTreeMap<String, String> = skips
5511                .iter()
5512                .map(|(id, reason)| (id.clone(), reason.key().to_owned()))
5513                .collect();
5514            {
5515                let mut snapshot = lock(status);
5516                snapshot.dispatch_skips = per_task_skips;
5517                if !started {
5518                    snapshot.dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
5519                }
5520            }
5521            if changed_dispatch_skips(&mut previous_skips, skips) {
5522                if previous_skips.is_empty() {
5523                    tracing::info!("dispatch skips cleared");
5524                }
5525                for (task, reason) in &previous_skips {
5526                    tracing::info!(
5527                        task,
5528                        reason = reason.key(),
5529                        "task {} skipped: {}",
5530                        crate::run::short_of(task),
5531                        reason.describe()
5532                    );
5533                }
5534            }
5535        }
5536        if started || resync {
5537            continue;
5538        }
5539        if owned.is_empty() && opts.once {
5540            settling_once_services = true;
5541            // These finite services can own queue claims or publish answers.
5542            // A skipped claim is not an idle queue until they have finished;
5543            // scan again afterwards so their changes are actually scheduled.
5544            if crate::worker::active(home)?.iter().any(|job| {
5545                job.kind == "daemon-service"
5546                    && matches!(
5547                        job.key.as_str(),
5548                        "service:daemon-housekeeping"
5549                            | "service:daemon-conductor"
5550                            | "service:daemon-maintenance"
5551                    )
5552            }) {
5553                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
5554                continue;
5555            }
5556            break;
5557        }
5558        stop.idle(if live.is_empty() {
5559            opts.poll
5560        } else {
5561            RECHECK_WHILE_BUSY.min(opts.poll)
5562        })
5563        .await;
5564    }
5565    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
5566    // every queue claim and Runner driver lease through outcome settlement.
5567    stop.busy.store(0, Ordering::SeqCst);
5568    {
5569        let mut snapshot = lock(status);
5570        snapshot.dispatch_wait = None;
5571        snapshot.dispatch_skips.clear();
5572    }
5573    Ok(())
5574}
5575
5576/// A maintenance pass may briefly own the same record while a worker starts.
5577/// Wait without blocking the executor or charging an agent attempt, then read
5578/// ownership again under the acquired lock. Other I/O failures still fail closed.
5579async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
5580    let busy = |error: &anyhow::Error| {
5581        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
5582            error.kind() == std::io::ErrorKind::WouldBlock
5583                || cfg!(windows) && error.raw_os_error() == Some(33)
5584        })
5585    };
5586    match crate::pr_head::owner_lock(home, id) {
5587        Ok(lock) => return Ok(lock),
5588        Err(error) if busy(&error) => {}
5589        Err(error) => return Err(error),
5590    }
5591    let wait = RunState::load_under(id, home)?
5592        .config
5593        .graph
5594        .timeout_resource_wait;
5595    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
5596}
5597
5598/// Historical successors do not revoke a still-resumable public owner. Scan
5599/// under the same lock as publication/driver claims, and fail closed on unknown
5600/// history before spending another attempt.
5601async fn public_resume_owner(
5602    home: &Path,
5603    runs: &[String],
5604    repo: &Path,
5605) -> Result<Option<RunState>> {
5606    let mut owner = None;
5607    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
5608        let _lock = resume_owner_lock(home, id).await?;
5609        let state = RunState::load_under(id, home)?;
5610        if state.released()
5611            || state.retired_to.is_some()
5612            || state.pr_taken_over_by.is_some()
5613            || !crate::handover::landing_checkpoint(&state)
5614        {
5615            continue;
5616        }
5617        anyhow::ensure!(
5618            crate::git::toplevel(&state.repo).await?.canonicalize()?
5619                == crate::git::toplevel(repo).await?.canonicalize()?,
5620            "public owner repository differs; inspect run lineage"
5621        );
5622        anyhow::ensure!(
5623            owner.is_none(),
5624            "multiple retained public owners; inspect run lineage"
5625        );
5626        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
5627            anyhow::bail!(reason.diagnostic(&state));
5628        }
5629        let claimed = is_working_on_other(home, id, Timestamp::now())?;
5630        anyhow::ensure!(
5631            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
5632            "public owner's driver is live or unknown; wait before retrying"
5633        );
5634        owner = Some(state);
5635    }
5636    Ok(owner)
5637}
5638
5639/// Run one claimed task to a terminal status and record the outcome.
5640///
5641/// Every transition is flushed to the queue as it happens, so the state on disk
5642/// is what actually occurred rather than what this process still intends to
5643/// write.
5644async fn attempt(
5645    opts: &Opts,
5646    queue: &Queue,
5647    status: &Arc<Mutex<Status>>,
5648    stop: &Stop,
5649    interrupt_pause: crate::graph::Pause,
5650    task: &mut Task,
5651) -> Vec<QuotaLoss> {
5652    if let Some(request) = task.sync_only.clone() {
5653        Box::pin(attempt_sync_only(
5654            queue,
5655            status,
5656            stop,
5657            interrupt_pause,
5658            task,
5659            request,
5660        ))
5661        .await;
5662        return Vec::new();
5663    }
5664    let repo = repo_for(task, &opts.repo);
5665    tracing::info!(
5666        "task {} — {} (repo {})",
5667        task.short(),
5668        task.title,
5669        repo.display()
5670    );
5671
5672    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
5673        Ok(owner) => owner,
5674        Err(e) => {
5675            task.hold_machine(Some(format!(
5676                "Cannot verify existing public owner: {e:#}; no attempt started."
5677            )));
5678            record(queue, task);
5679            return Vec::new();
5680        }
5681    };
5682    let resume_runs = public_owner
5683        .as_ref()
5684        .map(|s| vec![s.id.clone()])
5685        .unwrap_or_else(|| task.execution_runs().to_vec());
5686
5687    // A stop spends no agent resources and uses the saved landing owner.
5688    // Current roster edits, missing attachments or a failed config fetch must
5689    // never turn it into a new implementation, or prevent a PR from closing.
5690    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
5691        && previous
5692            .merge_decision
5693            .as_ref()
5694            .is_some_and(|decision| !decision.closed)
5695        && previous.status != RunStatus::Landing
5696        && !crate::merge_decision::resumable_hold(&previous)
5697    {
5698        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)));
5699        record(queue, task);
5700        return Vec::new();
5701    }
5702    let stop_owner = resume_runs
5703        .last()
5704        .and_then(|id| RunState::load(id).ok())
5705        .filter(|state| {
5706            crate::merge_decision::resumable_hold(state)
5707                || state.status == RunStatus::Landing
5708                    && state.land_approval.as_ref().is_some_and(|binding| {
5709                        Questions::open()
5710                            .get_for_effects(&binding.question)
5711                            .is_ok_and(|q| {
5712                                q.run == state.id
5713                                    && q.resolution()
5714                                        .as_deref()
5715                                        .is_some_and(crate::merge_decision::stops)
5716                            })
5717                    })
5718        });
5719    if let Some(owner) = stop_owner {
5720        let mut runner = match Runner::resume(&owner.id) {
5721            Ok(runner) => runner,
5722            Err(e) => {
5723                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
5724                record(queue, task);
5725                return Vec::new();
5726            }
5727        };
5728        runner.on_pause(stop.pause());
5729        runner.watch_interrupt(interrupt_pause);
5730        let quota_before = runner.state.quota.clone();
5731        let before_start = task.clone();
5732        task.start(owner.id.clone());
5733        if let Err(error) = queue.put(task) {
5734            *task = before_start;
5735            let error = runner.fail_startup("task-start", error);
5736            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5737                task.record_startup_failure(failure.clone());
5738            }
5739            task.hold_manual(Some(format!(
5740                "Could not persist task start; no agents dispatched: {error:#}"
5741            )));
5742            record(queue, task);
5743            return Vec::new();
5744        }
5745        lock(status).current.push(Current {
5746            worker: None,
5747            task: task.id.clone(),
5748            run: owner.id,
5749        });
5750        runner.state.carry_dispatched_resumes(task);
5751        runner.state.next_pass_task_entry = true;
5752        let result = runner.execute().await;
5753        return finish_attempt(
5754            opts.max_attempts,
5755            queue,
5756            task,
5757            &runner.state,
5758            &quota_before,
5759            result,
5760        );
5761    }
5762
5763    if let Some(owner) = &public_owner
5764        && (task.fresh_start || !may_resume_run(owner, task))
5765    {
5766        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)));
5767        record(queue, task);
5768        return Vec::new();
5769    }
5770
5771    if let Some(state) = task
5772        .execution_runs()
5773        .last()
5774        .and_then(|id| RunState::load(id).ok())
5775        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
5776    {
5777        task.hold_machine(Some(reason));
5778        record(queue, task);
5779        return Vec::new();
5780    }
5781
5782    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
5783        && !task.fresh_start
5784        && task.pr_recovery.is_none()
5785    {
5786        // A pinned infrastructure resume continues the saved reservation;
5787        // it does not authorize another base-sync interval.
5788        let sequencer_resume = crate::repair_budget::legacy::resumable_sequencer_stop(&held)
5789            && task.review_branch.is_none()
5790            && task.assignment_accepts(&held)
5791            && compatible_run_instruction(&held, task)
5792            && task
5793                .resume_override
5794                .as_ref()
5795                .is_some_and(|pin| pin.pinned_run.as_ref() == Some(&held.id));
5796        // Exhaustion authorization still takes the owner lock and execution
5797        // lease and rechecks liveness, retained HEAD and ownership.
5798        let authorized = if sequencer_resume || crate::repair_budget::conflict_pending(task, &held)
5799        {
5800            true
5801        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
5802            let home = queue.root().parent().expect("queue has a home");
5803            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
5804                Ok(()) => true,
5805                Err(error) => {
5806                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
5807                    false
5808                }
5809            }
5810        } else {
5811            false
5812        };
5813        if !authorized {
5814            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())));
5815            // Retain the existing stop identity when an old release reached the queue.
5816            task.base_sync_notice(&held);
5817            task.resume_override = None;
5818            record(queue, task);
5819            return Vec::new();
5820        }
5821    }
5822    if !task.fresh_start && task.pr_recovery.is_none() {
5823        let home = queue.root().parent().expect("queue has a home");
5824        if let crate::land_sync_recovery::DispatchDecision::Hold { reason, state } =
5825            crate::land_sync_recovery::dispatch_check(queue, home, task).await
5826        {
5827            task.hold_machine(Some(reason));
5828            task.land_sync_notice(state.as_ref());
5829            task.resume_override = None;
5830            record(queue, task);
5831            return Vec::new();
5832        }
5833    }
5834    let head_e2e_approval = match crate::head_e2e_stop::check_attempt(queue, task) {
5835        Some(crate::head_e2e_stop::AttemptGate::Hold(hold)) => {
5836            hold.apply(task);
5837            record(queue, task);
5838            return Vec::new();
5839        }
5840        Some(crate::head_e2e_stop::AttemptGate::ConsumeOwnerApproval {
5841            run,
5842            stop_id,
5843            generation,
5844            approval_at,
5845        }) => Some((run, stop_id, generation, approval_at)),
5846        None => None,
5847    };
5848    let unfinished = (!task.fresh_start)
5849        .then(|| unfinished_run(&resume_runs, task.short()))
5850        .flatten()
5851        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
5852    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
5853    if task.repair_grants.last().is_some_and(|receipt| {
5854        task.execution_runs().last() == Some(&receipt.request.run)
5855            && task.operator_decided_at == receipt.decision
5856            && previous
5857                .as_ref()
5858                .is_none_or(|run| run.id != receipt.request.run)
5859    }) {
5860        task.hold_unrequested_retry(Some(
5861            "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(),
5862        ));
5863        record(queue, task);
5864        return Vec::new();
5865    }
5866    if let Some(id) = &task.disk_resume_run
5867        && unfinished.as_ref() != Some(id)
5868    {
5869        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()));
5870        record(queue, task);
5871        return Vec::new();
5872    }
5873
5874    if !task.fresh_start
5875        && task.pr_recovery.is_none()
5876        && task.review_branch.is_none()
5877        && task.resume_override.is_none()
5878        && previous
5879            .as_ref()
5880            .is_some_and(|run| run.retired_to.is_some())
5881        && unfinished.is_none()
5882    {
5883        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()));
5884        record(queue, task);
5885        return Vec::new();
5886    }
5887
5888    let saved_recovery = previous.as_ref().filter(|run| {
5889        task.replacement.is_none()
5890            && task.pr_recovery.as_ref().is_some_and(|selected| {
5891                selected
5892                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5893                    .is_ok()
5894                    && selected_starter(selected, Some(run), unfinished.as_deref())
5895                        == Starter::Resume(run.id.clone())
5896            })
5897    });
5898
5899    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
5900    // failure here is the network's or the operator's, not the task's: hold
5901    // without spending an attempt, never fall back to a possibly stale copy.
5902    let explicit = match &task.overrides {
5903        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5904        Some(_) => opts.config.as_deref(),
5905        None => opts.config.as_deref(),
5906    };
5907    let (mut config, layers) = if let Some(run) = saved_recovery {
5908        // A matching resume owns its resolved configuration and evidence;
5909        // current layers and inherited overrides only configure new work.
5910        let mut saved = run.clone();
5911        if let Err(e) = saved.configure_recovery_resume() {
5912            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
5913            record(queue, task);
5914            return Vec::new();
5915        }
5916        (saved.config, Vec::new())
5917    } else {
5918        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
5919            Ok(loaded) => loaded,
5920            Err(e) => {
5921                let reason = format!("[config] {e:#}");
5922                record_config_failure(task, &e);
5923                task.last_error = Some(reason.clone());
5924                task.hold_machine(Some(reason));
5925                record(queue, task);
5926                return Vec::new();
5927            }
5928        };
5929        if let Err(e) = apply_options(&mut config, opts, task) {
5930            task.hold_manual(Some(format!(
5931                "[config] {e:#}; correct the merge override before releasing the task"
5932            )));
5933            record(queue, task);
5934            return Vec::new();
5935        }
5936        if let Some(selected) = &task.pr_recovery
5937            && let Err(e) = selected.configure(&mut config)
5938        {
5939            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
5940            record(queue, task);
5941            return Vec::new();
5942        }
5943        (config, layers)
5944    };
5945    let config_evidence = crate::pr_recovery::ConfigEvidence {
5946        layers,
5947        overrides: task.overrides.clone(),
5948        daemon_merge: task
5949            .overrides
5950            .as_ref()
5951            .is_none_or(|o| o.inherit_daemon_options)
5952            .then(|| opts.merge.clone())
5953            .flatten(),
5954    };
5955    apply_task_implementers(&mut config, task);
5956    if let Some(replacement) = &task.replacement {
5957        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
5958            old.liveness(false) == Liveness::Dead
5959                && old.merge_decision.as_ref().is_some_and(|d| {
5960                    d.closed
5961                        && d.question == replacement.question
5962                        && d.replacement_run.as_ref().is_none_or(|run| {
5963                            task.execution_runs().last() == Some(run)
5964                                && RunState::load(run).is_ok_and(|current| {
5965                                    current.replaces.as_ref().is_some_and(|pin| {
5966                                        pin.question == replacement.question
5967                                            && pin.agent == replacement.agent
5968                                    })
5969                                })
5970                        })
5971                })
5972        });
5973        if !safe {
5974            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()));
5975            record(queue, task);
5976            return Vec::new();
5977        }
5978        match config.agent(&replacement.agent) {
5979            Ok(agent) if crate::agent::installed(agent) => {}
5980            _ => {
5981                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)));
5982                record(queue, task);
5983                return Vec::new();
5984            }
5985        }
5986        config.graph.implementers = 1;
5987        config.graph.land_approval = true;
5988        config.merge.mode = MergeMode::Pr;
5989        config.graph.selected_implementer = Some(replacement.agent.clone());
5990    }
5991    let p = phrases(&config.graph.language);
5992    let start_failed = p.could_not_start;
5993    // Resolve once for both admission and settlement. The inputs are the
5994    // task's explicit sources (never prose), plus an explicit review source's
5995    // current head; review-only runs may rebase later, and neither fact can
5996    // refund a failed automatic generation.
5997    if let Ok(base) =
5998        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
5999            .await
6000        && let Ok(head) =
6001            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
6002    {
6003        let mut inputs = crate::queue::recovery_inputs(&task.sources);
6004        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
6005            let source = crate::git::rev_parse(&repo, branch)
6006                .await
6007                .unwrap_or_default();
6008            inputs.push_str(&format!(";review:{branch}:{source}"));
6009        }
6010        if let Some(reason) = task
6011            .recovery_exhausted(
6012                &head,
6013                &inputs,
6014                task.attempt_limit
6015                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
6016            )
6017            .filter(|_| {
6018                !task.repair_grants.last().is_some_and(|receipt| {
6019                    RunState::load(&receipt.request.run)
6020                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
6021                })
6022            })
6023        {
6024            task.hold_recovery_budget(
6025                reason,
6026                crate::queue::RecoveryAdmission { base: head, inputs },
6027            );
6028            record(queue, task);
6029            return Vec::new();
6030        }
6031        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
6032    }
6033
6034    // A resumable run of this task is carried on, never re-competed. The
6035    // candidates are built and paid for, and a fresh competition races a
6036    // second implementation against them.
6037    //
6038    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
6039    // started 3cbf on the same task a moment later, duplicating two and a
6040    // half hours of agent work. Then b25f stalled on a judge that timed out
6041    // and one that answered with no JSON - `quota: 0`, so nothing the machine
6042    // was to blame for - and 4043 started **one second** later, buying three
6043    // fresh implementations to reach the same panel. `RunStatus::resumable`
6044    // rather than `!done()` is what catches the second case: a stall is
6045    // terminal, and its cheap recovery re-asks only the absent seats.
6046    //
6047    // A load failure is warned about rather than silently read as "not
6048    // resumable": the alternative is exactly what let a schema mismatch on
6049    // run `eba2` fall through to a full re-competition with nobody told why.
6050    // `crate::conduct` is what actually offers a better answer than
6051    // `Runner::start` here (see `Recovery::Review`), once this task's next
6052    // failure shows it up as `held`/`failed` with the run state unreadable.
6053    // Keep a retained review selection intact until disk admission succeeds.
6054    let consume_review = !previous
6055        .as_ref()
6056        .is_some_and(|state| crate::repair_budget::pending(task, state));
6057    let review_branch = consume_review
6058        .then(|| review_branch_for(task, previous.as_ref()))
6059        .flatten();
6060    let branch_exists = match review_branch {
6061        Some(branch) => crate::git::branch_exists(&repo, branch)
6062            .await
6063            .unwrap_or(false),
6064        None => false,
6065    };
6066    // An explicit `magi review <branch>` is reviewed whatever happens to the
6067    // branch unless an explicit implementer change requires fresh work. An
6068    // unfinished run of the same task still wins, so a retry resumes.
6069    let proposed = review_retry_starter(
6070        task,
6071        previous.as_ref(),
6072        review_branch,
6073        branch_exists,
6074        unfinished.as_deref(),
6075    );
6076    let retry_selected = task.replacement.is_some()
6077        && task.resumption.is_some()
6078        && !task.fresh_start
6079        && previous.as_ref().is_some_and(|run| {
6080            run.replaces.is_some()
6081                && ((run.status == RunStatus::Failed && run.viable().is_empty())
6082                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
6083        });
6084    let stop_pin = task
6085        .resume_override
6086        .as_ref()
6087        .filter(|pin| {
6088            Questions::open()
6089                .get_for_effects(&pin.question_id)
6090                .is_ok_and(|q| {
6091                    q.node == land::APPROVAL_NODE
6092                        && q.resolution()
6093                            .as_deref()
6094                            .is_some_and(crate::merge_decision::stops)
6095                })
6096        })
6097        .and_then(|pin| pin.pinned_run.clone());
6098    let granted_run = task.repair_grants.last().and_then(|receipt| {
6099        let state = RunState::load(&receipt.request.run).ok()?;
6100        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
6101    });
6102    let starter = if let Some(run) = granted_run {
6103        Starter::Resume(run)
6104    } else if let Some(owner) = &public_owner {
6105        Starter::Resume(owner.id.clone())
6106    } else if let Some(run) = stop_pin {
6107        // Stop actions resume their exact owner even after seat-count edits;
6108        // they must never fall through to implementation or a takeover.
6109        Starter::Resume(run)
6110    } else if retry_selected {
6111        Starter::Resume(previous.as_ref().unwrap().id.clone())
6112    } else if let Some(selected) = &task.pr_recovery {
6113        if selected
6114            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
6115            .is_ok()
6116        {
6117            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
6118        } else {
6119            Starter::Review(selected.branch.clone())
6120        }
6121    } else {
6122        starter_with_implementers(task, previous.as_ref(), proposed)
6123    };
6124    // A retained execution still writes to its saved output volume. A newer
6125    // repository policy only selects the volume for a fresh run.
6126    let disk_reason = match &starter {
6127        Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
6128            || {
6129                RunState::load(id)
6130                    .ok()
6131                    .and_then(|run| disk_gate(&run.repo, &run.config))
6132            },
6133            |run| disk_gate(&run.repo, &run.config),
6134        ),
6135        _ => disk_gate(&repo, &config),
6136    };
6137    if let Some(reason) = disk_reason {
6138        task.notice_cause("disk-space", None, None);
6139        task.last_error = Some(reason.clone());
6140        let disk_checked_at = task.disk_checked_at;
6141        task.hold_machine(Some(reason.clone()));
6142        if matches!(starter, Starter::Resume(_)) {
6143            task.mark_disk_capacity();
6144        } else {
6145            task.mark_startup_disk_capacity();
6146        }
6147        task.disk_checked_at = disk_checked_at;
6148        record(queue, task);
6149        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
6150        notices::raise(
6151            Notice::warn(
6152                &format!("disk:{}", repo.display()),
6153                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
6154            )
6155            .link(Link::Task {
6156                id: task.id.clone(),
6157            }),
6158        );
6159        return Vec::new();
6160    }
6161    let review_branch = if consume_review {
6162        let valid = review_branch.is_some();
6163        task.review_instruction = None;
6164        task.review_branch.take().filter(|_| valid)
6165    } else {
6166        None
6167    };
6168    // An explicit resume pin must never degrade into a new competition or
6169    // takeover, including when its run stops being eligible after the answer.
6170    if let Some(pin) = &task.resume_override
6171        && let Some(run) = &pin.pinned_run
6172        && starter != Starter::Resume(run.clone())
6173    {
6174        let run = run.clone();
6175        task.notice_cause("resume-owner", Some(&run), None);
6176        task.hold_machine(Some(format!(
6177            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
6178            task.id
6179        )));
6180        record(queue, task);
6181        return Vec::new();
6182    }
6183    // Automatic disk recovery resumes its retained run or stops: a changed
6184    // seat count or review branch must not turn it into a new competition.
6185    // No attempt is spent here.
6186    if let Some(run) = &task.disk_resume_run
6187        && starter != Starter::Resume(run.clone())
6188    {
6189        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()));
6190        record(queue, task);
6191        return Vec::new();
6192    }
6193    if task.replacement.is_some()
6194        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
6195        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
6196    {
6197        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()));
6198        record(queue, task);
6199        return Vec::new();
6200    }
6201    if let Some((ref run, ..)) = head_e2e_approval
6202        && starter != Starter::Resume(run.clone())
6203    {
6204        task.hold_machine(Some(format!(
6205            "Conclusive head_e2e stop on run {run} cannot resume safely with current task settings; inspect `magi show {run}` before retrying. No replacement competition was started."
6206        )));
6207        record(queue, task);
6208        return Vec::new();
6209    }
6210    if let Some(reason) = retained_attempt_hold(
6211        task,
6212        &starter,
6213        config.disk.retained_attempt_limit,
6214        RunState::load,
6215    ) {
6216        // The review choice was consumed above. Preserve it across this hold
6217        // so a later release cannot silently become a fresh implementation.
6218        if let Starter::Review(branch) = &starter {
6219            task.review_branch = Some(branch.clone());
6220        }
6221        task.hold_unrequested_retry(Some(reason));
6222        record(queue, task);
6223        return Vec::new();
6224    }
6225    // Absolute paths of the files the task was filed with, re-read from the
6226    // task now so a file attached while it was held reaches a resumed run
6227    // too. A stored name whose file has gone is an error before any agent is
6228    // paid for, never a silent omission the implementer cannot notice.
6229    let attachments = match task_attachments(queue, task) {
6230        Ok(a) => a,
6231        Err(e) => {
6232            task.attempts += 1;
6233            task.fail_startup_target(
6234                "startup-attachments",
6235                e.name.clone(),
6236                format!("{start_failed}{e:#}"),
6237                opts.max_attempts,
6238            );
6239            record(queue, task);
6240            return Vec::new();
6241        }
6242    };
6243    let startup_pause = stop.pause();
6244    let startup_interrupt = interrupt_pause.clone();
6245    let wait = crate::repo_lock::WaitPolicy::new(
6246        Duration::from_secs(config.graph.timeout_resource_wait),
6247        move || startup_pause.parked() || startup_interrupt.parked(),
6248    );
6249    // Startup includes review takeover and recovery. Do not embed its large
6250    // future in both the wait scope and the surrounding attempt stack frame.
6251    let started = wait.scope(Box::pin(async { match &starter {
6252        Starter::Review(_) if task.pr_recovery.is_some() => {
6253            let selected = task.pr_recovery.clone().expect("selected recovery");
6254            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
6255                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
6256                    .await
6257                    .map(|mut r| {
6258                        r.state.attachments = attachments.clone();
6259                        r
6260                    }),
6261                Err(e) => Err(e),
6262            }
6263        }
6264        Starter::Review(branch) => {
6265            tracing::info!(
6266                "task {} reopens `{branch}` as a review-only pass",
6267                task.short()
6268            );
6269            // Every earlier attempt is superseded by the one being minted
6270            // now, so a branch one of them still holds may be taken over.
6271            let takeover = crate::handover::Takeover {
6272                earlier: task.earlier_attempts().to_vec(),
6273                home: crate::run::home(),
6274                choice: take_divergence_answer(branch, &config.merge.remote, task),
6275                task_instruction: Some(instruction_for(task)),
6276            };
6277            Runner::review_taking_over(
6278                &repo,
6279                branch,
6280                config,
6281                Some(takeover),
6282                crate::run::Origin::queue(&task.id),
6283            )
6284            .await
6285        }
6286        Starter::Resume(id) => {
6287            tracing::info!("resuming run {id} rather than competing again");
6288            Runner::resume(id).and_then(|mut r| {
6289                if retry_selected {
6290                    // The explicit queue release retries this same pinned
6291                    // implementation, preserving the attempt and worktrees.
6292                    for candidate in &mut r.state.candidates {
6293                        candidate.failed = None;
6294                        candidate.empty = false;
6295                        candidate.commits = 0;
6296                    }
6297                    r.state.status = RunStatus::Implementing;
6298                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
6299                }
6300                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
6301                    r.state.sources = task.sources.clone();
6302                }
6303                if r.state.prep_failure.is_some() {
6304                    let approval = task
6305                        .resumption
6306                        .as_ref()
6307                        .context("preparation retry requires an explicit task release")?;
6308                    r.retry_preparation(approval.at)?;
6309                }
6310                if let Some(instruction) =
6311                    prepare_instruction(&starter, Some(&r.state.instruction), task)
6312                {
6313                    r.state.instruction = instruction;
6314                }
6315                r.state.attachments = attachments.clone();
6316                if task.replacement.is_some() {
6317                    r.state.config.merge.mode = MergeMode::Pr;
6318                    r.state.config.graph.land_approval = true;
6319                }
6320                // Replacements publish a new PR and ask again. Selected PR
6321                // recoveries keep their saved disposition; ordinary runs can
6322                // retain the task's merge override.
6323                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
6324                    .overrides
6325                    .as_ref()
6326                    .and_then(|o| o.merge.as_deref())
6327                    .and_then(|m| merge_mode(m).ok())
6328                {
6329                    r.state.config.merge.mode = mode;
6330                }
6331                Ok(r)
6332            })
6333        }
6334        Starter::Start => {
6335            if let Some(branch) = &review_branch {
6336                tracing::warn!(
6337                    "conductor chose review for task {} but branch `{branch}` no longer \
6338                     exists; requeuing as a fresh competition instead",
6339                    task.short()
6340                );
6341            }
6342            let instruction = prepare_instruction(&starter, None, task)
6343                .unwrap_or_else(|| task.instruction.clone());
6344            Runner::start_naming(
6345                &repo,
6346                instruction,
6347                &task.title,
6348                config,
6349                crate::run::Origin::queue(&task.id),
6350            )
6351            .await
6352            .map(|mut r| {
6353                r.state.attachments = attachments.clone();
6354                r.state.sources = task.sources.clone();
6355                r
6356            })
6357        }
6358    }})).await;
6359    if let Err(error) = &started
6360        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
6361    {
6362        task.record_startup_failure(failure.clone());
6363    }
6364    let mut runner = match started {
6365        Ok(r) => r,
6366        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6367            let detail = format!("{e:#}");
6368            task.last_error = Some(detail.clone());
6369            if e.is::<crate::build_target::AdmissionDiskWait>()
6370                && let Starter::Review(branch) = &starter
6371                && review_branch.is_some()
6372            {
6373                task.review_branch = Some(branch.clone());
6374                task.review_instruction = Some(task.instruction.clone());
6375            }
6376            if stop.parking() || interrupt_pause.parked() {
6377                let attempts = task.attempts;
6378                task.park(e.to_string());
6379                // Startup has not spent an attempt to refund.
6380                task.attempts = attempts;
6381            } else if e.is::<crate::build_target::AdmissionDiskWait>() {
6382                let disk_checked_at = task.disk_checked_at;
6383                task.hold_machine(Some(detail));
6384                task.mark_startup_disk_capacity();
6385                task.disk_checked_at = disk_checked_at;
6386            } else {
6387                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
6388            }
6389            record(queue, task);
6390            return Vec::new();
6391        }
6392        // A branch an earlier attempt still holds and magi will not release
6393        // by itself is the operator's call, not a failed attempt: hold the
6394        // task with the reason, spend nothing, and say so on the bell.
6395        Err(e) if task.pr_recovery.is_some() => {
6396            task.startup_notice_cause("startup-public-head");
6397            task.attempts += 1;
6398            task.last_error = Some(format!("{start_failed}{e:#}"));
6399            task.hold_unrequested_retry(Some(format!(
6400                "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."
6401            )));
6402            record(queue, task);
6403            return Vec::new();
6404        }
6405        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
6406            let detail = match e.downcast_ref::<crate::handover::Refused>() {
6407                Some(r) => (p.handover_refused)(r),
6408                None => format!("{e:#}"),
6409            };
6410            task.startup_notice_cause("startup-handover");
6411            let reason = format!("{start_failed}{detail}");
6412            task.last_error = Some(reason.clone());
6413            // Consumed above by `take`; keep it so the released task retries
6414            // as a review of this same branch.
6415            let branch = match &starter {
6416                Starter::Review(branch) => Some(branch.clone()),
6417                _ => None,
6418            };
6419            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
6420            // one page; the guidance rides in the reason, fixed per state so a
6421            // re-put never changes the wording and relights it.
6422            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
6423            record(queue, task);
6424            tracing::warn!(
6425                "holding {} for a branch it cannot take over: {e:#}",
6426                task.short()
6427            );
6428            return Vec::new();
6429        }
6430        // A branch that differs between here and the remote in ways magi
6431        // cannot prove are the same change is a decision for the owner, not a
6432        // failed attempt: ask with both sides laid out, spend no attempt, and
6433        // let the answer requeue the task.
6434        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
6435            let d = e
6436                .downcast_ref::<crate::reconcile::Diverged>()
6437                .expect("checked by the guard");
6438            let mut q = ask::Question::new(
6439                task.id.clone(),
6440                crate::reconcile::NODE.to_owned(),
6441                crate::reconcile::SEAT.to_owned(),
6442                d.summary(),
6443                d.detail(),
6444                d.choices(),
6445            );
6446            match Questions::open().put(&mut q) {
6447                Ok(()) => {
6448                    task.last_error = Some(format!("{e:#}"));
6449                    // Consumed above by `take`; the answer has to reach a review
6450                    // of this same branch, so keep pointing the task at it.
6451                    task.review_branch = Some(d.branch.clone());
6452                    task.review_instruction = Some(task.instruction.clone());
6453                    task.block(vec![q.id.clone()], Some(d.summary()));
6454                }
6455                Err(put) => {
6456                    tracing::warn!("could not file the divergence question: {put:#}");
6457                    task.attempts += 1;
6458                    task.fail_startup(
6459                        "startup-question-store",
6460                        format!("{start_failed}{e:#}"),
6461                        opts.max_attempts,
6462                    );
6463                }
6464            }
6465            record(queue, task);
6466            return Vec::new();
6467        }
6468        Err(e) => {
6469            // The answer was stale and nothing was applied: keep pointing at
6470            // the branch so the next attempt asks again against its new tips.
6471            // Nothing went wrong with the task, so no attempt is spent: a
6472            // budget one short of its limit must not hold it instead of
6473            // letting the question be asked again.
6474            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
6475                && let Starter::Review(branch) = &starter
6476            {
6477                task.review_branch = Some(branch.clone());
6478                task.review_instruction = Some(task.instruction.clone());
6479                task.last_error = Some(format!("{start_failed}{e:#}"));
6480                task.status = crate::queue::TaskStatus::Failed;
6481                record(queue, task);
6482                return Vec::new();
6483            }
6484            task.attempts += 1;
6485            task.last_error = Some(format!("{start_failed}{e:#}"));
6486            task.startup_notice_cause("startup-source");
6487            task.hold_unrequested_retry(Some(format!(
6488                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
6489            )));
6490            record(queue, task);
6491            return Vec::new();
6492        }
6493    };
6494    if !matches!(starter, Starter::Resume(_))
6495        && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
6496    {
6497        runner
6498            .state
6499            .event("build-cache", format!("{mode} selected by {source}"));
6500    }
6501    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
6502        runner.state.recovery_config = Some(config_evidence);
6503    }
6504    if let Some(replacement) = &task.replacement {
6505        if matches!(starter, Starter::Start) {
6506            runner.state.instruction.push_str(&format!(
6507                "\n\n# Replacement review context\n{}",
6508                replacement.context
6509            ));
6510        }
6511        runner.state.replaces = Some(replacement.clone());
6512        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
6513        if let Ok(mut old) = RunState::load(&replacement.run)
6514            && let Some(d) = &mut old.merge_decision
6515        {
6516            d.replacement_run = Some(runner.state.id.clone());
6517            old.event(
6518                "replacement",
6519                format!(
6520                    "replacement run {} owns the next attempt; old PR remains closed",
6521                    runner.state.id
6522                ),
6523            );
6524            if let Err(e) = old.save() {
6525                let error = runner.fail_startup("replacement-history", e);
6526                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
6527                    task.record_startup_failure(failure.clone());
6528                }
6529                task.hold_manual(Some(format!(
6530                    "Could not link replacement history: {error:#}; no agents dispatched"
6531                )));
6532                record(queue, task);
6533                return Vec::new();
6534            }
6535        }
6536    }
6537    runner.state.task_instruction = Some(task.instruction.clone());
6538    // The follow-up depth is fixed now, while the task certainly exists:
6539    // deleting it later must not reset the cap (`crate::followup`).
6540    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
6541    if runner.state.origin_chat.is_none() {
6542        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
6543    }
6544    // A stop that means "park" reaches the graph through this handle.
6545    runner.on_pause(stop.pause());
6546    // `poll`'s interrupt scheduler reaches this one run - and no other -
6547    // through this handle. See `Pause`'s own doc for why these are never
6548    // the same one.
6549    runner.watch_interrupt(interrupt_pause);
6550
6551    // `start` has minted the run, so the task can now point at it. Persisting
6552    // `Running` before `execute` is what makes a crash mid-run legible.
6553    let run = runner.state.id.clone();
6554    let before_start = task.clone();
6555    task.start(run.clone());
6556    if let Err(error) = queue.put(task) {
6557        *task = before_start;
6558        let error = runner.fail_startup("task-start", error);
6559        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
6560            task.record_startup_failure(failure.clone());
6561        }
6562        task.hold_manual(Some(format!(
6563            "Could not persist task start; no agents dispatched: {error:#}"
6564        )));
6565        record(queue, task);
6566        return Vec::new();
6567    }
6568    if task.status != TaskStatus::Running {
6569        // Queue::put kept a newer hold or continuation instead of this start.
6570        return Vec::new();
6571    }
6572    lock(status).current.push(Current {
6573        worker: None,
6574        task: task.id.clone(),
6575        run,
6576    });
6577
6578    // `RunState::quota` is the run's whole history across every resume, so
6579    // only what this execution added may arm the cooldown or earn a refund.
6580    let quota_before = runner.state.quota.clone();
6581    runner.state.carry_dispatched_resumes(task);
6582    runner.state.entry_resumption_generation =
6583        Some(task.resumption.as_ref().map_or(0, |r| r.generation));
6584    if let Some((run, stop_id, generation, approval_at)) = head_e2e_approval
6585        && runner.state.id == run
6586    {
6587        crate::head_e2e_stop::record_consumed_approval(
6588            &mut runner.state,
6589            &task.id,
6590            &stop_id,
6591            generation,
6592            approval_at,
6593        );
6594    }
6595    runner.state.next_pass_task_entry = true;
6596    let result = runner.execute().await;
6597    finish_attempt(
6598        opts.max_attempts,
6599        queue,
6600        task,
6601        &runner.state,
6602        &quota_before,
6603        result,
6604    )
6605}
6606
6607async fn attempt_sync_only(
6608    queue: &Queue,
6609    status: &Arc<Mutex<Status>>,
6610    stop: &Stop,
6611    interrupt: crate::graph::Pause,
6612    task: &mut Task,
6613    request: crate::base_sync_only::Request,
6614) {
6615    let result = async {
6616        anyhow::ensure!(
6617            task.status == TaskStatus::Queued
6618                && task.execution_runs().last() == Some(&request.run)
6619                && task.resume_override.as_ref().is_some_and(
6620                    |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
6621                ),
6622            "sync-base-only request no longer owns the exact queued run"
6623        );
6624        let mut runner = Runner::resume(&request.run)?;
6625        anyhow::ensure!(
6626            public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
6627                .await?
6628                .is_none(),
6629            "the task still has a public execution owner"
6630        );
6631        anyhow::ensure!(
6632            !stop.parking() && !interrupt.parked(),
6633            "paused before base synchronization"
6634        );
6635        let original = task.clone();
6636        task.start(request.run.clone());
6637        task.attempts = original.attempts;
6638        if let Err(error) = queue.put(task) {
6639            *task = original;
6640            return Err(error);
6641        }
6642        if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
6643            return Ok(());
6644        }
6645        lock(status).current.push(Current {
6646            worker: None,
6647            task: task.id.clone(),
6648            run: request.run.clone(),
6649        });
6650        runner.on_pause(stop.pause());
6651        runner.watch_interrupt(interrupt);
6652        runner.execute_sync_only(request.clone()).await
6653    }
6654    .await;
6655    if task.sync_only.as_ref() == Some(&request) {
6656        let saved = RunState::load(&request.run).ok();
6657        let detail = result.err().map(|error| {
6658            format!("Base synchronization only: {error:#}; verification was not allowed")
6659        });
6660        crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
6661        record(queue, task);
6662    }
6663}
6664
6665/// Settle `task` after its run executed: the verdict, the diagnosis, the
6666/// supersession of earlier attempts and the save. Shared by the loop and by
6667/// `magi run --resume`, so an attempt is counted one way wherever it ran.
6668/// Returns the quota losses this execution added to the run.
6669pub fn finish_attempt(
6670    max_attempts: usize,
6671    queue: &Queue,
6672    task: &mut Task,
6673    state: &RunState,
6674    quota_before: &[QuotaLoss],
6675    result: Result<()>,
6676) -> Vec<QuotaLoss> {
6677    let detail = match result {
6678        Ok(()) => describe(state),
6679        Err(e) => format!("{e:#}"),
6680    };
6681    let fresh = losses_this_attempt(quota_before, &state.quota);
6682    let verdict = Verdict {
6683        status: state.status,
6684        // A run that opened a pull request handed its work over, whatever the
6685        // gate then decided about merging it.
6686        left_pr: state.pr.is_some(),
6687        // Only a rate limit earns the task its attempt back - and only one
6688        // suffered now: a refund justified by a previous session's loss is
6689        // the same mistake as re-arming the cooldown from it. A stalled run
6690        // resumed without hitting quota again therefore spends its attempt,
6691        // like any other failure of the task's own.
6692        quota_hit: !fresh.is_empty(),
6693        // A run that parked was asked to stop; that is not a failure and must
6694        // not spend an attempt, or replacing the binary a few times would
6695        // exhaust a task's budget without an agent ever misbehaving.
6696        parked: state.parked,
6697        // A quota loss that left nothing viable is the same machine fact as a
6698        // `Stalled` quota loss; see `settle`'s doc table.
6699        no_viable_candidates: state.viable().is_empty(),
6700    };
6701    if let Some(replacement) = &state.replaces
6702        && let Some(pr) = &state.pr
6703        && let Ok(mut old) = RunState::load(&replacement.run)
6704        && let Some(d) = &mut old.merge_decision
6705    {
6706        d.replacement_pr = Some(pr.url.clone());
6707        let _ = old.save();
6708    }
6709    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
6710    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
6711        task.hold_unrequested_retry(Some(format!(
6712            "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.",
6713            task.short()
6714        )));
6715    }
6716    if task.status == TaskStatus::Done {
6717        supersede_prior_runs(task, &crate::run::home());
6718    }
6719    record(queue, task);
6720    tracing::info!(
6721        "task {} is {} after run {} ({})",
6722        task.short(),
6723        task.status.as_str(),
6724        state.short(),
6725        label(state.status)
6726    );
6727    fresh
6728}
6729
6730/// A task a hand-started run leaves runnable (failed with attempts to spare,
6731/// or requeued) is **held**: nobody asked for a retry, and a loop starting
6732/// later must not spend agent calls on it. `magi task release` retries.
6733pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
6734    // Parked work (including legacy Failed records with a parked run) is a
6735    // checkpoint or owner handoff, not an unrequested retry.
6736    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
6737        && !awaiting_resume_with(task, RunState::load)
6738        // A run parked on the owner's word about a withheld PR title/body
6739        // resumes via `land_resume_state`, including review-only tasks that
6740        // `awaiting_resume_with` does not consider.
6741        && withheld_text_wait(task).is_none()
6742        && !(task.fresh_start && task.replacement.is_some())
6743    {
6744        let why = task.last_error.clone().map_or_else(
6745            || "the run did not finish".to_owned(),
6746            |e| format!("the run did not finish: {e}"),
6747        );
6748        task.hold_unrequested_retry(Some(format!(
6749            "{why}. It was started by hand, so it is not retried \
6750             automatically; `magi task release` retries it."
6751        )));
6752        record(queue, task);
6753    }
6754}
6755
6756/// Whether an attempt at a task whose newest run is `run` would resume that
6757/// run rather than start a fresh competition. `magi run --resume` hands a run
6758/// to a live loop only when this holds.
6759#[must_use]
6760pub fn loop_would_resume(run: &str) -> bool {
6761    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
6762}
6763
6764/// A loop in another process that is alive right now: a fresh heartbeat in
6765/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
6766/// carries the pid it published (`None` inside when it published none - a
6767/// fresh heartbeat is still evidence of a live loop).
6768///
6769/// The one judgement of "is somebody else serving this queue", shared by the
6770/// web UI's refusal to start a second loop and by `magi run` / `magi review`
6771/// deciding whether to hand a task to the loop. A claim file proves nothing
6772/// here: whether a claim succeeds says nothing about whether its owner lives.
6773#[must_use]
6774pub fn foreign_loop(
6775    reading: Option<&Reading>,
6776    now: Timestamp,
6777    own_pid: u32,
6778) -> Option<Option<u32>> {
6779    let reading = reading.filter(|r| r.running(now))?;
6780    match reading.pid {
6781        Some(pid) if pid == own_pid => None,
6782        pid => Some(pid),
6783    }
6784}
6785
6786fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
6787    reading.worker_protocol != Some(1)
6788        && (foreign_loop(Some(reading), now, own_pid).is_some()
6789            || reading
6790                .pid
6791                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
6792}
6793
6794/// Low-level claimed-task execution shared by the detached standalone worker
6795/// and focused lifecycle fixtures. The caller must retain the queue claim for
6796/// this entire call. CLI callers transfer ownership through
6797/// [`run_detached_claimed`] instead of executing inside their own runtime.
6798///
6799/// The one deliberate difference from the loop: a task the attempt leaves
6800/// runnable (failed with attempts to spare, or requeued) is **held** instead.
6801/// Nobody asked for a retry, and a daemon starting later must not spend agent
6802/// calls re-running a hand-started task behind the operator's back;
6803/// `magi task release` is the explicit retry.
6804pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
6805    run_claimed_until(opts, queue, task, &Stop::new()).await;
6806}
6807
6808async fn run_claimed_until(
6809    opts: &Opts,
6810    queue: &Queue,
6811    task: &mut Task,
6812    stop: &Stop,
6813) -> Vec<QuotaLoss> {
6814    let status = Arc::new(Mutex::new(Status::new()));
6815    // An attempt embeds startup and graph futures. Keep it off the standalone
6816    // caller's stack, on both the initial execution and withheld-text resume.
6817    let mut quota = Box::pin(attempt(
6818        opts,
6819        queue,
6820        &status,
6821        stop,
6822        crate::graph::Pause::new(),
6823        task,
6824    ))
6825    .await;
6826    // A run parked on the owner's word about a withheld PR title/body has no
6827    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
6828    // here with the claim still held, and resume once the question is settled
6829    // (answered, or abandoned at its deadline -> the neutral text).
6830    // A rejected reply files one more question (the gate asks at most twice),
6831    // so after a resume the run may be waiting again: keep going, with a fresh
6832    // limit for the new question. `resumes` bounds it even if a resume parks
6833    // without asking anything new.
6834    let mut resumes = 0;
6835    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
6836        let Some(timeout) = withheld_text_wait(task) else {
6837            break;
6838        };
6839        eprintln!(
6840            "waiting for the owner's answer on a withheld pull request text \
6841             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
6842        );
6843        // The deadline abandons the question itself; the extra margin only
6844        // covers an abandon that could not be saved.
6845        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
6846        let ready = loop {
6847            match land_resume_state(task) {
6848                LandResume::StillWaiting
6849                    if !stop.parking() && std::time::Instant::now() < limit =>
6850                {
6851                    tokio::time::sleep(WITHHELD_POLL).await;
6852                }
6853                LandResume::Ready => break true,
6854                _ => break false,
6855            }
6856        };
6857        if !ready || stop.parking() {
6858            break;
6859        }
6860        resumes += 1;
6861        quota.extend(
6862            Box::pin(attempt(
6863                opts,
6864                queue,
6865                &status,
6866                stop,
6867                crate::graph::Pause::new(),
6868                task,
6869            ))
6870            .await,
6871        );
6872    }
6873    hold_if_runnable(queue, task);
6874    quota
6875}
6876
6877/// Resumes an in-process run makes for withheld-text questions: the gate asks
6878/// at most twice, plus one for a resume that asks nothing new.
6879const MAX_WITHHELD_RESUMES: u32 = 3;
6880
6881/// How often an in-process run rechecks its withheld-text question.
6882const WITHHELD_POLL: Duration = Duration::from_secs(15);
6883
6884/// The `answer_timeout` (seconds) of the task's last run when that run is
6885/// parked on an unresolved withheld-text question; `None` otherwise.
6886fn withheld_text_wait(task: &Task) -> Option<u64> {
6887    let id = task.execution_runs().last()?;
6888    let s = RunState::load(id).ok()?;
6889    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
6890        .then_some(s.config.graph.answer_timeout)
6891}
6892
6893/// The quota losses `after` holds that `before` did not: what one execution
6894/// suffered, as opposed to the run's history.
6895///
6896/// Compared by value rather than by length or position because
6897/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
6898/// the vector can shrink and shift under a resume. A retried seat that hits
6899/// quota again is a `push` with a new `at`, so it shows up as new here.
6900/// Crash recovery uses the recorded pass start as its boundary when available;
6901/// legacy records without passes retain their original history-based policy.
6902fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
6903    after
6904        .iter()
6905        .filter(|q| !before.contains(q))
6906        .cloned()
6907        .collect()
6908}
6909
6910/// When the loop-wide quota cooldown should end, given this attempt's losses;
6911/// `None` when there were none. Reset-hint parsing and the cap live here.
6912fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
6913    let quota: Vec<_> = quota
6914        .iter()
6915        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
6916        .collect();
6917    if quota.is_empty() {
6918        return None;
6919    }
6920    let with_hint = quota.iter().find(|q| q.reset.is_some());
6921    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
6922    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
6923    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
6924    Some(
6925        now.checked_add(jiff::SignedDuration::from_secs(secs))
6926            .unwrap_or(Timestamp::MAX),
6927    )
6928}
6929
6930/// An explicit task count must agree with a run before any resume.
6931fn implementers_match(task: &Task, state: &RunState) -> bool {
6932    task.replacement.as_ref().map_or_else(
6933        || {
6934            task.implementers()
6935                .is_none_or(|n| n == state.config.graph.implementers)
6936        },
6937        |replacement| {
6938            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
6939                && state.config.graph.implementers == 1
6940        },
6941    )
6942}
6943
6944/// Never resume or take over candidate work built for a different seat count.
6945fn starter_with_implementers(
6946    task: &Task,
6947    previous: Option<&RunState>,
6948    proposed: Starter,
6949) -> Starter {
6950    if previous.is_some_and(|s| !implementers_match(task, s)) {
6951        task.review_of
6952            .as_ref()
6953            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
6954    } else {
6955        proposed
6956    }
6957}
6958
6959/// Apply this task's explicit count to the new attempt, without changing defaults.
6960fn apply_task_implementers(config: &mut Config, task: &Task) {
6961    if let Some(n) = task.implementers() {
6962        config.graph.implementers = n;
6963    }
6964}
6965
6966/// [`prepare`] for one task: its own `--config` and command-line overrides
6967/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
6968/// over the loop's, so handing a hand-started task to a daemon changes nothing
6969/// about what it does.
6970#[cfg(test)]
6971fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
6972    let explicit = match &task.overrides {
6973        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
6974        _ => opts.config.as_deref(),
6975    };
6976    let (mut config, _) = Config::discover(repo, explicit)?;
6977    apply_options(&mut config, opts, task)?;
6978    Ok(config)
6979}
6980
6981fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
6982    if task
6983        .overrides
6984        .as_ref()
6985        .is_none_or(|o| o.inherit_daemon_options)
6986        && let Some(mode) = opts.merge.as_deref()
6987    {
6988        config.merge.mode = merge_mode(mode)?;
6989    }
6990    if let Some(o) = &task.overrides {
6991        o.apply(config);
6992    }
6993    if let Some((mode, _)) = task.build_cache_override(config) {
6994        config.verify.build_cache = mode;
6995    }
6996    Ok(())
6997}
6998
6999/// Load the config for a task's repository, with the merge override applied.
7000fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
7001    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
7002    if let Some(mode) = &opts.merge {
7003        config.merge.mode = merge_mode(mode)?;
7004    }
7005    Ok(config)
7006}
7007
7008/// Prune the shared build cache at a between-runs boundary. The detached cache
7009/// service checks authoritative task jobs first; dispatch waits for that finite
7010/// service, so scheduler replacement cannot turn a compile into idle cleanup.
7011/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
7012async fn maybe_prune_cache_between_runs(
7013    repo: &Path,
7014    opts: &Opts,
7015    home: &Path,
7016    stop: &Stop,
7017    last_checked: &mut Option<Timestamp>,
7018    now: Timestamp,
7019) {
7020    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
7021        return;
7022    }
7023    *last_checked = Some(now);
7024    let cfg = match prepare(repo, opts) {
7025        Ok(cfg) => cfg,
7026        Err(e) => {
7027            tracing::warn!("cache check: no config: {e:#}");
7028            return;
7029        }
7030    };
7031    match clean::prune_cache_if_over_limit(&cfg, home) {
7032        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
7033            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
7034            pruned.files,
7035            pruned.freed
7036        ),
7037        Ok(_) => {}
7038        Err(e) => {
7039            tracing::warn!("housekeep: prune cache: {e:#}");
7040            notices::raise_in(
7041                home,
7042                Notice::warn(
7043                    "housekeep:cache",
7044                    format!(
7045                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
7046                        e.to_string()
7047                            .lines()
7048                            .next()
7049                            .unwrap_or("unknown cleanup error")
7050                    ),
7051                ),
7052            );
7053        }
7054    }
7055}
7056
7057/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
7058/// now, given when it last did (if ever). Pure, so the cadence is asserted
7059/// directly rather than by waiting out real minutes in a test.
7060fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
7061    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
7062}
7063
7064/// The disk janitor, with its housekeeping logged rather than fatal.
7065///
7066/// Called only at the loop's idle points, for the reason the caller documents:
7067/// a prune racing a live compile would delete files mid-build. The config is
7068/// re-read on every call because the repository that just ran may not be the
7069/// daemon's own default, and the cache directory is a repository fact.
7070///
7071/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
7072/// and [`crate::run::default_worktree_root`] read here, for the same reason
7073/// [`drive`] takes its queue and status file rather than resolving them: a
7074/// test driving the loop must not reach through to the operator's real home
7075/// or worktree bay just because the janitor runs on every idle tick.
7076/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
7077/// to get wrong silently - a test's `home` was already isolated, but nothing
7078/// exercised the parameter next to it, so a real worktree bay stayed wired in
7079/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
7080/// it for real, every test in this file that drives the loop at all started
7081/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
7082async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
7083    let cfg = match prepare(repo, opts) {
7084        Ok(cfg) => cfg,
7085        Err(e) => {
7086            tracing::warn!("housekeep: no config: {e:#}");
7087            return;
7088        }
7089    };
7090    // A run's own worktree lives under `config.graph.worktree_root` when the
7091    // repository sets one - the same precedence `RunState::worktree_root`
7092    // uses - and `worktrees_root` only stands in for the *default* an
7093    // unconfigured repository resolves to (see this function's own
7094    // parameter, or the test fixture wiring one to a fake path). Housekeeping
7095    // that always swept the default regardless of this override would never
7096    // see, and so never reclaim, a single worktree for a repository that
7097    // relocated them elsewhere.
7098    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
7099    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
7100    // Reported whenever there is anything to say, not only when `folded > 0`:
7101    // the incident this exists to prevent was 90 of 93 runs skipped and 0
7102    // folded, on every single pass, for months - a report gated on `folded`
7103    // would have stayed silent through every one of them.
7104    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
7105        let mut extra = Vec::new();
7106        if out.unreadable > 0 {
7107            extra.push(format!("{} unreadable", out.unreadable));
7108        }
7109        if out.orphaned_worktrees > 0 {
7110            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
7111        }
7112        let detail = if extra.is_empty() {
7113            String::new()
7114        } else {
7115            format!(" ({})", extra.join(", "))
7116        };
7117        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
7118    }
7119    if out.external_merges_recorded > 0 {
7120        tracing::info!(
7121            "housekeep: recorded {} run(s) as merged externally",
7122            out.external_merges_recorded
7123        );
7124    }
7125    if out.stale_pr_states_repaired > 0 {
7126        tracing::info!(
7127            "housekeep: rewrote {} run record(s) whose pull request had already settled",
7128            out.stale_pr_states_repaired
7129        );
7130    }
7131    if out.cache_files > 0 {
7132        tracing::info!(
7133            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
7134            out.cache_files,
7135            out.cache_freed
7136        );
7137    }
7138    if out.questions_abandoned > 0 {
7139        tracing::info!(
7140            "housekeep: abandoned {} question(s) left open by a finished run",
7141            out.questions_abandoned
7142        );
7143    }
7144}
7145
7146/// Run [`triage::run_once`] and log whatever it did, the same "only when
7147/// there is something to say" rule [`janitor`] follows for its own report.
7148///
7149/// Called at the same idle points as [`janitor`] - once per full poll
7150/// interval, never mid-attempt - for the same reason: it is not liveness
7151/// critical, and a task's own `hold_reason` string is the one thing this
7152/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
7153/// tick for no benefit.
7154async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
7155    let questions = Questions::at(home.join("questions"));
7156    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
7157    if report.is_empty() {
7158        return;
7159    }
7160    if !report.quarantined.is_empty() {
7161        tracing::info!(
7162            "triage: held {} blocked task(s) whose blocked-on task or \
7163             question no longer exists: {}",
7164            report.quarantined.len(),
7165            report.quarantined.join(", ")
7166        );
7167    }
7168    if !report.resumed.is_empty() {
7169        tracing::info!(
7170            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
7171            report.resumed.len(),
7172            report.resumed.join(", ")
7173        );
7174    }
7175    if !report.asked.is_empty() {
7176        tracing::info!(
7177            "triage: asked about {} held task(s): {}",
7178            report.asked.len(),
7179            report.asked.join(", ")
7180        );
7181    }
7182    if !report.answered.is_empty() {
7183        tracing::info!(
7184            "triage: applied {} operator answer(s): {}",
7185            report.answered.len(),
7186            report.answered.join(", ")
7187        );
7188    }
7189}
7190
7191/// The free-space gate: what stands between this task and a new run, if
7192/// anything. `Some(reason)` holds the task; `None` lets it start.
7193///
7194/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
7195/// the operator opted out. A measurement failure is a gate, not a pass: both
7196/// sides of "cannot tell" are served by not starting.
7197pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
7198    disk_gate_at(repo, config, crate::run::home)
7199}
7200
7201pub(crate) fn disk_gate_at(
7202    repo: &Path,
7203    config: &Config,
7204    home: impl FnOnce() -> PathBuf,
7205) -> Option<String> {
7206    let measure = if crate::build_target::isolated(config) {
7207        crate::disk::managed_free_bytes
7208    } else {
7209        crate::disk::free_bytes
7210    };
7211    disk_gate_with(repo, config, home, measure)
7212}
7213
7214/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
7215/// test can assert the exact wiring `attempt` runs - config's threshold in,
7216/// task-holding reason out - without asking the real machine's disk anything.
7217fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
7218    repo: &Path,
7219    config: &Config,
7220    home: impl FnOnce() -> PathBuf,
7221    free_bytes: F,
7222) -> Option<String> {
7223    let min = config.disk.min_free_bytes;
7224    if min == 0 {
7225        return None;
7226    }
7227    let output = match config.verify.build_cache {
7228        BuildCache::Shared => config.cache_dir(),
7229        BuildCache::Isolated => Some(home()),
7230    };
7231    let default_worktree_root;
7232    let worktree_root = match config.graph.worktree_root.as_deref() {
7233        Some(root) => root,
7234        None => {
7235            default_worktree_root = crate::run::default_worktree_root();
7236            &default_worktree_root
7237        }
7238    };
7239    for path in [Some(repo), output.as_deref(), Some(worktree_root)]
7240        .into_iter()
7241        .flatten()
7242    {
7243        let probe = if path == repo {
7244            path
7245        } else {
7246            path.ancestors().find(|p| p.exists()).unwrap_or(path)
7247        };
7248        let reason = match free_bytes(probe) {
7249            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
7250            Err(e) => Some(crate::disk::unmeasured_in(
7251                probe,
7252                &e,
7253                &config.graph.language,
7254            )),
7255        };
7256        if reason.is_some() {
7257            return reason;
7258        }
7259    }
7260    None
7261}
7262
7263/// How long to wait before offering another task when a run lost a seat to a
7264/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
7265/// could read, or carried nothing at all. Long enough that a quota outage
7266/// cannot burn through a whole backlog in the few seconds each doomed attempt
7267/// takes to fail; short enough that a quota which clears early is not left
7268/// idle for the fallback's sake.
7269const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
7270
7271/// Longest a parsed reset hint may push the wait out to. The hint comes from
7272/// the CLI's own words, not a contract, so a parsing slip that lands a day
7273/// away must not leave the loop asleep for a day.
7274const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
7275
7276/// How long [`poll`] should wait before offering the next task, after a run
7277/// lost at least one seat to a rate limit.
7278///
7279/// Pure and separate from the loop so the policy can be exercised without a
7280/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
7281/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
7282/// nothing to parse, or the parsed time has already passed; `cap` bounds how
7283/// far a parsed hint is trusted to push the wait out.
7284fn quota_wait(
7285    reset_at: Option<Timestamp>,
7286    now: Timestamp,
7287    fallback: Duration,
7288    cap: Duration,
7289) -> Duration {
7290    match reset_at {
7291        Some(at) if at > now => {
7292            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
7293            Duration::from_secs(secs).min(cap)
7294        }
7295        _ => fallback,
7296    }
7297}
7298
7299/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
7300///
7301/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
7302/// explains why parsing it exactly "would be a bug factory" — so this only
7303/// recognises the shapes actually observed in the wild, and returns `None`
7304/// for anything else rather than guess at a format nobody has seen.
7305///
7306/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
7307/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
7308/// said it, not from whenever this loop happens to read it: anchoring on `now`
7309/// would push the reset later on every read and would read an already-elapsed
7310/// reset as still in the future. (A long hint is still clamped by
7311/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
7312fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
7313    parse_reset_hint_zoned(text, now)
7314        .or_else(|| parse_reset_hint_dated(text))
7315        .or_else(|| parse_reset_hint_relative(text, recorded))
7316}
7317
7318/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
7319/// optional but at least one required, in that order. A bare number or any
7320/// unknown unit is refused.
7321fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
7322    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
7323    let mut rest = rest.trim();
7324    if rest.is_empty() {
7325        return None;
7326    }
7327    let mut total: i64 = 0;
7328    let mut matched = false;
7329    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
7330        if let Some((digits, tail)) = rest.split_once(unit)
7331            && !digits.is_empty()
7332            && digits.bytes().all(|b| b.is_ascii_digit())
7333        {
7334            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
7335            rest = tail;
7336            matched = true;
7337        }
7338    }
7339    if !rest.is_empty() || !matched {
7340        return None;
7341    }
7342    recorded
7343        .checked_add(jiff::SignedDuration::from_secs(total))
7344        .ok()
7345}
7346
7347/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
7348/// case-insensitive) into a 24-hour hour and minute. Shared by every
7349/// reset-hint shape below.
7350fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
7351    let clock = clock.trim().to_lowercase();
7352    let (digits, pm) = clock
7353        .strip_suffix("am")
7354        .map(|d| (d, false))
7355        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
7356    let (h, m) = digits.trim().split_once(':')?;
7357    let mut hour: i8 = h.trim().parse().ok()?;
7358    let minute: i8 = m.trim().parse().ok()?;
7359    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
7360        return None;
7361    }
7362    if pm && hour != 12 {
7363        hour += 12;
7364    } else if !pm && hour == 12 {
7365        hour = 0;
7366    }
7367    Some((hour, minute))
7368}
7369
7370/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
7371/// and a zone, never a date. A clock reading already past today is read as
7372/// tomorrow's: a CLI naming a same-day reset that has already gone by means
7373/// the window rolled over while nothing was watching.
7374fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
7375    let open = text.find('(')?;
7376    let close = text.rfind(')')?;
7377    if close <= open {
7378        return None;
7379    }
7380    let zone = text[open + 1..close].trim();
7381    let (hour, minute) = parse_12h_clock(&text[..open])?;
7382    let tz = jiff::tz::TimeZone::get(zone).ok()?;
7383    let candidate = now
7384        .to_zoned(tz)
7385        .with()
7386        .hour(hour)
7387        .minute(minute)
7388        .second(0)
7389        .millisecond(0)
7390        .microsecond(0)
7391        .nanosecond(0)
7392        .build()
7393        .ok()?;
7394    let mut at = candidate.timestamp();
7395    if at <= now {
7396        at += jiff::SignedDuration::from_hours(24);
7397    }
7398    Some(at)
7399}
7400
7401/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
7402/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
7403/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
7404/// "already past today" correction to make: the year already disambiguates
7405/// it. Scanned as a five-word window so it can be pulled out of the middle
7406/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
7407/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
7408/// any other timestamp with no zone attached.
7409fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
7410    let words: Vec<&str> = text.split_whitespace().collect();
7411    if words.len() < 5 {
7412        return None;
7413    }
7414    (0..=words.len() - 5)
7415        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
7416}
7417
7418/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
7419/// parenthesis right after the window is refused rather than ignored — it
7420/// reads as an explicit zone annotation on a shape that otherwise carries
7421/// none, and guessing UTC anyway would be exactly the silent misread this
7422/// module's parsing otherwise avoids.
7423fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
7424    if trailing.is_some_and(|next| next.starts_with('(')) {
7425        return None;
7426    }
7427    let month = month_number(window[0])?;
7428    let day_token = window[1].strip_suffix(',')?.to_lowercase();
7429    let day_digits = ["st", "nd", "rd", "th"]
7430        .iter()
7431        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
7432    let day: i8 = day_digits.parse().ok()?;
7433    let year_token = window[2];
7434    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
7435        return None;
7436    }
7437    let year: i16 = year_token.parse().ok()?;
7438    // The am/pm word carries the sentence's own trailing punctuation, e.g.
7439    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
7440    // reusing the same 12-hour clock reader the bracketed shape uses.
7441    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
7442    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
7443    let date = jiff::civil::Date::new(year, month, day).ok()?;
7444    let candidate = date
7445        .at(hour, minute, 0, 0)
7446        .to_zoned(jiff::tz::TimeZone::UTC)
7447        .ok()?;
7448    Some(candidate.timestamp())
7449}
7450
7451/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
7452/// case-insensitively, into a 1-based month number.
7453fn month_number(name: &str) -> Option<i8> {
7454    const NAMES: [&str; 12] = [
7455        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
7456    ];
7457    let lower = name.to_lowercase();
7458    NAMES
7459        .iter()
7460        .position(|n| *n == lower.as_str())
7461        .map(|i| i as i8 + 1)
7462}
7463
7464/// Test probe for the shared resume policy's review-budget exclusion.
7465#[cfg(test)]
7466fn exhausted_review_budget(state: &RunState) -> bool {
7467    // A run whose task-head publication failed has nothing left to review:
7468    // resuming it only retries the publication, so it is never "exhausted".
7469    !crate::handover::can_resume(state)
7470        && state.status == RunStatus::Blocked
7471        && !state.released()
7472        && state.retired_to.is_none()
7473}
7474
7475/// This task's *most recent* run, if resuming it would actually make
7476/// progress. `short` is only for the warning's own message.
7477///
7478/// Only ever `runs.last()` — never a search back through older history.
7479/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
7480/// mint, oldest first, and every entry before the last one was already
7481/// superseded at the moment it was minted: the daemon only ever starts a new
7482/// run when the previous one was not worth resuming (unresumable, exhausted,
7483/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
7484/// opens a fresh review-only run alongside an older, already-failed
7485/// competition. Searching further back would let an old run that merely
7486/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
7487/// behind, say — get resumed instead of the fresh competition
7488/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
7489/// nothing asked to revisit.
7490///
7491/// Two runs paid for the "prefer resuming over restarting" half of this
7492/// lesson, which is why this still checks `runs.last()` rather than always
7493/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
7494/// task a moment later, duplicating two and a half hours of agent work. Then
7495/// b25f stalled on a judge that timed out and one that answered with no JSON
7496/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
7497/// **one second** later, buying three fresh implementations to reach the
7498/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
7499/// the second case: a stall is terminal, and its cheap recovery re-asks only
7500/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
7501/// that is technically `resumable()` but provably cannot progress must not
7502/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
7503/// no-op instead of the fresh competition it promises.
7504///
7505/// A load failure is warned about rather than silently read as "not
7506/// resumable": the alternative is exactly what let a schema mismatch on run
7507/// `eba2` fall through to a full re-competition with nobody told why.
7508/// `crate::conduct` is what actually offers a better answer than
7509/// `Runner::start` here (see `Recovery::Review`), once this task's next
7510/// failure shows it up as `held`/`failed` with the run state unreadable.
7511fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
7512    unfinished_run_with(runs, short, RunState::load)
7513}
7514
7515/// [`unfinished_run`] with an injected state reader. Tests provide their
7516/// fixtures directly rather than touching the process-global run home.
7517pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
7518where
7519    F: FnMut(&str) -> Result<RunState>,
7520{
7521    let mut id = runs.last()?.clone();
7522    let mut visited = std::collections::BTreeSet::new();
7523    let mut repo = None;
7524    loop {
7525        if !runs.contains(&id) || !visited.insert(id.clone()) {
7526            tracing::warn!("invalid or cyclic recovery authority for task {short}");
7527            return None;
7528        }
7529        let state = match load(&id) {
7530            Ok(state) if state.id == id => state,
7531            Ok(_) => return None,
7532            Err(e) => {
7533                tracing::warn!("could not read run {id} for task {short}: {e:#}");
7534                return None;
7535            }
7536        };
7537        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
7538            return None;
7539        }
7540        repo = Some(state.repo.clone());
7541        if let Some(authority) = state.retired_to {
7542            id = authority;
7543            continue;
7544        }
7545        return (crate::handover::can_resume(&state)
7546            && state.liveness(false) != crate::run::Liveness::Live)
7547            .then_some(id);
7548    }
7549}
7550
7551/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
7552/// that [`attempt`] will resume it on its own?
7553///
7554/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
7555/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
7556/// injected reader like its sibling. An unreadable run is not awaiting
7557/// anything: it keeps going to the conductor as before.
7558fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
7559where
7560    F: FnOnce(&str) -> Result<RunState>,
7561{
7562    // `Failed` stays: a record an older build wrote for a parked run.
7563    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
7564        || task.fresh_start
7565        || task.review_branch.is_some()
7566    {
7567        return false;
7568    }
7569    let Some(id) = task.execution_runs().last() else {
7570        return false;
7571    };
7572    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
7573}
7574
7575/// Which of the three ways [`attempt`] can mint or continue a run this task
7576/// should use.
7577#[derive(Debug, Clone, PartialEq, Eq)]
7578enum Starter {
7579    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
7580    /// and that still exists.
7581    Review(String),
7582    /// `crate::graph::Runner::resume` on an unfinished run of this task.
7583    Resume(String),
7584    /// `crate::graph::Runner::start`: a fresh competition.
7585    Start,
7586}
7587
7588/// A second bound independent of inputs and the resettable failure counter.
7589/// Count execution and failed-startup recovery records once per run. Startup
7590/// failures can retain unrecorded preparation assets without an execution pass.
7591/// Unknown history is not evidence that a new set of worktrees is affordable.
7592fn retained_attempt_hold(
7593    task: &Task,
7594    starter: &Starter,
7595    limit: usize,
7596    mut load: impl FnMut(&str) -> Result<RunState>,
7597) -> Option<String> {
7598    if limit == 0 || matches!(starter, Starter::Resume(_)) {
7599        return None;
7600    }
7601    let mut retained = 0;
7602    for id in task
7603        .runs
7604        .iter()
7605        .chain(task.startup_failures.iter().map(|failure| &failure.run))
7606        .collect::<std::collections::BTreeSet<_>>()
7607    {
7608        let state = match load(id) {
7609            Ok(state) if state.id == *id => state,
7610            _ => {
7611                return Some(format!(
7612                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
7613                ));
7614            }
7615        };
7616        if state.retired_to.is_some() || state.released() {
7617            continue;
7618        }
7619        // Neither a completed status nor an empty candidate array proves that
7620        // all recovery sources (including unrecorded preparation) were retired.
7621        retained += 1;
7622    }
7623    (retained >= limit).then(|| format!(
7624        "[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."
7625    ))
7626}
7627
7628/// A selected public implementation overrides every historical candidate and pin.
7629fn selected_starter(
7630    selected: &crate::pr_recovery::Selection,
7631    previous: Option<&RunState>,
7632    unfinished: Option<&str>,
7633) -> Starter {
7634    if let Some(id) = unfinished
7635        && previous.is_some_and(|r| {
7636            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
7637        })
7638    {
7639        Starter::Resume(id.to_owned())
7640    } else {
7641        Starter::Review(selected.branch.clone())
7642    }
7643}
7644
7645/// The owner's answer to this branch's divergence question, consumed from the
7646/// task so a later, different divergence asks again. The runner applies it
7647/// (see `Runner::review_taking_over`), after the earlier worktree is released.
7648fn take_divergence_answer(
7649    branch: &str,
7650    remote: &str,
7651    task: &mut Task,
7652) -> Option<crate::reconcile::Choice> {
7653    let summary = crate::reconcile::summary_for(branch, remote);
7654    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
7655        (a.question == summary)
7656            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
7657            .flatten()
7658            .map(|c| (i, c))
7659    })?;
7660    task.answers.remove(idx);
7661    Some(choice)
7662}
7663
7664/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
7665/// this attempt should use. Pure, and separate from [`attempt`], so the
7666/// routing itself is assertable without spawning a real graph or a git
7667/// process: `attempt`'s own `crate::git::branch_exists` call has already
7668/// happened by the time this is called.
7669///
7670/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
7671/// whose branch is gone falls all the way through to [`Starter::Start`], not
7672/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
7673/// old (likely `Blocked`) run in the first place, and a branch that vanished
7674/// out from under that choice is not evidence resuming it would fare better.
7675fn choose_starter(
7676    review_branch: Option<&str>,
7677    branch_exists: bool,
7678    unfinished: Option<&str>,
7679) -> Starter {
7680    match review_branch {
7681        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
7682        Some(_) => Starter::Start,
7683        None => match unfinished {
7684            Some(id) => Starter::Resume(id.to_owned()),
7685            None => Starter::Start,
7686        },
7687    }
7688}
7689
7690/// Reuse a compatible latest review owner instead of taking its checked-out
7691/// branch into a new run. Different branches and changed criteria still use
7692/// the ordinary review/takeover policy.
7693fn review_retry_starter(
7694    task: &Task,
7695    previous: Option<&RunState>,
7696    branch: Option<&str>,
7697    exists: bool,
7698    unfinished: Option<&str>,
7699) -> Starter {
7700    if let Some(run) = previous
7701        && unfinished == Some(run.id.as_str())
7702        && run.reviewed_commits.is_some()
7703        && branch.is_some_and(|branch| {
7704            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
7705        })
7706        && may_resume_run(run, task)
7707    {
7708        return Starter::Resume(run.id.clone());
7709    }
7710    match (branch, unfinished, &task.review_of) {
7711        (None, None, Some(branch)) => Starter::Review(branch.clone()),
7712        _ => choose_starter(branch, exists, unfinished),
7713    }
7714}
7715
7716/// A retained review is valid only while its authored criteria still match.
7717fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
7718    task.review_branch
7719        .as_deref()
7720        .filter(|&branch| match &task.review_instruction {
7721            Some(authored) => *authored == task.instruction,
7722            // Legacy retained branches must agree with their prior run; only an
7723            // explicitly pinned review can proceed without recoverable provenance.
7724            None => previous.map_or_else(
7725                || task.review_of.as_deref() == Some(branch),
7726                |run| compatible_run_instruction(run, task),
7727            ),
7728        })
7729}
7730
7731/// A current explicit pin can select an otherwise incompatible run. Edits
7732/// and subsequent approvals invalidate pins selected for earlier criteria.
7733fn may_resume_run(run: &RunState, task: &Task) -> bool {
7734    if !task.assignment_accepts(run) {
7735        return false;
7736    }
7737    task.resume_override
7738        .as_ref()
7739        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
7740        || compatible_run_instruction(run, task)
7741}
7742
7743/// Review scaffolding is execution context, not evidence of an operator edit.
7744pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
7745    if let Some(authored) = &run.task_instruction {
7746        return compatible_instruction(authored, task);
7747    }
7748    if compatible_instruction(&run.instruction, task) {
7749        return true;
7750    }
7751    // Recognize only the existing generated review shapes on legacy runs.
7752    // Ordinary authored text with a similar heading is left intact.
7753    if run.reviewed_commits.is_some() {
7754        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
7755            return strip_answers_block(authored, task).trim() == task.instruction.trim();
7756        }
7757        if let Some(branch) = &task.review_of {
7758            let canonical = format!(
7759                "Review the branch `{branch}` (review-only: no implementation, no judging)."
7760            );
7761            let generated = format!(
7762                "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"
7763            );
7764            return task.instruction == canonical && run.instruction.starts_with(&generated);
7765        }
7766    }
7767    false
7768}
7769
7770/// Compare authored instructions, excluding answer blocks appended by the daemon.
7771pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
7772    strip_answers_block(old, task) == task.instruction
7773}
7774
7775/// Which repository a task runs in. A task that names none — the normal case
7776/// for one filed from a phone — runs in the daemon's own default.
7777fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
7778    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
7779        return fallback.to_path_buf();
7780    }
7781    task.repo.clone()
7782}
7783
7784/// The header [`append_answers`] appends operator answers under. Shared with
7785/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
7786/// rather than grown a new block on every resume.
7787const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
7788
7789/// Render the first `count` answers in the block appended to an instruction.
7790fn answers_block(task: &Task, count: usize) -> String {
7791    let mut s = ANSWERS_HEADER.to_owned();
7792    for a in &task.answers[..count] {
7793        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
7794    }
7795    s
7796}
7797
7798/// Render the approval independently of transient task state, so historical
7799/// suffixes remain recognizable after another explicit release.
7800fn resumption_block(r: &crate::queue::Resumption) -> String {
7801    format!(
7802        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
7803         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
7804        r.generation, r.at, r.instruction, r.answers_through,
7805    )
7806}
7807
7808/// Append audit answers and the latest explicit approval to the instruction.
7809fn append_answers(base: &str, task: &Task) -> String {
7810    let mut s = base.to_owned();
7811    if !task.answers.is_empty() {
7812        s.push_str(&answers_block(task, task.answers.len()));
7813    }
7814    if let Some(r) = &task.resumption {
7815        s.push_str(&resumption_block(r));
7816    }
7817    s
7818}
7819
7820/// Drop the prior answer block only when it is exactly the suffix this task
7821/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
7822/// the task author is ordinary instruction text, not a block to remove.
7823fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
7824    let mut instruction = instruction;
7825    for approval in task
7826        .resumption
7827        .iter()
7828        .chain(task.resumption_history.iter().rev())
7829    {
7830        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
7831            instruction = base;
7832            break;
7833        }
7834    }
7835    for count in (1..=task.answers.len()).rev() {
7836        let block = answers_block(task, count);
7837        if let Some(base) = instruction.strip_suffix(&block) {
7838            return base;
7839        }
7840    }
7841    instruction
7842}
7843
7844/// The instruction handed to `Runner::start`: the task's own text, plus any
7845/// operator answers `crate::conduct` collected for it (see
7846/// [`Task::answers`]), so a decision the operator actually made reaches the
7847/// implementers rather than only clearing the block that was waiting on it.
7848///
7849/// Appended rather than merged into [`Task::instruction`] itself, so the
7850/// task's own record stays exactly what its author wrote.
7851fn instruction_for(task: &Task) -> String {
7852    append_answers(&task.instruction, task)
7853}
7854
7855/// The instruction a resumed run should carry on with: whatever it already
7856/// had, refreshed with the task's *current* operator answers.
7857///
7858/// A resumable run's own `RunState::instruction` predates any answer
7859/// `crate::conduct` collects after the run parks, so resuming it unchanged —
7860/// the behaviour before this function existed — silently drops the very
7861/// decision the operator made to unblock it. Re-stripping any block this
7862/// function appended on an earlier resume before re-appending the current
7863/// list (rather than blindly appending again) is what keeps a task resumed
7864/// three times over three answered questions from carrying the same answer
7865/// three times.
7866fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
7867    append_answers(strip_answers_block(old_instruction, task), task)
7868}
7869
7870/// Preserve the producer's verified boundary and target, independent of prose.
7871fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
7872    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
7873    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
7874    if let Some(cause) = task.hold_notice_cause.as_mut() {
7875        cause.target = failure.map(|f| f.target.clone());
7876    }
7877}
7878
7879#[derive(Debug, thiserror::Error)]
7880#[error("attachment `{name}` is recorded on the task but {path} is missing")]
7881struct MissingAttachment {
7882    name: String,
7883    path: PathBuf,
7884}
7885
7886/// The task's attachments as absolute paths, each checked to still exist.
7887fn task_attachments(
7888    queue: &Queue,
7889    task: &Task,
7890) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
7891    let paths = queue.attachment_paths(task);
7892    for (name, path) in task.attachments.iter().zip(&paths) {
7893        if !path.is_file() {
7894            return Err(MissingAttachment {
7895                name: name.clone(),
7896                path: path.clone(),
7897            });
7898        }
7899    }
7900    Ok(paths)
7901}
7902
7903/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
7904/// answers before handing it to `Runner` — the actual boundary between
7905/// [`choose_starter`]'s routing and the graph, factored out so it is
7906/// assertable without a real repository, git branch, or agent CLI.
7907///
7908/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
7909/// instruction from the reviewed branch's own commit log because there is no
7910/// task statement to speak of for hand-written work, and splicing operator
7911/// answers into that text would contradict the very message it sends
7912/// reviewers ("there is no task statement").
7913fn prepare_instruction(
7914    starter: &Starter,
7915    old_instruction: Option<&str>,
7916    task: &Task,
7917) -> Option<String> {
7918    match starter {
7919        Starter::Start => Some(instruction_for(task)),
7920        Starter::Resume(_) => Some(resumed_instruction(
7921            old_instruction.expect("a resumed run always has a prior instruction"),
7922            task,
7923        )),
7924        Starter::Review(_) => None,
7925    }
7926}
7927
7928/// Persist a transition. A queue write failure is logged rather than fatal: the
7929/// run already happened, and taking the daemon down would only add a lost
7930/// backlog to a full disk.
7931fn record(queue: &Queue, task: &mut Task) {
7932    if let Err(e) = queue.put(task) {
7933        tracing::error!("could not record task {}: {e:#}", task.short());
7934        let notice = Notice::error(
7935            "loop:record",
7936            format!(
7937                "Task {} state could not be saved: {}. Check the disk.",
7938                task.id,
7939                e.to_string().lines().next().unwrap_or("unknown save error")
7940            ),
7941        )
7942        .link(Link::Task {
7943            id: task.id.clone(),
7944        });
7945        // The queue lives at `<home>/queue`, so its parent is the home.
7946        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
7947            Some(home) => notices::raise_in(home, notice),
7948            None => notices::raise(notice),
7949        }
7950    }
7951}
7952
7953/// Every runnable task, in the order the loop should try them.
7954///
7955/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
7956/// tail exists so that a claim somebody else holds costs the loop the next
7957/// candidate rather than a whole poll interval of idleness.
7958fn runnable(queue: &Queue) -> Vec<Task> {
7959    let mut tasks: Vec<Task> = queue
7960        .list()
7961        .into_iter()
7962        .filter(|t| t.status.runnable())
7963        .collect();
7964    tasks.sort_unstable_by(crate::queue::dispatch_order);
7965    tasks
7966}
7967
7968/// Why a run ended where it did, in one line, for [`Task::last_error`].
7969///
7970/// A stalled run names the seats the quota took out: "out of quota" is not
7971/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
7972/// agent to replace or which plan to top up.
7973///
7974/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
7975/// purpose: unlike `label`'s other callers (an internal log line, an
7976/// already-a-bug fallback message), this string becomes `Task::last_error`
7977/// verbatim, which the phone renders in the same alarm-styled box an
7978/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
7979/// `.err` styling. A bare `verified_noop` there would read exactly like the
7980/// failure this whole feature exists to tell apart from one.
7981fn describe(state: &RunState) -> String {
7982    let p = phrases(&state.config.graph.language);
7983    let mut detail = if state.status == RunStatus::Stalled {
7984        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
7985        seats.sort_unstable();
7986        seats.dedup();
7987        if seats.is_empty() {
7988            p.quorum_lost.to_owned()
7989        } else {
7990            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
7991        }
7992    } else {
7993        format!("{}{}", p.run_ended, state.status.display_label())
7994    };
7995    if let Some(cause) = state.verification_blocking_cause() {
7996        detail.push_str(&format!(" ({cause})"));
7997    } else if let Some(last) = state.events.last() {
7998        // The review loop's "never answered" stop is the one event worth
7999        // translating; it is recognised from structured state, not by
8000        // matching the English event text (which stays as recorded).
8001        let unanswered = state
8002            .reviews
8003            .last()
8004            .filter(|r| {
8005                state.status == RunStatus::Blocked
8006                    && last.node == "review"
8007                    && r.incomplete()
8008                    && r.blocking == 0
8009                    && r.round == state.config.graph.review_rounds
8010                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
8011            })
8012            .map(|r| (r.expected - r.answered, r.round));
8013        match unanswered {
8014            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
8015                detail.push_str(&format!(
8016                    " ({}: {})",
8017                    last.node,
8018                    (p.reviewers_never_answered)(missing, rounds)
8019                ));
8020            }
8021            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
8022        }
8023    }
8024    detail.push_str(&format!(" [run {}]", state.id));
8025    detail
8026}
8027
8028/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
8029///
8030/// The task file lives in the backlog indefinitely; a diagnostic is an
8031/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
8032/// stay small regardless of how much a gate command or a candidate printed.
8033const DIAGNOSTIC_MAX: usize = 4_000;
8034
8035/// Tail kept from a single failing command's output inside a diagnostic.
8036/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
8037/// pointer for a human deciding whether to go read the full artifact by hand,
8038/// not a replacement for reading it.
8039const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
8040
8041/// Assemble a bounded diagnostic excerpt from a held task's own run, so
8042/// `magi task show` says more than the one-line reason in [`describe`].
8043///
8044/// The one-liner answers "where did the run stop"; this answers "what would a
8045/// human have found opening `artifacts/` by hand" — the point of the whole
8046/// feature is the case that one-liner actively misleads on: a run held as "no
8047/// candidate produced a change" can mean the implementer actually finished
8048/// the task (opened a PR, merged it, tagged a release) and only left a clean
8049/// local worktree behind, which reads as "nothing happened" unless someone
8050/// goes and reads what the agent actually said. `None` when the run carries
8051/// none of the three shapes this recognises — an ordinary run held for
8052/// something not diagnosable from `RunState` alone still explains itself
8053/// through `Task::last_error`.
8054pub(crate) fn diagnostic_for(state: &RunState) -> Option<String> {
8055    diagnostic(state)
8056}
8057
8058fn diagnostic(state: &RunState) -> Option<String> {
8059    let mut parts: Vec<String> = Vec::new();
8060
8061    if let Some(e2e) = &state.head_e2e
8062        && !e2e.passed
8063    {
8064        for o in e2e
8065            .outcomes
8066            .iter()
8067            .filter(|o| !o.ok() && !o.resource_blocked)
8068        {
8069            parts.push(format!(
8070                "head_e2e `{}` failed on {} ({}):\n{}",
8071                o.command,
8072                e2e.head.chars().take(7).collect::<String>(),
8073                notices::exit_status(o.code),
8074                crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
8075            ));
8076        }
8077    }
8078
8079    // Gate failure: which check(s), and the tail of what each printed.
8080    for o in state.gate.iter().filter(|o| !o.ok()) {
8081        parts.push(format!(
8082            "gate `{}` failed ({}):\n{}",
8083            o.command,
8084            notices::exit_status(o.code),
8085            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
8086        ));
8087    }
8088
8089    // The land loop gave up because the fixer declined while checks were
8090    // still red: the message already names them (see `land::run`).
8091    if let Some(last) = state
8092        .events
8093        .iter()
8094        .rev()
8095        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
8096    {
8097        parts.push(last.message.clone());
8098    }
8099
8100    // No viable candidate: every implementer's own final word, sanitized the
8101    // same way a judge would have read it, so a run that actually finished
8102    // the job does not read as an unexplained failure. A verified no-op is
8103    // called out ahead of its own summary and apart from an ordinary
8104    // failure's `why` — this is the one candidate shape whose diagnostic a
8105    // human is expected to actually judge, not just skim.
8106    if state.viable().is_empty() {
8107        for c in &state.candidates {
8108            if c.has_valid_verified_noop()
8109                && let Some(evidence) = c.verified_noop_display()
8110            {
8111                parts.push(format!(
8112                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
8113                    c.label
8114                ));
8115            } else if !c.summary.trim().is_empty() {
8116                if let Some(why) = &c.failed {
8117                    parts.push(format!(
8118                        "candidate {} ({why}): {}",
8119                        c.label,
8120                        c.summary.trim()
8121                    ));
8122                } else {
8123                    parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
8124                }
8125            } else if let Some(why) = &c.failed {
8126                parts.push(format!("candidate {}: {why}", c.label));
8127            }
8128        }
8129    }
8130
8131    if parts.is_empty() {
8132        return None;
8133    }
8134    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
8135    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
8136    // back slightly over. Leave it enough room to always land under the
8137    // limit.
8138    Some(crate::run::tail(
8139        &parts.join("\n\n"),
8140        DIAGNOSTIC_MAX.saturating_sub(100),
8141    ))
8142}
8143
8144/// Stable lower-case name for a run status, for an internal log line and the
8145/// "graph stopped without reaching a terminal status" bug message in
8146/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
8147/// doc for why that one reads [`RunStatus::display_label`] instead. One
8148/// definition of a status's name, on the type that owns it: this table used
8149/// to live here as a second copy, and a status renamed in one place would
8150/// have gone on reading correctly in the other.
8151fn label(status: RunStatus) -> &'static str {
8152    status.as_str()
8153}
8154
8155/// Parse a merge mode override.
8156pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
8157    match mode {
8158        "none" => Ok(MergeMode::None),
8159        "local" => Ok(MergeMode::Local),
8160        "pr" => Ok(MergeMode::Pr),
8161        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
8162    }
8163}
8164
8165/// Take the status lock, recovering from a poisoned one.
8166///
8167/// A panic elsewhere must not silently stop the heartbeat: the status is plain
8168/// data, and the worst a poisoned lock can hold is a stale timestamp.
8169fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
8170    mutex
8171        .lock()
8172        .unwrap_or_else(std::sync::PoisonError::into_inner)
8173}
8174
8175#[cfg(test)]
8176mod tests {
8177    use super::*;
8178    use crate::queue::{Source, TaskStatus};
8179    use crate::run::{Candidate, CommandOutcome};
8180    use pretty_assertions::assert_eq;
8181
8182    fn task() -> Task {
8183        Task::new(
8184            "add retries".to_owned(),
8185            "add retries".to_owned(),
8186            PathBuf::from("/repo"),
8187            Source::Human,
8188        )
8189    }
8190
8191    #[test]
8192    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
8193        let skips = DispatchSkips::from([
8194            ("a".into(), SkipReason::CoolingDown),
8195            ("b".into(), SkipReason::WaitingOnLanding),
8196            ("c".into(), SkipReason::WaitingOnLanding),
8197            ("d".into(), SkipReason::OrdinaryCapacity),
8198        ]);
8199        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
8200        assert_eq!(wait.runnable, 4);
8201        assert_eq!(
8202            wait.reasons
8203                .iter()
8204                .map(|r| (r.reason.as_str(), r.count))
8205                .collect::<Vec<_>>(),
8206            [
8207                ("waiting_on_landing", 2),
8208                ("cooling_down", 1),
8209                ("ordinary_capacity", 1)
8210            ]
8211        );
8212        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
8213        assert!(
8214            aggregate_dispatch_wait(2, &DispatchSkips::new())
8215                .unwrap()
8216                .reasons
8217                .is_empty()
8218        );
8219    }
8220
8221    #[test]
8222    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
8223        let before = vec!["a".into(), "b".into(), "c".into()];
8224        let allowed = vec![task_with_id("b")];
8225        let skips = interrupt_skips(&before, &allowed);
8226        assert_eq!(
8227            skips,
8228            DispatchSkips::from([
8229                ("a".into(), SkipReason::InterruptGate),
8230                ("c".into(), SkipReason::InterruptGate),
8231            ])
8232        );
8233        let mut previous = DispatchSkips::new();
8234        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
8235        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
8236        assert!(!changed_dispatch_skips(&mut previous, skips));
8237        assert!(changed_dispatch_skips(
8238            &mut previous,
8239            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
8240        ));
8241        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
8242    }
8243
8244    #[test]
8245    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
8246        let mut value = serde_json::to_value(Status::new()).unwrap();
8247        value.as_object_mut().unwrap().remove("dispatch_wait");
8248        assert!(
8249            serde_json::from_value::<Status>(value.clone())
8250                .unwrap()
8251                .dispatch_wait
8252                .is_none()
8253        );
8254        assert!(
8255            serde_json::from_value::<Reading>(value.clone())
8256                .unwrap()
8257                .dispatch_wait
8258                .is_none()
8259        );
8260        value["dispatch_wait"] = serde_json::json!({
8261            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
8262        });
8263        let reading = serde_json::from_value::<Reading>(value).unwrap();
8264        assert_eq!(
8265            reading.dispatch_wait.unwrap().reasons[0].reason,
8266            "future_reason"
8267        );
8268    }
8269
8270    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
8271        let job = crate::worker::Job {
8272            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
8273            sequence: 1,
8274            kind: "task".into(),
8275            key: format!("task:{}", request.task),
8276            payload: serde_json::to_value(request).unwrap(),
8277            generation: "a".repeat(64),
8278            version: None,
8279            status: crate::worker::Status::Starting,
8280            result: None,
8281            pid: None,
8282            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
8283            finished_at: None,
8284        };
8285        let dir = home.join("workers/jobs").join(&job.id);
8286        std::fs::create_dir_all(&dir).unwrap();
8287        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
8288        job
8289    }
8290
8291    #[test]
8292    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
8293        let home = tempfile::tempdir().unwrap();
8294        let request = TaskWorker {
8295            opts: Opts::default(),
8296            queue: home.path().join("queue"),
8297            task: "startup".into(),
8298            lane: PermitKind::Ordinary,
8299            standalone: false,
8300        };
8301        let job = starting_task_reservation(home.path(), &request);
8302        let error = task_worker_spawn_error(
8303            home.path(),
8304            &request,
8305            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
8306        )
8307        .expect_err("our own reservation must not turn a failed spawn into a resync");
8308        let active = crate::worker::active(home.path()).unwrap();
8309        assert_eq!(active.len(), 1);
8310        assert_eq!(active[0].id, job.id);
8311        assert_eq!(active[0].status, crate::worker::Status::Starting);
8312        assert!(
8313            crate::worker::control(home.path(), &job.key)
8314                .unwrap()
8315                .is_none()
8316        );
8317        let notices = notices::Notices::at(home.path().join("notifications")).list();
8318        assert_eq!(notices.len(), 1);
8319        assert_eq!(notices[0].key, "loop:worker-startup");
8320        assert!(!notices[0].message.contains("private-error-detail"));
8321        assert!(notices[0].message.contains(&request.task));
8322        assert!(
8323            notices[0]
8324                .message
8325                .contains("could not be started or acknowledged")
8326        );
8327        assert!(notices[0].message.contains("worker.log"));
8328        assert_eq!(
8329            notices[0].link,
8330            Some(Link::Task {
8331                id: request.task.clone()
8332            })
8333        );
8334        assert!(format!("{error:#}").contains("private-error-detail"));
8335    }
8336
8337    #[test]
8338    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
8339        let home = tempfile::tempdir().unwrap();
8340        let mut request = TaskWorker {
8341            opts: Opts::default(),
8342            queue: home.path().join("queue"),
8343            task: "handoff".into(),
8344            lane: PermitKind::Ordinary,
8345            standalone: true,
8346        };
8347        let job = starting_task_reservation(home.path(), &request);
8348        request.standalone = false;
8349        task_worker_spawn_error(
8350            home.path(),
8351            &request,
8352            anyhow::anyhow!("operation key is already reserved for a different request"),
8353        )
8354        .expect("a different standalone request is the handoff race, not our startup failure");
8355        let active = crate::worker::active(home.path()).unwrap();
8356        assert_eq!(active.len(), 1);
8357        assert_eq!(active[0].id, job.id);
8358        assert_eq!(active[0].payload, job.payload);
8359        assert!(
8360            notices::Notices::at(home.path().join("notifications"))
8361                .list()
8362                .is_empty()
8363        );
8364    }
8365
8366    #[test]
8367    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
8368        let home = tempfile::tempdir().unwrap();
8369        let queue = Queue::at(home.path().join("queue"));
8370        let mut task = task();
8371        task.runs = vec!["previous".into()];
8372        queue.put(&mut task).unwrap();
8373        let request = TaskWorker {
8374            opts: Opts::default(),
8375            queue: home.path().join("queue"),
8376            task: task.id.clone(),
8377            lane: PermitKind::Ordinary,
8378            standalone: false,
8379        };
8380        let job = starting_task_reservation(home.path(), &request);
8381        let claims = current_work(home.path(), Timestamp::now());
8382        assert_eq!(claims.len(), 1);
8383        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
8384        assert_eq!(claims[0].run, "previous");
8385        assert!(other_claims_run(&claims, "previous", None));
8386        // Only after confirming the executing caller may admission ignore
8387        // this exact projection. Cleanup continues to observe it as live.
8388        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
8389        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
8390    }
8391
8392    #[test]
8393    fn admission_excludes_only_the_callers_exact_reservation() {
8394        let own = Current {
8395            worker: Some("own".into()),
8396            task: "same-task".into(),
8397            run: "previous".into(),
8398        };
8399        assert!(!other_claims_run(
8400            std::slice::from_ref(&own),
8401            "previous",
8402            Some("own")
8403        ));
8404        assert!(other_claims_run(
8405            std::slice::from_ref(&own),
8406            "previous",
8407            None
8408        ));
8409        for worker in [None, Some("other".into())] {
8410            let other = Current {
8411                worker,
8412                ..own.clone()
8413            };
8414            assert!(other_claims_run(
8415                &[own.clone(), other],
8416                "previous",
8417                Some("own")
8418            ));
8419        }
8420        let legacy: Current =
8421            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
8422        assert!(other_claims_run(&[legacy], "previous", Some("own")));
8423    }
8424
8425    #[test]
8426    fn os_leased_task_worker_survives_wall_clock_advance() {
8427        let home = tempfile::tempdir().unwrap();
8428        let queue = Queue::at(home.path().join("queue"));
8429        let mut task = task();
8430        let run = "20260903-100000-abcd";
8431        task.start(run.into());
8432        queue.put(&mut task).unwrap();
8433        let mut worker = live_task_fixture(home.path(), &task.id).unwrap();
8434        let future = Timestamp::now() + jiff::SignedDuration::from_secs(3600);
8435        assert!(
8436            current_work(home.path(), future)
8437                .iter()
8438                .any(
8439                    |claim| claim.worker.as_deref() == Some(worker.job.id.as_str())
8440                        && claim.run == run
8441                )
8442        );
8443        worker.release_lease();
8444        assert!(worker.dir.join("job.json").is_file());
8445        assert!(!is_working_on(home.path(), run, future));
8446        let dir = worker.dir.clone();
8447        drop(worker);
8448        assert!(!dir.exists());
8449    }
8450
8451    #[test]
8452    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
8453        let mut task = task();
8454        let mut run = run_state(RunStatus::Reviewing);
8455        run.task_instruction = Some(task.instruction.clone());
8456        run.reviewed_commits = Some(vec!["committed-fix".into()]);
8457        let branch = "magi/test/B";
8458        run.candidates.push(crate::run::Candidate {
8459            branch: branch.into(),
8460            ..candidate('B', "preserved work", false, None)
8461        });
8462        task.runs = vec![run.id.clone()];
8463        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
8464        assert_eq!(
8465            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
8466            Starter::Resume(run.id.clone())
8467        );
8468        assert!(matches!(
8469            review_retry_starter(
8470                &task,
8471                Some(&run),
8472                Some("different"),
8473                true,
8474                unfinished.as_deref()
8475            ),
8476            Starter::Review(_)
8477        ));
8478        assert_eq!(
8479            review_retry_starter(
8480                &task,
8481                Some(&run),
8482                Some(branch),
8483                false,
8484                unfinished.as_deref()
8485            ),
8486            Starter::Start
8487        );
8488        task.instruction.push_str(" changed criteria");
8489        assert!(matches!(
8490            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
8491            Starter::Review(_)
8492        ));
8493        assert!(matches!(
8494            review_retry_starter(&task, Some(&run), Some(branch), true, None),
8495            Starter::Review(_)
8496        ));
8497    }
8498
8499    #[test]
8500    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
8501        let dir = tempfile::tempdir().unwrap();
8502        let queue = Queue::at(dir.path().join("queue"));
8503        let mut task = task();
8504        task.status = TaskStatus::Running;
8505        task.attempts = 1;
8506        queue.put(&mut task).unwrap();
8507        let live = std::collections::BTreeSet::from([task.id.clone()]);
8508        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
8509        drop(queue.claim(&task.id).unwrap());
8510        let saved = queue.get(&task.id).unwrap();
8511        assert_eq!(saved.status, TaskStatus::Running);
8512        assert_eq!(saved.attempts, 1);
8513        assert!(saved.last_error.is_none());
8514    }
8515
8516    #[test]
8517    fn standalone_workers_do_not_consume_scheduler_lanes() {
8518        let request = |task: &str, lane, standalone| TaskWorker {
8519            opts: Opts::default(),
8520            queue: PathBuf::from("/queue"),
8521            task: task.to_owned(),
8522            lane,
8523            standalone,
8524        };
8525        let mut jobs = vec![
8526            request("ordinary", PermitKind::Ordinary, false),
8527            request("standalone-urgent", PermitKind::Urgent, true),
8528            request("standalone-ordinary", PermitKind::Ordinary, true),
8529            request("decision", PermitKind::None, false),
8530        ];
8531        assert_eq!(available_slots(&jobs, 2), (1, 1));
8532        jobs.push(request("urgent", PermitKind::Urgent, false));
8533        assert_eq!(available_slots(&jobs, 2), (1, 0));
8534        assert_eq!(available_slots(&jobs, 0), (0, 0));
8535    }
8536
8537    #[test]
8538    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
8539        let now = Timestamp::now();
8540        let mut reading = Reading {
8541            pid: Some(std::process::id()),
8542            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
8543            ..Reading::default()
8544        };
8545        assert!(!reading.running(now));
8546        assert!(legacy_scheduler_running(&reading, now, 0));
8547        reading.worker_protocol = Some(1);
8548        assert!(!legacy_scheduler_running(&reading, now, 0));
8549    }
8550
8551    #[test]
8552    fn selected_public_head_overrides_historical_resume_and_pin() {
8553        let mut t = task();
8554        let mut old = run_state(RunStatus::Blocked);
8555        let selection = crate::pr_recovery::Selection {
8556            url: "url".into(),
8557            branch: format!("magi/task-{}", t.id),
8558            head: "a".repeat(40),
8559            source_head: None,
8560            source_run: None,
8561            source_proof: None,
8562            disposition: Some(crate::pr_recovery::Disposition::Review),
8563            instruction: t.instruction.clone(),
8564            approved_at: Timestamp::now(),
8565        };
8566        t.resume_override = Some(crate::queue::OperatorResume {
8567            pinned_run: Some(old.id.clone()),
8568            question_id: "choice".into(),
8569            at: Timestamp::now(),
8570            conductor_rehold: None,
8571            forced: false,
8572        });
8573        assert_eq!(
8574            selected_starter(&selection, Some(&old), Some(&old.id)),
8575            Starter::Review(selection.branch.clone())
8576        );
8577        old.pr_recovery = Some(selection.clone());
8578        assert_eq!(
8579            selected_starter(&selection, Some(&old), Some(&old.id)),
8580            Starter::Review(selection.branch.clone())
8581        );
8582        old.reviewed_commits = Some(vec!["implementation".into()]);
8583        assert_eq!(
8584            selected_starter(&selection, Some(&old), Some(&old.id)),
8585            Starter::Resume(old.id.clone())
8586        );
8587        let mut changed = selection.clone();
8588        changed.head = "b".repeat(40);
8589        assert_eq!(
8590            selected_starter(&changed, Some(&old), Some(&old.id)),
8591            Starter::Review(changed.branch)
8592        );
8593    }
8594
8595    #[test]
8596    fn candidate_transplant_failure_is_one_actionable_hold() {
8597        let dir = tempfile::tempdir().unwrap();
8598        let q = Queue::at(dir.path().join("queue"));
8599        let mut t = task();
8600        let mut state = run_state(RunStatus::Blocked);
8601        state.event("prep", "cannot apply referenced commit: conflict");
8602        state.prep_failure = Some("conflict".into());
8603        t.start(state.id.clone());
8604        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
8605        assert_eq!(t.attempts, 1);
8606        assert_eq!(t.status, TaskStatus::Held);
8607        assert!(t.operator_held());
8608        assert!(!t.status.runnable());
8609        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
8610        let first = t.chat_notice_key().unwrap();
8611        t.chat_notices.push(first.clone());
8612        t.release_operator("test", None);
8613        state.id = "another-unprepared-run".into();
8614        t.start(state.id.clone());
8615        finish_attempt(
8616            3,
8617            &q,
8618            &mut t,
8619            &state,
8620            &[],
8621            Err(anyhow::anyhow!("still conflicts")),
8622        );
8623        assert_eq!(
8624            t.chat_notice_key().as_ref(),
8625            Some(&first),
8626            "no work happened"
8627        );
8628        t.release_operator("test", None);
8629        state.prep_failure = None;
8630        state.status = RunStatus::Failed;
8631        state.begin_pass();
8632        t.start(state.id.clone());
8633        finish_attempt(
8634            1,
8635            &q,
8636            &mut t,
8637            &state,
8638            &[],
8639            Err(anyhow::anyhow!("new gate failure")),
8640        );
8641        let failure = t.chat_notice_key().unwrap();
8642        assert_ne!(failure, first, "approved recovery reached a real failure");
8643        t.release_operator("test", None);
8644        state.begin_pass();
8645        t.start(state.id.clone());
8646        finish_attempt(
8647            1,
8648            &q,
8649            &mut t,
8650            &state,
8651            &[],
8652            Err(anyhow::anyhow!("new failure on resume")),
8653        );
8654        assert_ne!(
8655            t.chat_notice_key().as_ref(),
8656            Some(&failure),
8657            "a new settled pass"
8658        );
8659    }
8660
8661    #[test]
8662    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
8663        for source in ["cli", "web"] {
8664            let mut t = task();
8665            let mut run = run_state(RunStatus::Blocked);
8666            run.instruction = "Run A original criteria".into();
8667            run.task_instruction = Some(run.instruction.clone());
8668            t.start(run.id.clone());
8669            t.release_operator("choice", Some("resume-question"));
8670            t.resume_override = Some(crate::queue::OperatorResume {
8671                question_id: "resume-question".into(),
8672                at: Timestamp::now(),
8673                conductor_rehold: None,
8674                forced: true,
8675                pinned_run: Some(run.id.clone()),
8676            });
8677            t.hold_machine(Some("not enough free space to start a run".into()));
8678            let mut unchanged = t.clone();
8679            unchanged
8680                .edit("title changed".into(), unchanged.instruction.clone())
8681                .unwrap();
8682            unchanged.release_operator(source, None);
8683            assert_eq!(
8684                unchanged
8685                    .resume_override
8686                    .as_ref()
8687                    .unwrap()
8688                    .pinned_run
8689                    .as_deref(),
8690                Some(run.id.as_str())
8691            );
8692            assert!(!compatible_run_instruction(&run, &unchanged));
8693            assert!(may_resume_run(&run, &unchanged));
8694
8695            t.edit(
8696                "approved recovery".into(),
8697                "Reuse measured PR head B; fix Clippy; review".into(),
8698            )
8699            .unwrap();
8700            assert!(t.resume_override.is_none());
8701            t.release_operator(source, None);
8702            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
8703            assert!(reloaded.resume_override.is_none());
8704            assert!(!may_resume_run(&run, &reloaded));
8705            let unfinished =
8706                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
8707                    .filter(|_| may_resume_run(&run, &reloaded));
8708            assert_eq!(
8709                choose_starter(None, false, unfinished.as_deref()),
8710                Starter::Start
8711            );
8712            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
8713            assert_eq!(
8714                reloaded.resumption_history[0].question_id.as_deref(),
8715                Some("resume-question")
8716            );
8717
8718            // A revision already persisted with the old approval/pin is also
8719            // invalidated when the new operator release is recorded.
8720            unchanged.instruction = "Reuse measured PR head B".into();
8721            unchanged.hold_machine(Some("disk hold".into()));
8722            unchanged.release_operator(source, None);
8723            assert!(unchanged.resume_override.is_none());
8724            assert!(!may_resume_run(&run, &unchanged));
8725        }
8726    }
8727
8728    #[test]
8729    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
8730        let mut t = task();
8731        let mut run = run_state(RunStatus::Blocked);
8732        t.review_of = Some("approved-head".into());
8733        t.instruction =
8734            "Review the branch `approved-head` (review-only: no implementation, no judging)."
8735                .into();
8736        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();
8737        run.reviewed_commits = Some(vec!["Commit log".into()]);
8738        t.start(run.id.clone());
8739        t.hold_machine(Some("interrupted review".into()));
8740        t.release_operator("cli", None);
8741        assert!(
8742            compatible_run_instruction(&run, &t),
8743            "legacy explicit review remains resumable"
8744        );
8745        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
8746            .filter(|_| compatible_run_instruction(&run, &t));
8747        assert_eq!(
8748            choose_starter(None, false, unfinished.as_deref()),
8749            Starter::Resume(run.id.clone())
8750        );
8751        run.task_instruction = Some(t.instruction.clone());
8752        assert!(compatible_run_instruction(&run, &t));
8753        let reloaded: RunState =
8754            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
8755        assert!(compatible_run_instruction(&reloaded, &t));
8756        t.edit(
8757            "new approved head".into(),
8758            "Reuse measured PR head B".into(),
8759        )
8760        .unwrap();
8761        assert!(!compatible_run_instruction(&run, &t));
8762
8763        // Legacy recovery reviews retain the task criteria ahead of the log.
8764        t.review_of = None;
8765        t.instruction = "Fix Clippy on approved head".into();
8766        run.task_instruction = None;
8767        run.instruction = format!(
8768            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
8769            t.instruction
8770        );
8771        assert!(compatible_run_instruction(&run, &t));
8772        t.instruction.push('\n');
8773        assert!(
8774            compatible_run_instruction(&run, &t),
8775            "legacy generated review trimmed the original criteria"
8776        );
8777        t.hold_for_handover(Some("approved-head".into()), "refused".into());
8778        assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
8779        t.edit("new plan".into(), "Reuse measured PR head B".into())
8780            .unwrap();
8781        assert!(review_branch_for(&t, Some(&run)).is_none());
8782        assert!(!compatible_run_instruction(&run, &t));
8783        t.review_branch = Some("approved-head".into());
8784        t.review_instruction = None;
8785        assert!(
8786            review_branch_for(&t, Some(&run)).is_none(),
8787            "legacy retained candidate cannot replace a revised approved head"
8788        );
8789    }
8790
8791    #[test]
8792    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
8793        let home = crate::run::test_home();
8794        crate::run::pin_test_home();
8795        let dir = tempfile::tempdir().unwrap();
8796        let queue = Queue::at(dir.path().join("queue"));
8797        for resume in [true, false] {
8798            let state = run_state(RunStatus::Blocked);
8799            let mut t = task();
8800            t.start(state.id.clone());
8801            let action = if resume {
8802                ask::ChoiceAction::Resume {
8803                    run: state.id.clone(),
8804                }
8805            } else {
8806                ask::ChoiceAction::Requeue
8807            };
8808            let mut q = action_question(&state.id, action);
8809            q.status = ask::QuestionStatus::Open;
8810            q.answer = None;
8811            q.answered_at = None;
8812            t.fail("run stopped with a question", 3);
8813            hold_if_runnable(&queue, &mut t);
8814            assert!(t.operator_decided_at.is_none());
8815            assert!(t.operator_held());
8816            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
8817            let expected = if resume {
8818                ActionDecision::Resume(state.id.clone())
8819            } else {
8820                ActionDecision::Requeue
8821            };
8822            assert_eq!(
8823                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
8824                expected
8825            );
8826            t.hold_manual(Some("later explicit hold".into()));
8827            assert_eq!(
8828                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
8829                ActionDecision::Stale
8830            );
8831        }
8832    }
8833
8834    #[test]
8835    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
8836        let mut t = task();
8837        t.answers.push(crate::queue::AnsweredQuestion {
8838            question: "Inspect the remote?".into(),
8839            answer: "Inspect then wait".into(),
8840        });
8841        let old = instruction_for(&t);
8842        assert!(compatible_instruction(&old, &t));
8843        t.instruction = "Reuse approved PR head and review".into();
8844        t.release_operator("cli", None);
8845        assert!(!compatible_instruction(&old, &t));
8846        let approved = instruction_for(&t);
8847        assert!(approved.contains("waiting premises are superseded"));
8848        assert!(compatible_instruction(&approved, &t));
8849        assert_eq!(resumed_instruction(&approved, &t), approved);
8850        t.release_operator("web", None);
8851        assert!(compatible_instruction(&approved, &t));
8852        assert_eq!(t.resumption_history.len(), 1);
8853        t.start("run".into());
8854        assert!(instruction_for(&t).contains("Explicit operator resumption"));
8855    }
8856
8857    /// A run that stopped on an infrastructure wait asked no agent anything:
8858    /// the task is held by the machine under a `[resource]` reason (resumable,
8859    /// re-checked by triage), and the attempt it started is given back.
8860    #[test]
8861    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
8862        let mut state = RunState::new(
8863            PathBuf::from("/repo"),
8864            "main".into(),
8865            "base".into(),
8866            "task".into(),
8867            Config::default(),
8868        );
8869        state.status = RunStatus::Landing;
8870        state.parked = true;
8871        state.pr_pushed_head = Some("head".into());
8872        state.land_unrelated = Some(
8873            serde_json::from_value(serde_json::json!({
8874                "head": "head", "question": "ci-question",
8875                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
8876            }))
8877            .unwrap(),
8878        );
8879        let mut t = task();
8880        t.start(state.id.clone());
8881        let verdict = Verdict {
8882            status: RunStatus::Landing,
8883            left_pr: true,
8884            quota_hit: false,
8885            parked: true,
8886            no_viable_candidates: false,
8887        };
8888        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
8889        assert_eq!(t.attempts, 0);
8890        assert_eq!(t.status, TaskStatus::Held);
8891        assert!(!t.operator_held());
8892        assert!(
8893            t.hold_reason
8894                .as_deref()
8895                .unwrap()
8896                .starts_with("[ci-unrelated]")
8897        );
8898        // A second settlement must not refund an earlier task attempt.
8899        t.attempts = 1;
8900        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
8901        assert_eq!(t.attempts, 1);
8902        assert_eq!(t.passes.len(), 1);
8903        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8904        state.pr_pushed_head = Some("new-head".into());
8905        state.parked = false;
8906        state.status = RunStatus::Blocked;
8907        let stale = Verdict {
8908            status: RunStatus::Blocked,
8909            parked: false,
8910            ..verdict
8911        };
8912        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
8913        assert_eq!(t.attempts, 1);
8914        // A new execution pass can refund its own newly charged attempt.
8915        state.begin_pass();
8916        state.begin_pass();
8917        state.status = RunStatus::Landing;
8918        state.parked = true;
8919        state.pr_pushed_head = Some("head".into());
8920        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
8921        assert_eq!(t.attempts, 0);
8922        assert_eq!(t.passes.len(), 2);
8923    }
8924
8925    #[test]
8926    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
8927        let mut state = run_state(RunStatus::Failed);
8928        state
8929            .quota
8930            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
8931        state.begin_pass();
8932        let mut t = task();
8933        t.start(state.id.clone());
8934        reclaim(&mut t, Some(state), 2, "en");
8935        assert_eq!(t.attempts, 1);
8936    }
8937
8938    #[test]
8939    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
8940        let mut state = run_state(RunStatus::Blocked);
8941        let losses: Vec<_> = ["alpha", "beta"]
8942            .into_iter()
8943            .enumerate()
8944            .map(|(i, agent)| {
8945                QuotaLoss::from_report(
8946                    format!("advisor-{i}"),
8947                    "advise",
8948                    Some(&crate::agent::Quota {
8949                        cause: crate::agent::QuotaCause::Authentication,
8950                        agent: agent.to_owned(),
8951                        reset: None,
8952                    }),
8953                )
8954            })
8955            .collect();
8956        crate::graph::block_machine_outage(&mut state, "advise", &losses);
8957        state.quota = losses;
8958        let mut t = task();
8959        t.start(state.id.clone());
8960        let verdict = Verdict {
8961            status: state.status,
8962            left_pr: false,
8963            quota_hit: true,
8964            parked: false,
8965            no_viable_candidates: true,
8966        };
8967        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
8968        assert_eq!(t.attempts, 0);
8969        assert_eq!(t.status, TaskStatus::Held);
8970        assert!(!t.operator_held());
8971        let reason = t.hold_reason.as_deref().unwrap();
8972        assert!(reason.starts_with("[authentication]"));
8973        assert!(
8974            reason.contains("alpha")
8975                && reason.contains("beta")
8976                && reason.contains("re-authenticate")
8977        );
8978        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
8979        // Orphan recovery uses the same settlement and cannot spend an attempt.
8980        let mut orphan = task();
8981        orphan.start(state.id.clone());
8982        reclaim(&mut orphan, Some(state), 2, "en");
8983        assert_eq!(orphan.attempts, 0);
8984        assert_eq!(orphan.status, TaskStatus::Held);
8985    }
8986
8987    #[test]
8988    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
8989        let mut state = RunState::new(
8990            PathBuf::from("/repo"),
8991            "main".to_owned(),
8992            "abc1234".to_owned(),
8993            "task".to_owned(),
8994            Config::default(),
8995        );
8996        state.status = RunStatus::Blocked;
8997        state.resource_block = Some(crate::run::ResourceBlock {
8998            cause: crate::run::ResourceBlockCause::Other,
8999            node: "graft".to_owned(),
9000            kind: "shared build cache".to_owned(),
9001            detail: "timed out".to_owned(),
9002            at: jiff::Timestamp::now(),
9003        });
9004        let mut t = task();
9005        t.start("20260902-000000-aaaa".to_owned());
9006        assert_eq!(t.attempts, 1);
9007        let verdict = Verdict {
9008            status: RunStatus::Blocked,
9009            left_pr: false,
9010            quota_hit: false,
9011            parked: false,
9012            no_viable_candidates: false,
9013        };
9014        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
9015        assert_eq!(t.status, TaskStatus::Held);
9016        assert_eq!(t.attempts, 0, "the attempt is refunded");
9017        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
9018        assert!(
9019            !t.operator_held(),
9020            "a machine hold, released without a human"
9021        );
9022
9023        let mut selected = task();
9024        selected.start("20260902-000000-cccc".into());
9025        selected.replacement = Some(crate::merge_decision::Replacement {
9026            question: "fixture".into(),
9027            run: "earlier".into(),
9028            pr: "https://example.invalid/pr/1".into(),
9029            agent: "selected".into(),
9030            context: "fixture".into(),
9031        });
9032        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
9033        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
9034        assert_eq!(selected.attempts, 0);
9035        assert!(
9036            !selected.operator_held(),
9037            "a selected agent also retains a machine resource hold"
9038        );
9039        assert!(
9040            selected
9041                .hold_reason
9042                .as_deref()
9043                .unwrap()
9044                .starts_with("[resource] ")
9045        );
9046
9047        // A park request outranks it: still the operator's doing.
9048        let mut p = task();
9049        p.start("20260902-000000-bbbb".to_owned());
9050        settle_and_diagnose(
9051            &mut p,
9052            Verdict {
9053                parked: true,
9054                ..verdict
9055            },
9056            "parked",
9057            2,
9058            &state,
9059        );
9060        assert_eq!(p.status, TaskStatus::Parked);
9061        assert_eq!(
9062            p.attempts, 0,
9063            "parking refunds once rather than also settling the resource hold"
9064        );
9065    }
9066
9067    #[test]
9068    fn record_failure_notice_links_the_task() {
9069        let dir = tempfile::tempdir().unwrap();
9070        // A regular file where the queue directory should be makes every
9071        // `put` fail, on every platform and whoever runs the test.
9072        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
9073        let queue = Queue::at(dir.path().join("queue"));
9074        let mut t = interrupt_task("rec-fail-1");
9075        record(&queue, &mut t);
9076
9077        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
9078        assert_eq!(found.len(), 1);
9079        assert_eq!(found[0].key, "loop:record");
9080        assert_eq!(
9081            found[0].link,
9082            Some(Link::Task {
9083                id: "rec-fail-1".to_owned()
9084            })
9085        );
9086    }
9087
9088    /// A runnable task marked to interrupt, with an id fixed for assertions
9089    /// rather than the random one [`Task::new`] mints.
9090    fn interrupt_task(id: &str) -> Task {
9091        let mut t = task();
9092        t.id = id.to_owned();
9093        t.interrupt = true;
9094        t
9095    }
9096
9097    /// An ordinary runnable task with an id fixed for assertions.
9098    fn task_with_id(id: &str) -> Task {
9099        let mut t = task();
9100        t.id = id.to_owned();
9101        t
9102    }
9103
9104    /// A runnable task marked `--urgent`, with an id fixed for assertions.
9105    fn urgent_task(id: &str) -> Task {
9106        let mut t = task();
9107        t.id = id.to_owned();
9108        t.urgent = true;
9109        t
9110    }
9111
9112    #[test]
9113    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
9114        let dir = tempfile::tempdir().unwrap();
9115        let queue = Queue::at(dir.path().join("queue"));
9116        let mut parked = task_with_id("parked");
9117        parked.start("run".into());
9118        parked.park("upgrade");
9119        parked.record_pass_at(
9120            "run",
9121            0,
9122            Some(Timestamp::now()),
9123            1,
9124            Some(crate::run::ParkCause::Upgrade {
9125                from: "old".into(),
9126                to: None,
9127            }),
9128        );
9129        let mut fresh = task_with_id("fresh");
9130        fresh.priority = 100;
9131        let mut urgent_task = urgent_task("urgent");
9132        for t in [&mut parked, &mut fresh, &mut urgent_task] {
9133            queue.put(t).unwrap();
9134        }
9135        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9136        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9137        let candidates = runnable(&queue);
9138        assert_eq!(candidates[0].id, parked.id);
9139        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
9140        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
9141        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
9142        drop(first);
9143        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
9144        let next = runnable(&queue)
9145            .into_iter()
9146            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
9147            .unwrap();
9148        assert_eq!(next.task.id, fresh.id);
9149        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
9150        drop(claimed_elsewhere);
9151        drop(next);
9152        assert!(matches!(
9153            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
9154            Err(SkipReason::CoolingDown)
9155        ));
9156    }
9157
9158    #[test]
9159    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
9160        let dir = tempfile::tempdir().unwrap();
9161        let queue = Queue::at(dir.path().join("queue"));
9162        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9163        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9164        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
9165        let mut first = task();
9166        queue.put(&mut first).unwrap();
9167        let stale_plain = queue.get(&first.id).unwrap();
9168        first.set_urgent(true).unwrap();
9169        queue.put(&mut first).unwrap();
9170        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
9171        let mut second = urgent_task("second");
9172        queue.put(&mut second).unwrap();
9173        assert!(matches!(
9174            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
9175            Err(SkipReason::UrgentCapacity)
9176        ));
9177        drop(queue.claim(&second.id).unwrap());
9178        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
9179        drop(dispatched);
9180        let stale_urgent = queue.get(&first.id).unwrap();
9181        first.set_urgent(false).unwrap();
9182        queue.put(&mut first).unwrap();
9183        assert!(matches!(
9184            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
9185            Err(SkipReason::OrdinaryCapacity)
9186        ));
9187        assert_eq!(urgent.available_permits(), 1);
9188        drop(queue.claim(&first.id).unwrap());
9189        drop(occupied);
9190    }
9191
9192    #[test]
9193    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
9194        let dir = tempfile::tempdir().unwrap();
9195        let queue = Queue::at(dir.path().join("queue"));
9196        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9197        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9198        let mut t = task();
9199        queue.put(&mut t).unwrap();
9200        for enabled in [true, false] {
9201            let stale = queue.get(&t.id).unwrap();
9202            t.set_urgent(enabled).unwrap();
9203            queue.put(&mut t).unwrap();
9204            assert_ne!(stale.urgent, enabled);
9205            let DispatchClaim {
9206                task: fresh,
9207                claim,
9208                lane,
9209                permit,
9210            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
9211            assert_eq!(fresh.urgent, enabled);
9212            assert_eq!(
9213                lane,
9214                if enabled {
9215                    PermitKind::Urgent
9216                } else {
9217                    PermitKind::Ordinary
9218                }
9219            );
9220            assert_eq!(ordinary.available_permits(), usize::from(enabled));
9221            assert_eq!(urgent.available_permits(), usize::from(!enabled));
9222            assert!(queue.claim(&t.id).is_err());
9223            assert_eq!(fresh.attempts, stale.attempts);
9224            drop((claim, permit));
9225            assert_eq!(ordinary.available_permits(), 1);
9226            assert_eq!(urgent.available_permits(), 1);
9227        }
9228        t.set_urgent(true).unwrap();
9229        queue.put(&mut t).unwrap();
9230        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
9231        assert!(matches!(
9232            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9233            Err(SkipReason::UrgentCapacity)
9234        ));
9235        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
9236        drop(queue.claim(&t.id).unwrap());
9237        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
9238        drop(occupied);
9239        assert!(matches!(
9240            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
9241            Err(SkipReason::CoolingDown)
9242        ));
9243        drop(queue.claim(&t.id).unwrap());
9244        let held = queue.claim(&t.id).unwrap();
9245        assert!(matches!(
9246            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9247            Err(SkipReason::ClaimUnavailable)
9248        ));
9249        drop(held);
9250        t.status = TaskStatus::Held;
9251        queue.put(&mut t).unwrap();
9252        assert!(matches!(
9253            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9254            Err(SkipReason::NoLongerRunnable)
9255        ));
9256        drop(queue.claim(&t.id).unwrap());
9257        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
9258        assert!(matches!(
9259            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9260            Err(SkipReason::RereadFailed)
9261        ));
9262        drop(queue.claim(&t.id).unwrap());
9263        assert_eq!(urgent.available_permits(), 1);
9264    }
9265
9266    /// The land-resume exemption wins outright, whether or not the candidate
9267    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
9268    /// queue behind anything" guarantee cannot be weaker just because the
9269    /// same task was also filed with `--urgent`.
9270    #[test]
9271    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
9272        assert_eq!(permit_kind(true, false, false), PermitKind::None);
9273        assert_eq!(permit_kind(true, false, true), PermitKind::None);
9274        assert_eq!(permit_kind(true, true, false), PermitKind::None);
9275        assert_eq!(permit_kind(true, true, true), PermitKind::None);
9276    }
9277
9278    /// The one property this whole feature exists for: `--urgent` draws from
9279    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
9280    /// ordinary candidate draws from the ordinary pool exactly as before,
9281    /// untouched by the urgent slot's existence.
9282    #[test]
9283    fn permit_kind_separates_urgent_from_ordinary() {
9284        assert_eq!(permit_kind(false, false, true), PermitKind::Urgent);
9285        assert_eq!(permit_kind(false, false, false), PermitKind::Ordinary);
9286        assert_eq!(permit_kind(false, true, false), PermitKind::Immediate);
9287        assert_eq!(permit_kind(false, true, true), PermitKind::Immediate);
9288    }
9289
9290    #[test]
9291    fn immediate_lane_does_not_consume_ordinary_or_urgent_slots() {
9292        let request = |task: &str, lane, standalone| TaskWorker {
9293            opts: Opts::default(),
9294            queue: PathBuf::from("/queue"),
9295            task: task.to_owned(),
9296            lane,
9297            standalone,
9298        };
9299        let jobs = vec![
9300            request("ordinary", PermitKind::Ordinary, false),
9301            request("urgent", PermitKind::Urgent, false),
9302            request("immediate-1", PermitKind::Immediate, false),
9303            request("immediate-2", PermitKind::Immediate, false),
9304            request("decision", PermitKind::None, false),
9305        ];
9306        assert_eq!(available_slots(&jobs, 1), (0, 0));
9307        assert_eq!(available_slots(&jobs, 2), (1, 0));
9308        let immediate_only = vec![
9309            request("immediate-1", PermitKind::Immediate, false),
9310            request("immediate-2", PermitKind::Immediate, false),
9311        ];
9312        assert_eq!(available_slots(&immediate_only, 1), (1, 1));
9313    }
9314
9315    #[test]
9316    fn immediate_dispatch_bypasses_saturated_lanes_and_preserves_non_concurrency_gates() {
9317        let dir = tempfile::tempdir().unwrap();
9318        let queue = Queue::at(dir.path().join("queue"));
9319        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9320        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9321        let _ord_permit = Arc::clone(&ordinary).try_acquire_owned().unwrap();
9322        let _urg_permit = Arc::clone(&urgent).try_acquire_owned().unwrap();
9323
9324        // Both ordinary and urgent lanes are saturated.
9325        let mut imm1 = task_with_id("imm-1");
9326        imm1.immediate = true;
9327        let mut imm2 = task_with_id("imm-2");
9328        imm2.immediate = true;
9329        imm2.urgent = true;
9330        queue.put(&mut imm1).unwrap();
9331        queue.put(&mut imm2).unwrap();
9332
9333        // Stale non-immediate listing still picks up saved immediate under claim.
9334        let mut stale = imm1.clone();
9335        stale.immediate = false;
9336        let claim1 = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
9337        assert_eq!(claim1.lane, PermitKind::Immediate);
9338        assert!(claim1.permit.is_none());
9339
9340        // Multiple immediate tasks can claim simultaneously without touching semaphores.
9341        let claim2 = claim_dispatch(&queue, &imm2, false, &ordinary, &urgent).unwrap();
9342        assert_eq!(claim2.lane, PermitKind::Immediate);
9343        assert!(claim2.permit.is_none());
9344        assert_eq!(ordinary.available_permits(), 0);
9345        assert_eq!(urgent.available_permits(), 0);
9346
9347        // Duplicate claim on an already-claimed immediate task is refused.
9348        assert_eq!(
9349            claim_dispatch(&queue, &imm1, false, &ordinary, &urgent).err(),
9350            Some(SkipReason::ClaimUnavailable)
9351        );
9352        drop((claim1, claim2));
9353
9354        // Cooldown still blocks immediate tasks.
9355        assert_eq!(
9356            claim_dispatch(&queue, &imm1, true, &ordinary, &urgent).err(),
9357            Some(SkipReason::CoolingDown)
9358        );
9359
9360        // Clearing immediate while urgent remains true reverts to urgent lane.
9361        imm2.set_immediate(false).unwrap();
9362        queue.put(&mut imm2).unwrap();
9363        assert_eq!(
9364            claim_dispatch(&queue, &imm2, false, &ordinary, &urgent).err(),
9365            Some(SkipReason::UrgentCapacity)
9366        );
9367
9368        // Interrupt gate still withholds immediate candidates.
9369        let interrupt = Interrupt::Parking {
9370            parked: vec!["in-flight".into()],
9371            interrupt_task: "other".into(),
9372        };
9373        assert!(
9374            interrupt_gate(&interrupt, &["in-flight".into()], vec![imm1.clone()]).is_empty(),
9375            "an active interrupt sequence must withhold immediate tasks too"
9376        );
9377    }
9378
9379    #[test]
9380    fn admission_snapshot_distinguishes_mode_lane_blockers_and_unknown_state() {
9381        let dir = tempfile::tempdir().unwrap();
9382        let home = dir.path();
9383        let queue = Queue::at(home.join("queue"));
9384        let now = Timestamp::now();
9385
9386        let mut imm = task_with_id("imm-ready");
9387        imm.immediate = true;
9388        queue.put(&mut imm).unwrap();
9389
9390        // No scheduler running -> waiting, never "next poll".
9391        let snap = AdmissionSnapshot::capture(home, now);
9392        let adm = snap.evaluate(&imm, &queue, None, home);
9393        assert_eq!(adm.mode, "immediate");
9394        assert_eq!(adm.state, "waiting");
9395        assert_eq!(adm.label, "Immediate: waiting — scheduler not running");
9396
9397        // Live scheduler + saturated ordinary/urgent workers + stale capacity skip -> next poll!
9398        let mut status = Status::new();
9399        status.updated_at = now;
9400        status
9401            .dispatch_skips
9402            .insert(imm.id.clone(), SkipReason::UrgentCapacity.key().to_owned());
9403        write_status_to(&home.join("daemon.json"), &status).unwrap();
9404
9405        let mut ord = task_with_id("ord-running");
9406        ord.status = TaskStatus::Running;
9407        queue.put(&mut ord).unwrap();
9408        let ord_req = TaskWorker {
9409            opts: Opts::default(),
9410            queue: queue.root().to_path_buf(),
9411            task: ord.id.clone(),
9412            lane: PermitKind::Ordinary,
9413            standalone: false,
9414        };
9415        let (_ord_job, _ord_lease) = crate::worker::running_fixture(
9416            home,
9417            &format!("task:{}", ord.id),
9418            serde_json::to_value(&ord_req).unwrap(),
9419        )
9420        .unwrap();
9421
9422        let mut urg = task_with_id("urg-running");
9423        urg.urgent = true;
9424        urg.status = TaskStatus::Running;
9425        queue.put(&mut urg).unwrap();
9426        let urg_req = TaskWorker {
9427            opts: Opts::default(),
9428            queue: queue.root().to_path_buf(),
9429            task: urg.id.clone(),
9430            lane: PermitKind::Urgent,
9431            standalone: false,
9432        };
9433        let (_urg_job, _urg_lease) = crate::worker::running_fixture(
9434            home,
9435            &format!("task:{}", urg.id),
9436            serde_json::to_value(&urg_req).unwrap(),
9437        )
9438        .unwrap();
9439
9440        let snap = AdmissionSnapshot::capture(home, now);
9441        let adm = snap.evaluate(&imm, &queue, None, home);
9442        assert_eq!(adm.state, "next_poll");
9443        assert_eq!(adm.label, "Immediate: next poll");
9444        assert_eq!(adm.reservation_lane, None);
9445
9446        // Running worker reports its actual persisted reservation lane.
9447        let ord_adm = snap.evaluate(&ord, &queue, None, home);
9448        assert_eq!(ord_adm.state, "running");
9449        assert_eq!(ord_adm.reservation_lane, Some("ordinary"));
9450        assert_eq!(ord_adm.label, "Running (ordinary lane)");
9451
9452        // Held (manual + disk) and Blocked (dependency) report concrete blockers.
9453        let mut held = task_with_id("imm-held");
9454        held.immediate = true;
9455        held.hold_manual(Some("awaiting signoff".into()));
9456        queue.put(&mut held).unwrap();
9457        let held_adm = snap.evaluate(&held, &queue, None, home);
9458        assert_eq!(held_adm.state, "waiting");
9459        assert_eq!(
9460            held_adm.label,
9461            "Immediate: waiting — held (awaiting signoff)"
9462        );
9463
9464        let mut disk_held = task_with_id("imm-disk");
9465        disk_held.immediate = true;
9466        disk_held.hold_machine(Some("only 1 GiB free".into()));
9467        disk_held.mark_startup_disk_capacity();
9468        queue.put(&mut disk_held).unwrap();
9469        let disk_adm = snap.evaluate(&disk_held, &queue, None, home);
9470        assert_eq!(disk_adm.state, "waiting");
9471        assert!(disk_adm.label.contains("disk admission"), "{disk_adm:?}");
9472
9473        let mut blocked = task_with_id("imm-blocked");
9474        blocked.immediate = true;
9475        blocked.block(vec![held.id.clone()], Some("needs held task".into()));
9476        queue.put(&mut blocked).unwrap();
9477        let questions = Questions::at(home.join("questions"));
9478        let inv = crate::blockers::Inventory::load(&queue, &questions);
9479        let blocked_adm = snap.evaluate(&blocked, &queue, Some(&inv), home);
9480        assert_eq!(blocked_adm.state, "waiting");
9481        assert!(
9482            blocked_adm
9483                .label
9484                .starts_with("Immediate: waiting — waiting on dependencies"),
9485            "{blocked_adm:?}"
9486        );
9487
9488        // Existing claim blocks immediate.
9489        let _claim = queue.claim(&imm.id).unwrap();
9490        let claimed_adm = snap.evaluate(&imm, &queue, None, home);
9491        assert_eq!(claimed_adm.state, "waiting");
9492        assert_eq!(
9493            claimed_adm.label,
9494            "Immediate: waiting — claimed by another process"
9495        );
9496        drop(_claim);
9497
9498        // Quota cooldown blocks immediate.
9499        let until = now + jiff::SignedDuration::from_secs(120);
9500        std::fs::write(
9501            home.join("task-quota-cooldown.json"),
9502            serde_json::to_vec(&until).unwrap(),
9503        )
9504        .unwrap();
9505        let cool_snap = AdmissionSnapshot::capture(home, now);
9506        let cool_adm = cool_snap.evaluate(&imm, &queue, None, home);
9507        assert_eq!(cool_adm.state, "waiting");
9508        assert!(cool_adm.label.contains("quota cooldown"), "{cool_adm:?}");
9509        std::fs::remove_file(home.join("task-quota-cooldown.json")).unwrap();
9510
9511        // Corrupt interrupt file is reported as unknown, never "next poll".
9512        std::fs::write(home.join("scheduler-interrupt.json"), "{broken").unwrap();
9513        let bad_snap = AdmissionSnapshot::capture(home, now);
9514        let bad_adm = bad_snap.evaluate(&imm, &queue, None, home);
9515        assert_eq!(bad_adm.state, "unknown");
9516        assert_ne!(bad_adm.label, "Immediate: next poll");
9517    }
9518
9519    /// The exact wiring `attempt` runs before minting anything: a config's
9520    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
9521    /// Free space is injected rather than asked of the real disk - the point
9522    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
9523    /// is deterministic on every machine this test runs on, never dependent
9524    /// on how full the CI runner's own disk happens to be.
9525    #[test]
9526    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
9527        let cfg = Config::default();
9528        let repo = Path::new("/any/repo/path");
9529
9530        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
9531            .expect("must hold below the threshold");
9532        assert!(reason.contains("1024"), "{reason}");
9533        assert!(
9534            reason.contains(&cfg.disk.min_free_bytes.to_string()),
9535            "{reason}"
9536        );
9537
9538        assert_eq!(
9539            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
9540            None,
9541            "exactly at the floor is open"
9542        );
9543        assert_eq!(
9544            disk_gate_with(
9545                repo,
9546                &cfg,
9547                PathBuf::new,
9548                |_| Ok(cfg.disk.min_free_bytes + 1)
9549            ),
9550            None,
9551            "comfortably above the floor is open"
9552        );
9553    }
9554
9555    #[test]
9556    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
9557        let dir = tempfile::tempdir().unwrap();
9558        let repo = dir.path().join("repo");
9559        let cache = dir.path().join("cache");
9560        let worktrees = dir.path().join("worktrees");
9561        for path in [&repo, &cache, &worktrees] {
9562            std::fs::create_dir(path).unwrap();
9563        }
9564        let mut cfg = Config::default();
9565        cfg.graph.worktree_root = Some(worktrees.clone());
9566        cfg.verify.gate = vec![format!(
9567            "CARGO_TARGET_DIR='{}' cargo build",
9568            cache.display()
9569        )];
9570        for blocked in [&cache, &worktrees] {
9571            for unmeasured in [false, true] {
9572                assert!(
9573                    disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
9574                        if path == blocked {
9575                            if unmeasured {
9576                                Err(anyhow::anyhow!("measurement failed"))
9577                            } else {
9578                                Ok(0)
9579                            }
9580                        } else {
9581                            Ok(u64::MAX)
9582                        }
9583                    })
9584                    .is_some(),
9585                    "a blocked secondary output volume must close admission"
9586                );
9587            }
9588        }
9589        assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
9590    }
9591
9592    #[test]
9593    fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
9594        let dir = tempfile::tempdir().unwrap();
9595        let repo = dir.path().join("repo");
9596        let cache = dir.path().join("cache");
9597        let home_parent = dir.path().join("run-volume");
9598        let home = home_parent.join("new-home");
9599        for path in [&repo, &cache, &home_parent] {
9600            std::fs::create_dir(path).unwrap();
9601        }
9602        let mut cfg = Config::default();
9603        cfg.graph.worktree_root = Some(repo.clone());
9604        cfg.verify.gate = vec![format!(
9605            "CARGO_TARGET_DIR='{}' cargo build",
9606            cache.display()
9607        )];
9608        cfg.verify.build_cache = BuildCache::Isolated;
9609        let denied = |blocked: &Path| {
9610            disk_gate_with(
9611                &repo,
9612                &cfg,
9613                || home.clone(),
9614                |path| Ok(if path == blocked { 0 } else { u64::MAX }),
9615            )
9616            .is_some()
9617        };
9618        assert!(!denied(&cache));
9619        assert!(denied(&home_parent));
9620    }
9621
9622    #[test]
9623    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
9624        let mut cfg = Config::default();
9625        cfg.disk.min_free_bytes = 0;
9626        let repo = Path::new("/any/repo/path");
9627        assert_eq!(
9628            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
9629            None,
9630            "a zero floor never measures at all"
9631        );
9632    }
9633
9634    #[test]
9635    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
9636        let cfg = Config::default();
9637        let repo = Path::new("/any/repo/path");
9638        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
9639            Err(anyhow::anyhow!("no df on this box"))
9640        })
9641        .expect("a measurement failure must close the gate, not open it");
9642        assert!(reason.contains("could not measure"), "{reason}");
9643    }
9644
9645    #[test]
9646    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
9647        let ordinary = task();
9648        let next = advance_interrupt(
9649            Interrupt::Idle,
9650            std::slice::from_ref(&ordinary.id),
9651            std::slice::from_ref(&ordinary),
9652        );
9653        assert_eq!(next, Interrupt::Idle);
9654    }
9655
9656    #[test]
9657    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
9658        // Nothing to interrupt - this is just an ordinary candidate, and the
9659        // loop's normal dispatch will pick it up like any other.
9660        let marked = interrupt_task("marked");
9661        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
9662        assert_eq!(next, Interrupt::Idle);
9663    }
9664
9665    #[test]
9666    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
9667        let marked = interrupt_task("marked");
9668        let next = advance_interrupt(
9669            Interrupt::Idle,
9670            &["running".to_owned()],
9671            std::slice::from_ref(&marked),
9672        );
9673        assert_eq!(
9674            next,
9675            Interrupt::Parking {
9676                parked: vec!["running".to_owned()],
9677                interrupt_task: "marked".to_owned(),
9678            }
9679        );
9680    }
9681
9682    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
9683    /// one run can be in flight when a task becomes runnable and marked.
9684    /// Parking all of them would mean `Resuming` later has more than one id
9685    /// to release back to ordinary dispatch, which cannot be made safe
9686    /// against that same setting's own extra concurrency slots letting two
9687    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
9688    /// The simplification the task's own constraints ask for: do not begin
9689    /// a sequence at all until the herd settles back to exactly one.
9690    #[test]
9691    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
9692        let marked = interrupt_task("marked");
9693
9694        let two = advance_interrupt(
9695            Interrupt::Idle,
9696            &["a".to_owned(), "b".to_owned()],
9697            std::slice::from_ref(&marked),
9698        );
9699        assert_eq!(two, Interrupt::Idle);
9700
9701        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
9702        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
9703    }
9704
9705    #[test]
9706    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
9707        let state = Interrupt::Parking {
9708            parked: vec!["running".to_owned()],
9709            interrupt_task: "marked".to_owned(),
9710        };
9711        // Still in flight: no change.
9712        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
9713        assert_eq!(still_going, state);
9714
9715        // Left flight, but the interrupt task has not been dispatched yet on
9716        // this tick - stays `Parking` so `interrupt_gate` can let it through,
9717        // as long as it is still runnable.
9718        let stopped_but_not_yet_dispatched =
9719            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
9720        assert_eq!(stopped_but_not_yet_dispatched, state);
9721
9722        // Left flight, and the interrupt task is now in flight itself.
9723        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
9724        assert_eq!(
9725            dispatched,
9726            Interrupt::Running {
9727                parked: vec!["running".to_owned()],
9728                interrupt_task: "marked".to_owned(),
9729            }
9730        );
9731    }
9732
9733    #[test]
9734    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
9735        let state = Interrupt::Running {
9736            parked: vec!["running".to_owned()],
9737            interrupt_task: "marked".to_owned(),
9738        };
9739        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
9740        assert_eq!(still_running, state);
9741
9742        // Whatever it ended as - merged, failed, held - is not this
9743        // function's concern: leaving flight is the only trigger, driven
9744        // straight off the same in-flight list `poll` already reaps. It does
9745        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
9746        // why that would let an unrelated task start ahead of, or alongside,
9747        // the guaranteed resume.
9748        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
9749        assert_eq!(
9750            ended,
9751            Interrupt::Resuming {
9752                parked: vec!["running".to_owned()]
9753            }
9754        );
9755    }
9756
9757    #[test]
9758    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
9759        let state = Interrupt::Resuming {
9760            parked: vec!["running".to_owned()],
9761        };
9762        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
9763        assert_eq!(still_waiting, state);
9764
9765        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
9766        assert_eq!(dispatched, Interrupt::Idle);
9767    }
9768
9769    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
9770    /// or otherwise moved on by an operator with no claim standing in the
9771    /// way - must not wedge the sequence (and so the whole loop's dispatch,
9772    /// via `interrupt_gate`) waiting forever for a dispatch that can never
9773    /// come. The parked run still gets its resume.
9774    #[test]
9775    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
9776    {
9777        let state = Interrupt::Parking {
9778            parked: vec!["running".to_owned()],
9779            interrupt_task: "marked".to_owned(),
9780        };
9781        // `marked` has been held/blocked/deleted since the sequence began:
9782        // it no longer appears in `runnable` at all.
9783        let next = advance_interrupt(state, &[], &[]);
9784        assert_eq!(
9785            next,
9786            Interrupt::Resuming {
9787                parked: vec!["running".to_owned()]
9788            },
9789            "abandoning the interrupt must not abandon the resume it owes"
9790        );
9791    }
9792
9793    /// The same abandonment, one step later: `Resuming` itself must not wait
9794    /// forever for a parked task that has since become unrunnable.
9795    #[test]
9796    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
9797        let state = Interrupt::Resuming {
9798            parked: vec!["running".to_owned()],
9799        };
9800        let next = advance_interrupt(state, &[], &[]);
9801        assert_eq!(
9802            next,
9803            Interrupt::Idle,
9804            "nothing is left to wait for; the loop must not stay wedged"
9805        );
9806    }
9807
9808    #[test]
9809    fn disabled_by_config_the_sequence_can_never_leave_idle() {
9810        let marked = interrupt_task("marked");
9811        let next = advance_interrupt_tick(
9812            false,
9813            Interrupt::Idle,
9814            &["running".to_owned()],
9815            std::slice::from_ref(&marked),
9816        );
9817        assert_eq!(
9818            next,
9819            Interrupt::Idle,
9820            "an unmarked, unconfigured daemon must behave exactly as before"
9821        );
9822    }
9823
9824    #[test]
9825    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
9826        let state = Interrupt::Parking {
9827            parked: vec!["running".to_owned()],
9828            interrupt_task: "marked".to_owned(),
9829        };
9830        let candidates = vec![interrupt_task("marked"), task()];
9831        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
9832        assert!(
9833            allowed.is_empty(),
9834            "nothing may dispatch - not even the interrupt task itself - \
9835             until the parked run has actually stopped"
9836        );
9837    }
9838
9839    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
9840    /// grow a special case for it: an urgent candidate that is not the
9841    /// interrupt task withholds exactly like an ordinary one for as long as
9842    /// the parked run it is racing has not actually left flight. A version
9843    /// of this feature once bypassed the gate for urgent candidates, on the
9844    /// theory that a genuinely separate concurrency lane could not collide
9845    /// with 75dd's own; it could, and did - the bypassed task dispatched
9846    /// alongside a run 75dd's own state machine had only *asked* to park,
9847    /// not yet confirmed gone, which is exactly the second run
9848    /// `Interrupt::Parking`'s own doc says must never happen. There is no
9849    /// tick during Parking/Running/Resuming where letting an extra
9850    /// candidate through is safe, urgent or not - the parked run may still
9851    /// be genuinely mid-call.
9852    #[test]
9853    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
9854        for state in [
9855            Interrupt::Parking {
9856                parked: vec!["running".to_owned()],
9857                interrupt_task: "marked".to_owned(),
9858            },
9859            Interrupt::Running {
9860                parked: vec!["running".to_owned()],
9861                interrupt_task: "marked".to_owned(),
9862            },
9863            Interrupt::Resuming {
9864                parked: vec!["running".to_owned()],
9865            },
9866        ] {
9867            let candidates = vec![
9868                interrupt_task("marked"),
9869                urgent_task("hot"),
9870                task_with_id("ordinary"),
9871            ];
9872            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
9873            assert!(
9874                !allowed.iter().any(|t| t.id == "hot"),
9875                "an urgent candidate must wait out the same gate as anything \
9876                 else while the run it would run alongside has not actually \
9877                 left flight, for state {state:?}: {allowed:?}"
9878            );
9879        }
9880    }
9881
9882    /// The one case where marking a task `--urgent` and `interrupt` at once
9883    /// is not redundant: once the interrupt sequence's own guaranteed
9884    /// resume/dispatch actually admits the task, it is unaffected by also
9885    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
9886    /// never on the urgent flag.
9887    #[test]
9888    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
9889        let state = Interrupt::Resuming {
9890            parked: vec!["hot".to_owned()],
9891        };
9892        let candidates = vec![urgent_task("hot"), task()];
9893        let allowed = interrupt_gate(&state, &[], candidates);
9894        assert_eq!(
9895            allowed.iter().filter(|t| t.id == "hot").count(),
9896            1,
9897            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
9898        );
9899    }
9900
9901    #[test]
9902    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
9903        let state = Interrupt::Parking {
9904            parked: vec!["running".to_owned()],
9905            interrupt_task: "marked".to_owned(),
9906        };
9907        let other = task();
9908        let candidates = vec![interrupt_task("marked"), other.clone()];
9909        let allowed = interrupt_gate(&state, &[], candidates);
9910        assert_eq!(allowed.len(), 1);
9911        assert_eq!(allowed[0].id, "marked");
9912    }
9913
9914    #[test]
9915    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
9916        let state = Interrupt::Running {
9917            parked: vec!["running".to_owned()],
9918            interrupt_task: "marked".to_owned(),
9919        };
9920        let candidates = vec![task(), task()];
9921        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
9922        assert!(allowed.is_empty());
9923    }
9924
9925    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
9926    /// sequence began (only reachable above the default
9927    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
9928    /// never both in the same tick, which is what "exactly one resume, no
9929    /// simultaneous run" actually requires structurally rather than by
9930    /// coincidence of how many ordinary slots happen to be free.
9931    #[test]
9932    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
9933        let state = Interrupt::Resuming {
9934            parked: vec!["a".to_owned(), "c".to_owned()],
9935        };
9936        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
9937        let allowed = interrupt_gate(&state, &[], candidates);
9938        assert_eq!(
9939            allowed.len(),
9940            1,
9941            "at most one candidate may be offered while resuming: {allowed:?}"
9942        );
9943        assert_eq!(allowed[0].id, "a");
9944    }
9945
9946    #[test]
9947    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
9948        let state = Interrupt::Resuming {
9949            parked: vec!["a".to_owned()],
9950        };
9951        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
9952        assert!(allowed.is_empty());
9953    }
9954
9955    /// The invariant the completion criteria ask for by name: across a whole
9956    /// simulated sequence, there is never a tick where the gate would let
9957    /// through both the parked run's resume and the interrupt task, and
9958    /// exactly one candidate resumes the instant the interrupt task's run
9959    /// ends - never zero, never more than one.
9960    #[test]
9961    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
9962        let running = task(); // id: whatever `Task::new` minted
9963        let marked = interrupt_task("marked");
9964
9965        let mut state = Interrupt::Idle;
9966        // Tick 1: `running` is in flight, `marked` becomes runnable.
9967        let in_flight = vec![running.id.clone()];
9968        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
9969        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
9970        assert!(gated.is_empty(), "still waiting on `running` to park");
9971
9972        // Tick 2: `running` parked and left flight; nothing dispatched yet.
9973        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
9974        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
9975        assert_eq!(
9976            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
9977            vec!["marked"],
9978            "only the interrupt task may be offered to the dispatcher now"
9979        );
9980
9981        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
9982        state = advance_interrupt_tick(
9983            true,
9984            state,
9985            &["marked".to_owned()],
9986            std::slice::from_ref(&running),
9987        );
9988        let gated = interrupt_gate(
9989            &state,
9990            &["marked".to_owned()],
9991            vec![marked.clone(), running.clone()],
9992        );
9993        assert!(
9994            gated.is_empty(),
9995            "the parked run must not be offered back while the interrupt \
9996             task is still running"
9997        );
9998
9999        // Tick 4: `marked`'s run reached a terminal status and left flight.
10000        // A higher-priority ordinary task `other` is also runnable now - it
10001        // must not be let through instead of, or alongside, `running`.
10002        let other = task_with_id("other");
10003        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
10004        assert_eq!(
10005            state,
10006            Interrupt::Resuming {
10007                parked: vec![running.id.clone()]
10008            }
10009        );
10010        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
10011        assert_eq!(
10012            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10013            vec![running.id.as_str()],
10014            "exactly the parked run resumes - not the unrelated task, even \
10015             though it was offered first"
10016        );
10017
10018        // Tick 5: `running` is now in flight (dispatched from tick 4's
10019        // gate). Only now does the sequence end and ordinary dispatch fully
10020        // resume.
10021        state = advance_interrupt_tick(
10022            true,
10023            state,
10024            std::slice::from_ref(&running.id),
10025            std::slice::from_ref(&other),
10026        );
10027        assert_eq!(state, Interrupt::Idle);
10028        let gated = interrupt_gate(
10029            &state,
10030            std::slice::from_ref(&running.id),
10031            vec![other.clone()],
10032        );
10033        assert_eq!(
10034            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10035            vec![other.id.as_str()],
10036            "ordinary dispatch is unrestricted again"
10037        );
10038    }
10039
10040    #[test]
10041    fn every_run_status_settles_the_task_it_came_from() {
10042        // run status, resulting task status, attempts still standing after one
10043        let table = [
10044            (RunStatus::Merged, TaskStatus::Done, 1),
10045            (RunStatus::Ready, TaskStatus::Done, 1),
10046            (RunStatus::Stalled, TaskStatus::Failed, 0),
10047            (RunStatus::Blocked, TaskStatus::Failed, 1),
10048            (RunStatus::Failed, TaskStatus::Failed, 1),
10049            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
10050            (RunStatus::Prep, TaskStatus::Failed, 1),
10051            (RunStatus::Implementing, TaskStatus::Failed, 1),
10052            (RunStatus::Judging, TaskStatus::Failed, 1),
10053            (RunStatus::Deliberating, TaskStatus::Failed, 1),
10054            (RunStatus::Voting, TaskStatus::Failed, 1),
10055            (RunStatus::Reviewing, TaskStatus::Failed, 1),
10056            (RunStatus::Gating, TaskStatus::Failed, 1),
10057        ];
10058        for (run, want, attempts) in table {
10059            let mut t = task();
10060            t.start("20260902-000000-aaaa".to_owned());
10061            settle(
10062                &mut t,
10063                Verdict {
10064                    status: run,
10065                    left_pr: false,
10066                    parked: false,
10067                    quota_hit: matches!(run, RunStatus::Stalled),
10068                    no_viable_candidates: false,
10069                },
10070                "why",
10071                2,
10072            );
10073            assert_eq!(t.status, want, "task status after {}", label(run));
10074            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
10075        }
10076    }
10077
10078    #[test]
10079    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
10080        let mut stalled = task();
10081        stalled.start("20260902-000000-aaaa".to_owned());
10082        settle(
10083            &mut stalled,
10084            Verdict {
10085                status: RunStatus::Stalled,
10086                left_pr: false,
10087                parked: false,
10088                quota_hit: true,
10089                no_viable_candidates: false,
10090            },
10091            "quota",
10092            1,
10093        );
10094        assert_eq!(stalled.attempts, 0);
10095        assert!(
10096            stalled.status.runnable(),
10097            "a machine problem must leave the task in line"
10098        );
10099
10100        let mut blocked = task();
10101        blocked.start("20260902-000000-aaaa".to_owned());
10102        settle(
10103            &mut blocked,
10104            Verdict {
10105                status: RunStatus::Blocked,
10106                left_pr: false,
10107                parked: false,
10108                quota_hit: false,
10109                no_viable_candidates: false,
10110            },
10111            "findings open",
10112            1,
10113        );
10114        assert_eq!(blocked.attempts, 1);
10115        assert_eq!(
10116            blocked.status,
10117            TaskStatus::Held,
10118            "the last attempt hands the task to a human"
10119        );
10120    }
10121
10122    #[test]
10123    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
10124        // Attempts to spare: without the pull request this task would go
10125        // straight back in line and run the whole competition again.
10126        let mut delivered = task();
10127        delivered.start("20260903-080619-01c2".to_owned());
10128        settle(
10129            &mut delivered,
10130            Verdict {
10131                status: RunStatus::Blocked,
10132                left_pr: true,
10133                parked: false,
10134                quota_hit: false,
10135                no_viable_candidates: false,
10136            },
10137            "no check status",
10138            4,
10139        );
10140        assert_eq!(
10141            delivered.status,
10142            TaskStatus::Held,
10143            "a pull request waiting on CI or a person is not a retryable failure"
10144        );
10145        assert!(
10146            !delivered.status.runnable(),
10147            "the loop must not pick this task up again"
10148        );
10149        assert_eq!(
10150            delivered.last_error.as_deref(),
10151            Some("no check status"),
10152            "the operator needs to be told what the gate was waiting for"
10153        );
10154
10155        // The same status without a pull request is a plain failure, and with
10156        // attempts left it is retried.
10157        let mut empty_handed = task();
10158        empty_handed.start("20260903-080619-01c2".to_owned());
10159        settle(
10160            &mut empty_handed,
10161            Verdict {
10162                status: RunStatus::Blocked,
10163                left_pr: false,
10164                parked: false,
10165                quota_hit: false,
10166                no_viable_candidates: false,
10167            },
10168            "findings open",
10169            4,
10170        );
10171        assert_eq!(empty_handed.status, TaskStatus::Failed);
10172        assert!(empty_handed.status.runnable());
10173    }
10174
10175    #[test]
10176    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
10177        // Every candidate agreed, with evidence, that nothing belonged in the
10178        // worktree. That is not a confirmed success to close automatically -
10179        // a human still has to check the claim - and it is not an ordinary
10180        // failure either, so this settles exactly like a pull request nobody
10181        // merged yet: `Held`, same as `Blocked` with a PR.
10182        let mut noop = task();
10183        noop.start("20260912-131304-391f".to_owned());
10184        settle(
10185            &mut noop,
10186            Verdict {
10187                status: RunStatus::VerifiedNoop,
10188                left_pr: false,
10189                parked: false,
10190                quota_hit: false,
10191                no_viable_candidates: true,
10192            },
10193            "candidate A: already fixed by b32cfc4, on main",
10194            4,
10195        );
10196        assert_eq!(
10197            noop.status,
10198            TaskStatus::Held,
10199            "an unverified claim is a request for a human, not a failure"
10200        );
10201        assert!(
10202            !noop.status.runnable(),
10203            "the loop must not requeue this on the same unverified claim"
10204        );
10205        // `Task::release` resets attempts to zero the moment a human looks at
10206        // the evidence and lets it run again, so it does not matter here
10207        // whether the one attempt already spent stays spent - what matters is
10208        // that nothing retries this task unattended in the meantime.
10209        assert_eq!(noop.attempts, 1);
10210    }
10211
10212    #[test]
10213    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
10214        // Parking is the operator asking for the process back - to replace the
10215        // binary, most of all. The run's work is intact on disk, so this is
10216        // not a failed attempt, and charging for it would mean a few upgrades
10217        // could exhaust a budget meant for agents that misbehaved.
10218        let mut parked = task();
10219        parked.start("20260903-183634-2d98".to_owned());
10220        settle(
10221            &mut parked,
10222            Verdict {
10223                status: RunStatus::Implementing,
10224                left_pr: false,
10225                quota_hit: false,
10226                parked: true,
10227                no_viable_candidates: false,
10228            },
10229            "parked after `implementing`",
10230            2,
10231        );
10232        assert_eq!(parked.attempts, 0, "a park is refunded");
10233        assert!(
10234            parked.status.runnable(),
10235            "and the task stays in line so the next loop resumes its run"
10236        );
10237        assert_eq!(parked.status, TaskStatus::Parked);
10238        assert_eq!(
10239            parked.park_reason.as_deref(),
10240            Some("parked after `implementing`"),
10241            "the card says where it stopped"
10242        );
10243        assert_eq!(parked.last_error, None, "nothing failed");
10244
10245        // Without the park flag the same non-terminal status is what it always
10246        // was: `execute` returning mid-flight, which is a bug and spends an
10247        // attempt so a task cannot loop on it forever.
10248        let mut broken = task();
10249        broken.start("20260903-183634-2d98".to_owned());
10250        settle(
10251            &mut broken,
10252            Verdict {
10253                status: RunStatus::Implementing,
10254                left_pr: false,
10255                quota_hit: false,
10256                parked: false,
10257                no_viable_candidates: false,
10258            },
10259            "returned mid-flight",
10260            2,
10261        );
10262        assert_eq!(broken.attempts, 1);
10263    }
10264
10265    #[test]
10266    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
10267        // Run e633: quorum lost because two judges answered with the wrong
10268        // JSON shape, `quota: []`. Refunding that takes the bound off the
10269        // retry loop, and each retry pays for a fresh hour-long implement
10270        // wave before it can fail the same way.
10271        let mut flaky = task();
10272        flaky.start("20260903-123023-e633".to_owned());
10273        settle(
10274            &mut flaky,
10275            Verdict {
10276                status: RunStatus::Stalled,
10277                left_pr: false,
10278                parked: false,
10279                quota_hit: false,
10280                no_viable_candidates: false,
10281            },
10282            "verdict rests on 1 of 3 judges",
10283            2,
10284        );
10285        assert_eq!(
10286            flaky.attempts, 1,
10287            "flakiness spends an attempt, so `max_attempts` still bounds it"
10288        );
10289        assert!(flaky.status.runnable(), "and it is still worth retrying");
10290
10291        // The same status, lost to a rate limit, is the machine's fault.
10292        let mut limited = task();
10293        limited.start("20260903-123023-e633".to_owned());
10294        settle(
10295            &mut limited,
10296            Verdict {
10297                status: RunStatus::Stalled,
10298                left_pr: false,
10299                parked: false,
10300                quota_hit: true,
10301                no_viable_candidates: false,
10302            },
10303            "judge-2, judge-3 out of quota",
10304            2,
10305        );
10306        assert_eq!(limited.attempts, 0, "a quota window is refunded");
10307        assert!(limited.status.runnable());
10308
10309        // And the bound really binds: a task that keeps stalling on flakiness
10310        // reaches a human instead of running the roster forever.
10311        let mut worn = task();
10312        for _ in 0..2 {
10313            worn.release();
10314        }
10315        worn.start("20260903-123023-e633".to_owned());
10316        worn.attempts = 2;
10317        settle(
10318            &mut worn,
10319            Verdict {
10320                status: RunStatus::Stalled,
10321                left_pr: false,
10322                parked: false,
10323                quota_hit: false,
10324                no_viable_candidates: false,
10325            },
10326            "no quorum again",
10327            2,
10328        );
10329        assert_eq!(worn.status, TaskStatus::Held);
10330        assert!(!worn.status.runnable());
10331    }
10332
10333    #[test]
10334    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
10335        // The implement wave loses every seat to the same rate limit and
10336        // `after_implement` bails with nothing viable, which surfaces as
10337        // `Failed` rather than `Stalled`. That is the same machine fact the
10338        // `Stalled`-quota row already refunds, and must be refunded the same
10339        // way, or a quota outage quietly holds every task it touches instead
10340        // of leaving them in line for the reset.
10341        let mut wiped_out = task();
10342        wiped_out.start("20260907-025000-a1b2".to_owned());
10343        settle(
10344            &mut wiped_out,
10345            Verdict {
10346                status: RunStatus::Failed,
10347                left_pr: false,
10348                parked: false,
10349                quota_hit: true,
10350                no_viable_candidates: true,
10351            },
10352            "no candidate produced a change; nothing to judge",
10353            2,
10354        );
10355        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
10356        assert!(
10357            wiped_out.status.runnable(),
10358            "a machine problem must leave the task in line"
10359        );
10360
10361        // This is the exemption that must stay narrow: a candidate that did
10362        // produce a change, and then failed for some other reason, still
10363        // spends the attempt even though a seat elsewhere hit its quota.
10364        // Otherwise every ordinary failure that happens to share a run with
10365        // an unrelated rate limit would be refunded for free.
10366        let mut partial_progress = task();
10367        partial_progress.start("20260907-025500-c3d4".to_owned());
10368        settle(
10369            &mut partial_progress,
10370            Verdict {
10371                status: RunStatus::Failed,
10372                left_pr: false,
10373                parked: false,
10374                quota_hit: true,
10375                no_viable_candidates: false,
10376            },
10377            "gate failed on the winning candidate",
10378            2,
10379        );
10380        assert_eq!(
10381            partial_progress.attempts, 1,
10382            "a candidate that actually produced a change spends the attempt \
10383             even though some other seat hit its quota"
10384        );
10385        assert!(partial_progress.status.runnable());
10386    }
10387
10388    #[test]
10389    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
10390        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
10391        // disk, and that construction must reach the same conclusion as the
10392        // one `attempt` builds from a live run, or a crash at exactly the
10393        // wrong moment gives a recovered task a different policy than one a
10394        // daemon finished settling itself.
10395        let mut t = task();
10396        t.start("20260907-025000-a1b2".to_owned());
10397        let mut state = run_state(RunStatus::Failed);
10398        state.quota.push(QuotaLoss {
10399            cause: crate::agent::QuotaCause::UsageLimit,
10400            agent: String::new(),
10401            seat: "cand-a".to_owned(),
10402            node: "implement".to_owned(),
10403            at: Timestamp::now(),
10404            reset: None,
10405        });
10406        assert!(
10407            state.viable().is_empty(),
10408            "no candidate was added, so nothing is viable"
10409        );
10410        reclaim(&mut t, Some(state), 2, "en");
10411        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
10412        assert!(t.status.runnable());
10413    }
10414
10415    #[test]
10416    fn a_held_task_is_never_offered_to_the_loop() {
10417        let dir = tempfile::tempdir().unwrap();
10418        let queue = Queue::at(dir.path().to_path_buf());
10419        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
10420            let mut t = task();
10421            t.id = format!("2026090{n}-000000-000{n}");
10422            t.priority = priority;
10423            queue.put(&mut t).unwrap();
10424        }
10425        let mut held = task();
10426        held.id = "20260909-000000-9999".to_owned();
10427        held.priority = 99;
10428        held.hold_machine(None);
10429        queue.put(&mut held).unwrap();
10430
10431        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
10432        assert_eq!(order.len(), 3);
10433        assert!(!order.contains(&held.id));
10434        assert_eq!(
10435            order.first().cloned(),
10436            queue.next_runnable().map(|t| t.id),
10437            "the loop's first candidate is exactly what the queue offers"
10438        );
10439        assert_eq!(
10440            order,
10441            vec![
10442                "20260902-000000-0002".to_owned(),
10443                "20260903-000000-0003".to_owned(),
10444                "20260901-000000-0001".to_owned(),
10445            ],
10446            "priority first, then oldest, so nothing starves"
10447        );
10448    }
10449
10450    #[test]
10451    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
10452        let dir = tempfile::tempdir().unwrap();
10453        let queue = Queue::at(dir.path().to_path_buf());
10454        let mut old = task();
10455        old.id = "20260101-000000-old0".to_owned();
10456        queue.put(&mut old).unwrap();
10457        let mut fresh = task();
10458        fresh.id = "20260101-000000-new0".to_owned();
10459        queue.put(&mut fresh).unwrap();
10460
10461        // No parseable pid at all, so age is the only signal there is to
10462        // check - unlike a real `Queue::claim`, which always names a real,
10463        // and therefore alive, pid this test cannot fake as dead.
10464        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
10465        std::thread::sleep(Duration::from_millis(60));
10466        let live = queue.claim(&fresh.id).unwrap();
10467
10468        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
10469        assert_eq!(swept, vec![old.id.clone()]);
10470        assert!(
10471            queue.claim(&old.id).is_ok(),
10472            "an unparseable lock older than the threshold is swept"
10473        );
10474        assert!(
10475            queue.claim(&fresh.id).is_err(),
10476            "a live pid protects its lock regardless of age"
10477        );
10478        drop(live);
10479    }
10480
10481    #[test]
10482    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
10483        // A live worker's claim remains authoritative even beyond the sweep's
10484        // age limit. Sweeping it would permit a second competing attempt.
10485        let dir = tempfile::tempdir().unwrap();
10486        let queue = Queue::at(dir.path().to_path_buf());
10487        let mut t = task();
10488        t.id = "20260101-000000-live".to_owned();
10489        queue.put(&mut t).unwrap();
10490
10491        let claim = queue.claim(&t.id).unwrap();
10492        std::thread::sleep(Duration::from_millis(60));
10493
10494        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
10495        assert!(
10496            swept.is_empty(),
10497            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
10498        );
10499        assert!(
10500            queue.claim(&t.id).is_err(),
10501            "the lock still protects its task"
10502        );
10503        drop(claim);
10504    }
10505
10506    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
10507    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
10508    fn injected_dead_pid() -> u32 {
10509        std::process::id().checked_add(1).unwrap_or(1)
10510    }
10511
10512    #[test]
10513    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
10514        let dir = tempfile::tempdir().unwrap();
10515        let queue = Queue::at(dir.path().to_path_buf());
10516        let mut t = task();
10517        t.id = "20260101-000000-dead".to_owned();
10518        queue.put(&mut t).unwrap();
10519        let dead_pid = injected_dead_pid();
10520
10521        // Written directly rather than through `Queue::claim`, which would
10522        // stamp this test process's own very much alive pid and defeat the
10523        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
10524        // like moments after it died, not six hours later.
10525        std::fs::write(
10526            dir.path().join(format!("{}.lock", t.id)),
10527            dead_pid.to_string(),
10528        )
10529        .unwrap();
10530
10531        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10532            pid != dead_pid
10533        });
10534        assert_eq!(
10535            swept,
10536            vec![t.id.clone()],
10537            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
10538        );
10539        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
10540    }
10541
10542    #[test]
10543    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
10544        let dir = tempfile::tempdir().unwrap();
10545        let queue = Queue::at(dir.path().to_path_buf());
10546        let mut t = task();
10547        t.id = "20260101-000000-late".to_owned();
10548        queue.put(&mut t).unwrap();
10549        let dead_pid = injected_dead_pid();
10550
10551        // Tick one, standing in for the sweep `poll` already runs at
10552        // startup: nothing to find yet.
10553        assert!(
10554            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
10555            "nothing has claimed the task yet"
10556        );
10557
10558        // A second daemon claims the task and dies before it ever writes
10559        // `running`, well after this loop's own startup sweep already ran.
10560        std::fs::write(
10561            dir.path().join(format!("{}.lock", t.id)),
10562            dead_pid.to_string(),
10563        )
10564        .unwrap();
10565
10566        // Tick two, standing in for a poll long into this daemon's uptime:
10567        // the same function, called again, notices what only just appeared -
10568        // proving the sweep is not a one-shot startup check.
10569        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10570            pid != dead_pid
10571        });
10572        assert_eq!(swept, vec![t.id.clone()]);
10573    }
10574
10575    #[test]
10576    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
10577        // `reclaim_orphaned_running` looks up the task's last run, which
10578        // touches `run::home()`; the first call anywhere in this binary wins,
10579        // so this is a no-op if another test already pinned one, and either
10580        // way the run id below is never written under it.
10581        crate::run::pin_test_home();
10582        let dir = tempfile::tempdir().unwrap();
10583        let queue = Queue::at(dir.path().to_path_buf());
10584        let mut t = task();
10585        t.id = "20260101-000000-crsh".to_owned();
10586        t.status = TaskStatus::Running;
10587        t.attempts = 1;
10588        // No `run.json` behind this id: standing in for a run this test does
10589        // not need to make readable, since the point is the lock, not the
10590        // recovery table `reclaim` already has its own tests for.
10591        t.runs.push("20260904-000000-4043".to_owned());
10592        queue.put(&mut t).unwrap();
10593        let dead_pid = injected_dead_pid();
10594
10595        // The crashed daemon's own claim, naming a pid nothing on the
10596        // machine holds anymore.
10597        std::fs::write(
10598            dir.path().join(format!("{}.lock", t.id)),
10599            dead_pid.to_string(),
10600        )
10601        .unwrap();
10602
10603        // Before the lock is swept the task looks claimed, and
10604        // `reclaim_orphaned_running` must leave it alone - this is exactly
10605        // the bug: a `running` task stranded behind a dead daemon's lock,
10606        // invisible to the claim-as-proof check because the lock outlived
10607        // the process that wrote it.
10608        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
10609        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10610
10611        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10612            pid != dead_pid
10613        });
10614        assert_eq!(swept, vec![t.id.clone()]);
10615
10616        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10617        assert_eq!(reclaimed, vec![t.id.clone()]);
10618        let after = queue.get(&t.id).unwrap();
10619        assert_eq!(
10620            after.status,
10621            TaskStatus::Held,
10622            "no run.json to recover from, so a human is asked"
10623        );
10624        assert_eq!(
10625            after.runs,
10626            vec!["20260904-000000-4043".to_owned()],
10627            "the crashed run's id is kept as evidence, not discarded"
10628        );
10629    }
10630
10631    #[test]
10632    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
10633        let dir = tempfile::tempdir().unwrap();
10634        let queue = Queue::at(dir.path().to_path_buf());
10635        let mut t = task();
10636        t.id = "20260101-000000-unknown".to_owned();
10637        queue.put(&mut t).unwrap();
10638        let dead_pid = injected_dead_pid();
10639        std::fs::write(
10640            dir.path().join(format!("{}.lock", t.id)),
10641            dead_pid.to_string(),
10642        )
10643        .unwrap();
10644
10645        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
10646        assert!(swept.is_empty(), "an unknown pid must keep its lock");
10647        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
10648    }
10649
10650    fn run_state_in(status: RunStatus, language: &str) -> RunState {
10651        let mut s = run_state(status);
10652        s.config.graph.language = language.to_owned();
10653        s
10654    }
10655
10656    fn unstarted_verdict(status: RunStatus) -> Verdict {
10657        Verdict {
10658            status,
10659            left_pr: false,
10660            quota_hit: false,
10661            parked: false,
10662            no_viable_candidates: false,
10663        }
10664    }
10665
10666    #[test]
10667    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
10668        let mut t = task();
10669        t.attempts = 1;
10670        settle_in(
10671            &mut t,
10672            unstarted_verdict(RunStatus::AlreadyInBase),
10673            "already in main",
10674            1,
10675            phrases("en"),
10676            None,
10677        );
10678        assert_eq!(t.status, TaskStatus::Done);
10679        assert_eq!(t.attempts, 0);
10680    }
10681
10682    #[test]
10683    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
10684        let reason = |language: &str| {
10685            let mut t = task();
10686            settle_in(
10687                &mut t,
10688                unstarted_verdict(RunStatus::Judging),
10689                "boom",
10690                1,
10691                phrases(language),
10692                None,
10693            );
10694            t.last_error.or(t.hold_reason).unwrap_or_default()
10695        };
10696        assert!(
10697            reason("en").starts_with("the graph stopped at `"),
10698            "{}",
10699            reason("en")
10700        );
10701        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
10702        assert!(reason("日本語").contains("boom"));
10703        assert_eq!(reason("fr"), reason("en"));
10704    }
10705
10706    #[test]
10707    fn describe_follows_the_run_language_and_keeps_the_run_id() {
10708        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
10709        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
10710        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
10711        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
10712        assert!(ja.contains("[run "), "{ja}");
10713        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
10714        assert!(ended.starts_with("run 終了: "), "{ended}");
10715        let mut de = run_state_in(RunStatus::Failed, "de");
10716        let mut en = run_state_in(RunStatus::Failed, "en");
10717        de.id = "same".to_owned();
10718        en.id = "same".to_owned();
10719        assert_eq!(describe(&de), describe(&en));
10720    }
10721
10722    #[test]
10723    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
10724        use crate::handover::Refused;
10725        let cases = [
10726            Refused::Foreign {
10727                branch: "b".into(),
10728                path: "/w/x".into(),
10729                why: "made by hand".into(),
10730            },
10731            Refused::Unsafe {
10732                branch: "b".into(),
10733                path: "/w/x".into(),
10734                why: "its worktree has uncommitted changes (a.rs)".into(),
10735            },
10736            Refused::ReleaseFailed {
10737                branch: "b".into(),
10738                path: "/w/x".into(),
10739                run: "ab12".into(),
10740            },
10741        ];
10742        for r in &cases {
10743            let en = (phrases("en").handover_refused)(r);
10744            assert_eq!(en, r.to_string());
10745            let ja = (phrases("ja").handover_refused)(r);
10746            assert!(
10747                !ja.contains("is checked out") && !ja.contains("try again"),
10748                "{ja}"
10749            );
10750            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
10751            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
10752                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
10753            }
10754        }
10755        assert!(phrases("en").handover_hint.contains("release the task"));
10756        assert!(phrases("ja").handover_hint.contains("解放"));
10757    }
10758
10759    #[test]
10760    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
10761        let build = |lang: &str| {
10762            let mut s = run_state_in(RunStatus::Blocked, lang);
10763            s.id = "same".to_owned();
10764            s.config.graph.review_rounds = 3;
10765            let mut r = review_round(3);
10766            r.expected = 3;
10767            r.answered = 1;
10768            s.reviews.push(r);
10769            s.event(
10770                "review",
10771                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
10772            );
10773            s
10774        };
10775        let en = describe(&build("en"));
10776        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
10777        let ja = describe(&build("ja"));
10778        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
10779        assert!(!ja.contains("never answered"), "{ja}");
10780        assert!(ja.contains("[run "), "{ja}");
10781
10782        // An incomplete panel whose verification failed is a different stop:
10783        // the real event must survive in ja too.
10784        let mut failed = build("ja");
10785        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
10786            command: "cargo test".to_owned(),
10787            code: Some(1),
10788            output_tail: String::new(),
10789            duration_ms: 0,
10790            resource_blocked: false,
10791            ..Default::default()
10792        });
10793        failed.event("review", "stopped; e2e failed: cargo test");
10794        let ja = describe(&failed);
10795        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
10796        assert!(!ja.contains("席のレビュアー"), "{ja}");
10797    }
10798
10799    #[test]
10800    fn refusals_and_recovery_prose_follow_the_language() {
10801        let home = crate::run::test_home();
10802        let t = held_task_with("r1");
10803        let q = action_question(
10804            "r1",
10805            ask::ChoiceAction::Resume {
10806                run: "r1".to_owned(),
10807            },
10808        );
10809        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
10810            ActionDecision::Refuse(s) => s,
10811            other => panic!("{other:?}"),
10812        };
10813        assert!(refuse(phrases("en")).contains("could not be read: gone"));
10814        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
10815        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
10816
10817        let mut held = task();
10818        reclaim(&mut held, None, 2, "ja");
10819        assert!(held.hold_reason.unwrap().contains("保留にしました"));
10820        let mut held = task();
10821        reclaim(&mut held, None, 2, "xx");
10822        assert!(held.hold_reason.unwrap().contains("held for a human"));
10823    }
10824
10825    fn run_state(status: RunStatus) -> RunState {
10826        let mut state = RunState::new(
10827            PathBuf::from("/repo"),
10828            "main".to_owned(),
10829            "abc1234def".to_owned(),
10830            "add retries".to_owned(),
10831            Config::default(),
10832        );
10833        state.status = status;
10834        state
10835    }
10836
10837    #[test]
10838    fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
10839        crate::run::pin_test_home();
10840        let dir = tempfile::tempdir().unwrap();
10841        let mut state = run_state(RunStatus::Blocked);
10842        state.id = "20260101-000000-audit".into();
10843        state.save_under(dir.path()).unwrap();
10844        let mut t = task();
10845        t.start(state.id.clone());
10846        // The final state is newer than disk, as when a worker settles its
10847        // in-memory outcome or recovery is passed an already loaded run.
10848        state.status = RunStatus::Ready;
10849        settle_and_diagnose(
10850            &mut t,
10851            unstarted_verdict(RunStatus::Ready),
10852            "Verified local delivery",
10853            2,
10854            &state,
10855        );
10856        let completion = t.completion_history.last().unwrap();
10857        assert_eq!(completion.actor, CompletionActor::DaemonSettle);
10858        assert_eq!(completion.prior_status, TaskStatus::Running);
10859        assert_eq!(
10860            completion.reason.as_deref(),
10861            Some("Verified local delivery")
10862        );
10863        let snapshot = completion.run.as_ref().unwrap();
10864        assert_eq!(snapshot.id, state.id);
10865        assert_eq!(snapshot.status, Some(RunStatus::Ready));
10866        assert_eq!(
10867            RunState::load_under(&state.id, dir.path()).unwrap().status,
10868            RunStatus::Blocked,
10869            "settlement records the actual outcome without rewriting run history"
10870        );
10871    }
10872
10873    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
10874        Candidate {
10875            index: 0,
10876            label,
10877            agent: "claude".to_owned(),
10878            branch: format!("magi/x/{label}"),
10879            worktree: PathBuf::from("/repo"),
10880            summary: summary.to_owned(),
10881            stat: String::new(),
10882            files: 0,
10883            commits: usize::from(!empty),
10884            empty,
10885            failed: failed.map(str::to_owned),
10886            verified_noop: None,
10887            duration_ms: 0,
10888            folded: false,
10889        }
10890    }
10891
10892    #[test]
10893    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
10894        let mut state = run_state(RunStatus::Blocked);
10895        state.gate = vec![
10896            CommandOutcome {
10897                command: "cargo make check".to_owned(),
10898                code: Some(0),
10899                output_tail: "ok".to_owned(),
10900                duration_ms: 0,
10901                resource_blocked: false,
10902                ..Default::default()
10903            },
10904            CommandOutcome {
10905                command: "cargo test".to_owned(),
10906                code: Some(101),
10907                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
10908                duration_ms: 0,
10909                resource_blocked: false,
10910                ..Default::default()
10911            },
10912        ];
10913        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
10914        assert!(d.contains("cargo test"), "{d}");
10915        assert!(
10916            !d.contains("cargo make check"),
10917            "a passing check is not a diagnostic: {d}"
10918        );
10919        assert!(d.contains("assertion failed"), "{d}");
10920    }
10921
10922    #[test]
10923    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
10924        let mut state = run_state(RunStatus::Blocked);
10925        state.event(
10926            "land",
10927            "stopped: the fixer produced no commit while 2 check(s) were failing \
10928             (build, lint); stopping instead of looping on an unchanged tree",
10929        );
10930        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
10931        assert!(d.contains("build"), "{d}");
10932        assert!(d.contains("lint"), "{d}");
10933        assert!(d.contains("fixer produced no commit"), "{d}");
10934    }
10935
10936    #[test]
10937    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
10938        // `describe`'s output becomes `Task::last_error` verbatim, and the
10939        // phone renders that in the same alarm-styled box an ordinary
10940        // failure gets. A bare `verified_noop` there would read exactly like
10941        // the failure this status exists to be told apart from.
10942        let state = run_state(RunStatus::VerifiedNoop);
10943        let d = describe(&state);
10944        assert!(
10945            d.contains("agent-verified no-op"),
10946            "expected the display label, not the wire spelling: {d}"
10947        );
10948        assert!(!d.contains("verified_noop"), "{d}");
10949    }
10950
10951    #[test]
10952    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
10953        let mut state = run_state(RunStatus::Failed);
10954        state.gate.push(crate::run::CommandOutcome {
10955            command: "cargo test".into(),
10956            code: Some(101),
10957            output_tail: format!(
10958                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
10959                "  41: 0x1234 - backtrace frame\n".repeat(10000)
10960            ),
10961            duration_ms: 1,
10962            resource_blocked: false,
10963            ..Default::default()
10964        });
10965        let d = diagnostic(&state).unwrap();
10966        assert!(d.contains("panicked at widget.rs:12"), "{d}");
10967        assert!(d.contains("assertion failed: widget missing"));
10968        assert!(d.contains("widget log"));
10969    }
10970
10971    #[test]
10972    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
10973        // The whole point of the feature: a run held as "no candidate produced
10974        // a change" can mean the implementer actually finished the task and
10975        // only left a clean local tree behind - see AGENTS.md on this exact
10976        // failure mode. The diagnostic has to carry what the agent actually
10977        // said, not just the fact that nothing was there to judge.
10978        let mut state = run_state(RunStatus::Failed);
10979        state.candidates = vec![candidate(
10980            'A',
10981            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
10982            true,
10983            None,
10984        )];
10985        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
10986        assert!(d.contains("candidate A"), "{d}");
10987        assert!(d.contains("tagged v1.2.3"), "{d}");
10988    }
10989
10990    #[test]
10991    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
10992        let mut state = run_state(RunStatus::Failed);
10993        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
10994        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
10995        assert!(d.contains("candidate A"), "{d}");
10996        assert!(d.contains("agent timed out"), "{d}");
10997    }
10998
10999    #[test]
11000    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
11001        // A viable candidate existed, the gate never ran, and nothing land
11002        // said matches - `Task::last_error` is left to explain this one alone.
11003        let mut state = run_state(RunStatus::Failed);
11004        state.candidates = vec![candidate('A', "did the work", false, None)];
11005        assert!(diagnostic(&state).is_none());
11006    }
11007
11008    #[test]
11009    fn diagnostic_is_bounded_however_much_a_run_printed() {
11010        let mut state = run_state(RunStatus::Blocked);
11011        state.gate = vec![
11012            CommandOutcome {
11013                command: "cargo test".to_owned(),
11014                code: Some(101),
11015                output_tail: "x".repeat(50_000),
11016                duration_ms: 0,
11017                resource_blocked: false,
11018                ..Default::default()
11019            },
11020            CommandOutcome {
11021                command: "cargo clippy".to_owned(),
11022                code: Some(1),
11023                output_tail: "y".repeat(50_000),
11024                duration_ms: 0,
11025                resource_blocked: false,
11026                ..Default::default()
11027            },
11028        ];
11029        state.candidates = vec![
11030            candidate('A', &"z".repeat(50_000), true, None),
11031            candidate('B', &"w".repeat(50_000), true, None),
11032        ];
11033        let d = diagnostic(&state).expect("plenty here to diagnose");
11034        assert!(
11035            d.len() <= DIAGNOSTIC_MAX,
11036            "diagnostic grew to {} bytes, unbounded",
11037            d.len()
11038        );
11039    }
11040
11041    #[test]
11042    fn selected_delivery_guards_survive_recovery_failure_accounting() {
11043        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
11044            let mut t = task();
11045            let mut state = run_state(status);
11046            t.pr_recovery = Some(crate::pr_recovery::Selection {
11047                url: "url".into(),
11048                branch: format!("magi/task-{}", t.id),
11049                head: "a".repeat(40),
11050                source_head: None,
11051                source_run: None,
11052                source_proof: None,
11053                disposition: Some(crate::pr_recovery::Disposition::Land),
11054                instruction: t.instruction.clone(),
11055                approved_at: Timestamp::now(),
11056            });
11057            state.pr_recovery = t.pr_recovery.clone();
11058            t.start(state.id.clone());
11059            settle_and_diagnose(
11060                &mut t,
11061                Verdict {
11062                    status,
11063                    left_pr: false,
11064                    quota_hit: false,
11065                    parked: false,
11066                    no_viable_candidates: false,
11067                },
11068                "delivery stopped",
11069                5,
11070                &state,
11071            );
11072            assert_eq!(t.status, TaskStatus::Held);
11073            let reason = t.hold_reason.as_deref().unwrap();
11074            if status == RunStatus::Ready {
11075                assert!(reason.contains("Selected PR delivery is incomplete"));
11076                assert!(t.recovery_budget.is_none());
11077            } else {
11078                assert!(reason.contains("Selected recovery stopped"));
11079                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
11080            }
11081            assert!(t.pr_recovery.is_some());
11082        }
11083    }
11084
11085    #[test]
11086    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
11087        let mut state = run_state(RunStatus::Voting);
11088        state.base_sync = Some(crate::run::BaseSync {
11089            tip: "base-tip".into(),
11090            behind: 3,
11091            attempts: 4,
11092            conflict: Some("base stopped".into()),
11093            already_in: None,
11094        });
11095        state.record_base_sync_stop("candidate-head");
11096        let mut t = task();
11097        t.start(state.id.clone());
11098        let verdict = Verdict {
11099            status: RunStatus::Blocked,
11100            left_pr: false,
11101            quota_hit: false,
11102            parked: false,
11103            no_viable_candidates: false,
11104        };
11105        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
11106        assert_eq!(
11107            t.status,
11108            TaskStatus::Held,
11109            "unspent task attempts cannot start another competition"
11110        );
11111        let at = t.held_at;
11112        let cause = t.hold_notice_cause.clone();
11113        state.begin_pass();
11114        t.release_operator("test-resume", None);
11115        t.start(state.id.clone());
11116        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
11117        assert_eq!(t.status, TaskStatus::Held);
11118        assert_eq!(t.held_at, at);
11119        assert_eq!(t.hold_notice_cause, cause);
11120    }
11121
11122    #[test]
11123    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
11124        let mut state = run_state(RunStatus::Blocked);
11125        state.gate = vec![CommandOutcome {
11126            command: "cargo test".to_owned(),
11127            code: Some(101),
11128            output_tail: "assertion failed".to_owned(),
11129            duration_ms: 0,
11130            resource_blocked: false,
11131            ..Default::default()
11132        }];
11133        let verdict = Verdict {
11134            status: RunStatus::Blocked,
11135            left_pr: false,
11136            quota_hit: false,
11137            parked: false,
11138            no_viable_candidates: false,
11139        };
11140
11141        // Attempt one of two still has a retry coming: no diagnostic yet, the
11142        // task is going to run again and this run's evidence would go stale.
11143        let mut t = task();
11144        t.start("run-1".to_owned());
11145        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
11146        assert_eq!(t.status, TaskStatus::Failed);
11147        assert!(t.diagnostic.is_none());
11148
11149        // Attempt two exhausts the budget: now it is held, and the
11150        // diagnostic is what `magi task show` has to say more than one line.
11151        t.start("run-2".to_owned());
11152        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
11153        assert_eq!(t.status, TaskStatus::Held);
11154        let d = t.diagnostic.expect("a held task must carry its diagnostic");
11155        assert!(d.contains("cargo test"), "{d}");
11156    }
11157
11158    fn verified_noop_run_state() -> RunState {
11159        let mut state = run_state(RunStatus::VerifiedNoop);
11160        let summary = r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"requested fix already landed","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"commit","target":"b32cfc4","method":"git merge-base --is-ancestor b32cfc4 HEAD","observed":"exit 0; b32cfc4 is on main","passed":true}],"unresolved":[]}"#;
11161        let mut c = candidate('A', summary, true, None);
11162        c.verified_noop = Some(summary.to_owned());
11163        state.candidates = vec![c];
11164        state
11165    }
11166
11167    #[test]
11168    fn a_held_task_names_the_open_question_it_is_waiting_on() {
11169        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
11170        // `magi ask` question settled Held with `hold_reason: null`, so the
11171        // notification said nothing actionable. `note_open_question` should
11172        // append the question id to whatever `handed_off` already wrote.
11173        crate::run::pin_test_home();
11174        let home = crate::run::home();
11175        let state = verified_noop_run_state();
11176        let mut q = ask::Question::new(
11177            state.id.clone(),
11178            "implement".to_owned(),
11179            "impl-A".to_owned(),
11180            "is this really a no-op?".to_owned(),
11181            String::new(),
11182            Vec::new(),
11183        );
11184        Questions::at(home.join("questions")).put(&mut q).unwrap();
11185
11186        let verdict = Verdict {
11187            status: RunStatus::VerifiedNoop,
11188            left_pr: false,
11189            quota_hit: false,
11190            parked: false,
11191            no_viable_candidates: true,
11192        };
11193        let mut t = task();
11194        t.start(state.id.clone());
11195        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
11196
11197        assert_eq!(t.status, TaskStatus::Held);
11198        let reason = t.hold_reason.expect("a held task must record why");
11199        assert!(
11200            reason.starts_with("run ended agent-verified no-op"),
11201            "the original settle reason must survive unchanged: {reason}"
11202        );
11203        assert!(
11204            reason.contains(q.short()),
11205            "the open question's id must be named so the notice is actionable: {reason}"
11206        );
11207    }
11208
11209    #[test]
11210    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
11211        crate::run::pin_test_home();
11212        let state = verified_noop_run_state();
11213
11214        let verdict = Verdict {
11215            status: RunStatus::VerifiedNoop,
11216            left_pr: false,
11217            quota_hit: false,
11218            parked: false,
11219            no_viable_candidates: true,
11220        };
11221        let mut t = task();
11222        t.start(state.id.clone());
11223        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
11224
11225        assert_eq!(t.status, TaskStatus::Held);
11226        assert_eq!(
11227            t.hold_reason.as_deref(),
11228            Some("run ended agent-verified no-op"),
11229            "nothing to append when the question was already answered or never asked"
11230        );
11231    }
11232
11233    #[test]
11234    fn inconsistent_verified_noop_state_settles_and_reclaims_as_ordinary_failure() {
11235        crate::run::pin_test_home();
11236
11237        // Case 1: Saved `VerifiedNoop` run carrying the exact operational
11238        // regression prose instead of valid structured evidence.
11239        let mut bad = run_state(RunStatus::VerifiedNoop);
11240        let mut c = candidate(
11241            'A',
11242            "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.",
11243            true,
11244            None,
11245        );
11246        c.verified_noop = Some("Not established.".to_owned());
11247        bad.candidates = vec![c];
11248
11249        let mut t = task();
11250        t.start(bad.id.clone());
11251        let verdict = Verdict {
11252            status: RunStatus::VerifiedNoop,
11253            left_pr: false,
11254            quota_hit: true,
11255            parked: false,
11256            no_viable_candidates: true,
11257        };
11258        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 3, &bad);
11259        assert_eq!(
11260            t.status,
11261            TaskStatus::Failed,
11262            "inconsistent verified_noop must retry as Failed when attempts remain"
11263        );
11264        assert_eq!(t.attempts, 1);
11265        assert_eq!(
11266            t.last_error.as_deref(),
11267            Some("no-change result lacks verified evidence")
11268        );
11269        assert!(t.hold_reason.is_none());
11270
11271        // Case 2: Reclaim on an inconsistent `VerifiedNoop` state with
11272        // attempts exhausted holds as `failed`, never `verified_noop`, and
11273        // never auto-closes to `Done`.
11274        let mut t_exhausted = task();
11275        t_exhausted.start(bad.id.clone());
11276        reclaim(&mut t_exhausted, Some(bad.clone()), 1, "en");
11277        assert_eq!(t_exhausted.status, TaskStatus::Held);
11278        assert_eq!(t_exhausted.attempts, 1);
11279        assert_eq!(
11280            t_exhausted
11281                .hold_notice_cause
11282                .as_ref()
11283                .map(|c| c.stage.as_str()),
11284            Some("failed"),
11285            "exhausted inconsistent verified_noop must not emit a verified_noop notice cause"
11286        );
11287        let diag = t_exhausted.diagnostic.as_deref().unwrap_or("");
11288        assert!(
11289            !diag.contains("agent-verified no-op"),
11290            "diagnostic must not mislabel an invalid claim as verified no-op: {diag}"
11291        );
11292        assert!(diag.contains("Not established"), "{diag}");
11293    }
11294
11295    #[test]
11296    fn saved_noop_declaration_is_the_evidence_not_the_display_summary() {
11297        let mut state = verified_noop_run_state();
11298        let summary = state.candidates[0].summary.clone();
11299        state.candidates[0].summary = "Already satisfied.".to_owned();
11300        assert!(state.all_candidates_verified_noop());
11301
11302        state.candidates[0].summary = summary;
11303        state.candidates[0].verified_noop = Some("Historical prose only.".to_owned());
11304        assert!(!state.all_candidates_verified_noop());
11305    }
11306
11307    #[test]
11308    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
11309        crate::run::pin_test_home();
11310        let mut first = run_state(RunStatus::Blocked);
11311        first.id = "20260101-000000-sup1".to_owned();
11312        first.save().unwrap();
11313        let mut second = run_state(RunStatus::Merged);
11314        second.id = "20260101-000000-sup2".to_owned();
11315        second.save().unwrap();
11316
11317        let mut t = task();
11318        t.runs = vec![first.id.clone(), second.id.clone()];
11319        t.status = TaskStatus::Done;
11320
11321        supersede_prior_runs(&t, &crate::run::home());
11322
11323        assert_eq!(
11324            RunState::load(&first.id).unwrap().status,
11325            RunStatus::Superseded,
11326            "the first attempt's Blocked no longer needs anyone's attention"
11327        );
11328        assert_eq!(
11329            RunState::load(&second.id).unwrap().status,
11330            RunStatus::Merged,
11331            "the run that actually succeeded is left exactly as it was"
11332        );
11333    }
11334
11335    #[test]
11336    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
11337        // `is_working_on` alone only proves a *daemon* claim; a `magi run
11338        // --resume` invoked by hand outside the daemon never touches
11339        // `daemon.json` at all, so it would look identical to a genuinely
11340        // idle run without also consulting `RunState::liveness`, which reads
11341        // this run's own recorded `driver_pid` instead.
11342        crate::run::pin_test_home();
11343        let mut first = run_state(RunStatus::Blocked);
11344        first.id = "20260101-000000-sup9".to_owned();
11345        // This test process's own pid: guaranteed alive without needing a
11346        // real second process or daemon.
11347        first.driver_pid = Some(std::process::id());
11348        first.driver_started_at = Some(
11349            crate::proc::process_started_at(std::process::id())
11350                .expect("this test process's own start time must be queryable"),
11351        );
11352        first.save().unwrap();
11353        let mut second = run_state(RunStatus::Merged);
11354        second.id = "20260101-000000-supa".to_owned();
11355        second.save().unwrap();
11356
11357        let mut t = task();
11358        t.runs = vec![first.id.clone(), second.id.clone()];
11359        t.status = TaskStatus::Done;
11360
11361        supersede_prior_runs(&t, &crate::run::home());
11362
11363        assert_eq!(
11364            RunState::load(&first.id).unwrap().status,
11365            RunStatus::Blocked,
11366            "a live driver_pid means something is still actually working this run, \
11367             even though no daemon claims it - rewriting under it would just be \
11368             undone the next time that process saves"
11369        );
11370    }
11371
11372    #[test]
11373    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
11374        // The first resweep must skip a still-live attempt exactly like
11375        // `supersede_prior_runs` itself does; a later resweep, once that
11376        // process is no longer actually driving it, is what closes the gap
11377        // `supersede_prior_runs` alone leaves - a task only ever reaches
11378        // `Done` once, so nothing else would ever look at this run again.
11379        let dir = tempfile::tempdir().unwrap();
11380        let home = dir.path().to_path_buf();
11381        let queue = Queue::at(dir.path().join("queue"));
11382
11383        let mut first = run_state(RunStatus::Blocked);
11384        first.id = "20260101-000000-supd".to_owned();
11385        first.driver_pid = Some(std::process::id());
11386        first.driver_started_at = Some(
11387            crate::proc::process_started_at(std::process::id())
11388                .expect("this test process's own start time must be queryable"),
11389        );
11390        first.save_under(&home).unwrap();
11391        let mut second = run_state(RunStatus::Merged);
11392        second.id = "20260101-000000-supe".to_owned();
11393        second.save_under(&home).unwrap();
11394
11395        let mut t = task();
11396        t.runs = vec![first.id.clone(), second.id.clone()];
11397        t.status = TaskStatus::Done;
11398        queue.put(&mut t).unwrap();
11399
11400        resweep_superseded_attempts(&queue, &home);
11401        assert_eq!(
11402            RunState::load_under(&first.id, &home).unwrap().status,
11403            RunStatus::Blocked,
11404            "still live on the first pass, so still untouched"
11405        );
11406
11407        // Stand in for the manual process no longer being the one driving
11408        // this run: same pid (this test process really is still alive), but
11409        // an identity marker that no longer matches it - see
11410        // `RunState::liveness`'s own doc for why a mismatched
11411        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
11412        let mut stale = RunState::load_under(&first.id, &home).unwrap();
11413        stale.driver_started_at = Some("1".to_owned());
11414        stale.save_under(&home).unwrap();
11415
11416        resweep_superseded_attempts(&queue, &home);
11417        assert_eq!(
11418            RunState::load_under(&first.id, &home).unwrap().status,
11419            RunStatus::Superseded,
11420            "the second pass catches up what the first one correctly skipped"
11421        );
11422    }
11423
11424    #[test]
11425    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
11426        crate::run::pin_test_home();
11427        let mut first = run_state(RunStatus::Blocked);
11428        first.id = "20260101-000000-sup3".to_owned();
11429        first.save().unwrap();
11430        let mut second = run_state(RunStatus::Blocked);
11431        second.id = "20260101-000000-sup4".to_owned();
11432        second.save().unwrap();
11433
11434        let mut t = task();
11435        t.runs = vec![first.id.clone(), second.id.clone()];
11436        // Still retrying: nothing about this task's story is settled yet, so
11437        // neither Blocked run may be relabelled, even though a later attempt
11438        // already exists.
11439        t.status = TaskStatus::Failed;
11440
11441        supersede_prior_runs(&t, &crate::run::home());
11442
11443        assert_eq!(
11444            RunState::load(&first.id).unwrap().status,
11445            RunStatus::Blocked
11446        );
11447        assert_eq!(
11448            RunState::load(&second.id).unwrap().status,
11449            RunStatus::Blocked
11450        );
11451    }
11452
11453    #[test]
11454    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
11455        // `magi task done` (or the API's equivalent) can close a task with no
11456        // run of its own ever having succeeded - there is nothing here that
11457        // counts as "the attempt that finished it", so nothing is rewritten.
11458        crate::run::pin_test_home();
11459        let mut first = run_state(RunStatus::Blocked);
11460        first.id = "20260101-000000-sup5".to_owned();
11461        first.save().unwrap();
11462
11463        let mut t = task();
11464        t.runs = vec![first.id.clone()];
11465        t.status = TaskStatus::Done;
11466
11467        supersede_prior_runs(&t, &crate::run::home());
11468
11469        assert_eq!(
11470            RunState::load(&first.id).unwrap().status,
11471            RunStatus::Blocked,
11472            "a single-attempt task has no earlier run to supersede"
11473        );
11474    }
11475
11476    #[test]
11477    fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
11478        for status in [
11479            RunStatus::Blocked,
11480            RunStatus::Stalled,
11481            RunStatus::Failed,
11482            RunStatus::Ready,
11483            RunStatus::Merged,
11484        ] {
11485            let dir = tempfile::tempdir().unwrap();
11486            let home = dir.path();
11487            let mut first = run_state(RunStatus::Blocked);
11488            first.id = "20260101-000000-supb".to_owned();
11489            first.save_under(home).unwrap();
11490            let mut second = run_state(status);
11491            second.id = "20260101-000000-supc".to_owned();
11492            second.save_under(home).unwrap();
11493
11494            let mut t = task();
11495            t.runs = vec![first.id.clone(), second.id.clone()];
11496            t.hold_manual(Some("Unmerged work remains".into()));
11497            let mut context = CompletionContext::new(
11498                CompletionActor::Cli,
11499                Some("Discard the unmerged attempts".into()),
11500                home,
11501                &t,
11502            );
11503            context.discard = true;
11504            t.succeed(context);
11505            assert_eq!(t.completion_history.len(), 1);
11506
11507            supersede_prior_runs(&t, home);
11508
11509            assert_eq!(
11510                RunState::load_under(&first.id, home).unwrap().status,
11511                RunStatus::Blocked,
11512                "an audited manual close is not proof the earlier work landed"
11513            );
11514            assert_eq!(
11515                RunState::load_under(&second.id, home).unwrap().status,
11516                status,
11517                "the latest attempt retains its actual outcome"
11518            );
11519        }
11520    }
11521
11522    #[test]
11523    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
11524        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
11525        // to look" - `Failed` and `VerifiedNoop` are already their own
11526        // terminal answers and must not be relabelled into a third one.
11527        crate::run::pin_test_home();
11528        let mut failed = run_state(RunStatus::Failed);
11529        failed.id = "20260101-000000-sup6".to_owned();
11530        failed.save().unwrap();
11531        let mut noop = run_state(RunStatus::VerifiedNoop);
11532        noop.id = "20260101-000000-sup7".to_owned();
11533        noop.save().unwrap();
11534        let mut winner = run_state(RunStatus::Ready);
11535        winner.id = "20260101-000000-sup8".to_owned();
11536        winner.save().unwrap();
11537
11538        let mut t = task();
11539        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
11540        t.status = TaskStatus::Done;
11541
11542        supersede_prior_runs(&t, &crate::run::home());
11543
11544        assert_eq!(
11545            RunState::load(&failed.id).unwrap().status,
11546            RunStatus::Failed
11547        );
11548        assert_eq!(
11549            RunState::load(&noop.id).unwrap().status,
11550            RunStatus::VerifiedNoop
11551        );
11552    }
11553
11554    fn approval_question(run: &str) -> ask::Question {
11555        ask::Question::new(
11556            run.to_owned(),
11557            land::APPROVAL_NODE.to_owned(),
11558            "land".to_owned(),
11559            "merge?".to_owned(),
11560            String::new(),
11561            vec!["merge".to_owned(), "hold".to_owned()],
11562        )
11563    }
11564
11565    #[test]
11566    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
11567        crate::run::pin_test_home();
11568        let mut state = run_state(RunStatus::Landing);
11569        state.id = "20260101-000000-fre1".to_owned();
11570        state.parked = true;
11571        state.save().unwrap();
11572        ask::Questions::open()
11573            .put(&mut approval_question(&state.id))
11574            .unwrap();
11575
11576        let mut t = task();
11577        t.runs.push(state.id.clone());
11578        assert_eq!(
11579            land_resume_state(&t),
11580            LandResume::StillWaiting,
11581            "nobody has answered and the timeout has not passed"
11582        );
11583    }
11584
11585    #[test]
11586    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
11587        crate::run::pin_test_home();
11588        let mut state = run_state(RunStatus::Gating);
11589        state.id = "20260101-000000-gt01".to_owned();
11590        state.parked = true;
11591        state.config.graph.answer_timeout = 60;
11592        state.github_text = Some(crate::run::GithubTextAsk {
11593            rewrite: None,
11594            fingerprint: "f".into(),
11595            title: true,
11596            body: false,
11597            categories: vec!["title-language".into()],
11598            question: None,
11599            asks: 1,
11600            resolved: false,
11601            chosen_title: None,
11602            choice: None,
11603            publication: None,
11604        });
11605        state.save().unwrap();
11606        let store = ask::Questions::open();
11607        let mut q = ask::Question::new(
11608            state.id.clone(),
11609            crate::github_text::ASK_NODE.to_owned(),
11610            crate::github_text::ASK_SEAT.to_owned(),
11611            "s".into(),
11612            String::new(),
11613            vec!["use fallback".into()],
11614        );
11615        store.put(&mut q).unwrap();
11616        let mut t = task();
11617        t.runs.push(state.id.clone());
11618        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
11619        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
11620        store.put(&mut q).unwrap();
11621        assert_eq!(land_resume_state(&t), LandResume::Ready);
11622        assert!(!store.get(&q.id).unwrap().status.open());
11623        // Once decided, a parked run is an ordinary candidate again.
11624        state.github_text.as_mut().unwrap().resolved = true;
11625        state.save().unwrap();
11626        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
11627    }
11628
11629    #[test]
11630    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
11631        // `ask::ask_and_wait`'s own deadline used to retire a question
11632        // nobody answered; land's approval bypasses that wait (see
11633        // `land::approval_gate`), so this is now the only place
11634        // `graph.answer_timeout` is enforced for a land approval at all.
11635        crate::run::pin_test_home();
11636        let mut state = run_state(RunStatus::Landing);
11637        state.id = "20260101-000000-exp1".to_owned();
11638        state.parked = true;
11639        state.config.graph.answer_timeout = 60;
11640        state.save().unwrap();
11641
11642        let store = ask::Questions::open();
11643        let mut q = approval_question(&state.id);
11644        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
11645        store.put(&mut q).unwrap();
11646
11647        let mut t = task();
11648        t.runs.push(state.id.clone());
11649        assert_eq!(
11650            land_resume_state(&t),
11651            LandResume::Ready,
11652            "an expired question must not be waited on forever"
11653        );
11654
11655        let after = store.get(&q.id).unwrap();
11656        assert!(
11657            !after.status.open(),
11658            "the question is abandoned, not silently ignored"
11659        );
11660        assert!(
11661            after.resolution().is_none(),
11662            "an abandoned question is not read as a decision"
11663        );
11664    }
11665
11666    #[test]
11667    fn reclaim_settles_a_running_task_against_its_last_run() {
11668        let mut t = task();
11669        t.start("20260904-000000-4043".to_owned());
11670        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
11671        assert_eq!(
11672            t.status,
11673            TaskStatus::Done,
11674            "a run that actually finished must not stay `running` forever"
11675        );
11676    }
11677
11678    #[test]
11679    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
11680        let dir = tempfile::tempdir().unwrap();
11681        let queue = Queue::at(dir.path().join("queue"));
11682        let mut task = task();
11683        let mut run = run_state(RunStatus::Blocked);
11684        run.reserve_under(dir.path()).unwrap();
11685        run.driver_exited = true;
11686        run.save_under(dir.path()).unwrap();
11687        queue.put(&mut task).unwrap();
11688        let stale = task.clone();
11689        task.resume_override = Some(crate::queue::OperatorResume {
11690            question_id: "pending-resume".into(),
11691            at: Timestamp::now(),
11692            conductor_rehold: None,
11693            forced: true,
11694            pinned_run: Some(run.id.clone()),
11695        });
11696        task.start(run.id.clone());
11697        queue.put(&mut task).unwrap();
11698        // Discard every in-memory handoff, as a worker death before execute does.
11699        let mut recovered = queue.get(&task.id).unwrap();
11700        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
11701        reclaim(&mut recovered, Some(disk), 2, "en");
11702        queue.put(&mut recovered).unwrap();
11703        assert!(recovered.resume_override.is_none());
11704        assert_eq!(
11705            recovered.dispatched_resumes.get("pending-resume"),
11706            Some(&run.id)
11707        );
11708        let mut stale = stale;
11709        queue.put(&mut stale).unwrap();
11710        assert_eq!(
11711            stale.dispatched_resumes, recovered.dispatched_resumes,
11712            "a stale task writer cannot erase dispatch ownership"
11713        );
11714        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
11715        assert!(resumed.decision_starts.is_empty());
11716        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
11717        assert!(
11718            resumed.decision_starts.is_empty(),
11719            "handoff is not execution proof"
11720        );
11721        resumed.begin_pass();
11722        resumed.save_under(dir.path()).unwrap();
11723        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
11724        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
11725        disk.carry_dispatched_resumes(&recovered);
11726        disk.begin_pass();
11727        assert_eq!(
11728            disk.decision_starts.get("pending-resume"),
11729            Some(&0),
11730            "later execution must preserve the original pass receipt"
11731        );
11732    }
11733
11734    #[test]
11735    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
11736        let mut t = task();
11737        t.start("20260904-000000-4043".to_owned());
11738        t.last_error = Some("earlier trouble".to_owned());
11739        let mut state = run_state(RunStatus::Judging);
11740        state.parked = true;
11741        reclaim(&mut t, Some(state), 1, "en");
11742        assert_eq!(t.status, TaskStatus::Parked);
11743        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
11744        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
11745        assert!(t.park_reason.is_some());
11746        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
11747        assert!(!t.fresh_start);
11748        assert!(t.status.runnable());
11749    }
11750
11751    #[test]
11752    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
11753        let mut t = task();
11754        t.start("20260904-000000-4043".to_owned());
11755        t.last_error = Some("earlier trouble".to_owned());
11756        settle(
11757            &mut t,
11758            Verdict {
11759                status: RunStatus::Judging,
11760                left_pr: false,
11761                quota_hit: false,
11762                parked: true,
11763                no_viable_candidates: false,
11764            },
11765            "parked after `judging`",
11766            1,
11767        );
11768        assert_eq!(t.status, TaskStatus::Parked);
11769        assert_eq!(t.attempts, 0);
11770        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
11771        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
11772        assert_eq!(t.schema, crate::queue::SCHEMA);
11773        assert!(
11774            crate::notices::task_held(&t).is_none(),
11775            "a park is not news"
11776        );
11777        t.start("20260904-000000-4043".to_owned());
11778        assert_eq!(t.park_reason, None);
11779    }
11780
11781    #[test]
11782    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
11783        // A blocked run with attempts left goes back to `Failed`, exactly as
11784        // it would from `attempt` itself - `reclaim` must not invent a second
11785        // policy for a task a daemon merely stopped without reporting.
11786        let mut t = task();
11787        t.start("20260904-000000-4043".to_owned());
11788        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
11789        assert_eq!(t.status, TaskStatus::Failed);
11790        assert!(t.status.runnable());
11791    }
11792
11793    #[test]
11794    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
11795        let mut t = task();
11796        t.start("20260904-000000-4043".to_owned());
11797        assert_eq!(t.attempts, 1);
11798        let mut run = run_state(RunStatus::Implementing);
11799        run.id = "20260904-000000-4043".to_owned();
11800        run.begin_pass();
11801        let cause = crate::run::ParkCause::Upgrade {
11802            from: "0.121.0".to_owned(),
11803            to: Some("0.121.1".to_owned()),
11804        };
11805        run.end_pass_parked(cause.clone());
11806        run.parked = true;
11807        let verdict = Verdict {
11808            status: run.status,
11809            left_pr: false,
11810            quota_hit: false,
11811            parked: true,
11812            no_viable_candidates: false,
11813        };
11814        // A crash after the checkpoint but before queue settlement must
11815        // recover exactly the same scheduling evidence and refund.
11816        let mut orphan = t.clone();
11817        reclaim(&mut orphan, Some(run.clone()), 2, "en");
11818        assert_eq!(orphan.status, TaskStatus::Parked);
11819        assert_eq!(orphan.attempts, 0);
11820        assert_eq!(
11821            orphan.upgrade_resume_key(),
11822            Some((run.passes[0].started_at, orphan.id.as_str()))
11823        );
11824        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
11825        assert_eq!(t.attempts, 0);
11826        assert_eq!(t.passes.len(), 1);
11827        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
11828        assert_eq!(t.passes[0].parked, Some(cause));
11829        assert_eq!(t.passes[0].pass_index, 0);
11830        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
11831        assert!(t.upgrade_resume_key().is_some());
11832
11833        // A resumed pass that then fails spends its attempt, and the earlier
11834        // pass's entry is untouched.
11835        t.start("20260904-000000-4043".to_owned());
11836        run.begin_pass();
11837        run.status = RunStatus::Failed;
11838        let verdict = Verdict {
11839            status: RunStatus::Failed,
11840            left_pr: false,
11841            quota_hit: false,
11842            parked: false,
11843            no_viable_candidates: false,
11844        };
11845        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
11846        assert_eq!(t.passes.len(), 2);
11847        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
11848        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
11849        assert_eq!(t.passes[1].pass_index, 1);
11850        assert_eq!(t.attempts, 1);
11851    }
11852
11853    #[test]
11854    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
11855        let mut t = task();
11856        t.start("20260904-000000-4043".to_owned());
11857        reclaim(&mut t, None, 2, "en");
11858        assert_eq!(t.status, TaskStatus::Held);
11859        assert!(
11860            t.last_error
11861                .as_deref()
11862                .is_some_and(|e| e.contains("running")),
11863            "the operator needs to know why this task was held"
11864        );
11865    }
11866
11867    #[test]
11868    fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
11869        let dir = tempfile::tempdir().unwrap();
11870        let queue = Queue::at(dir.path().to_path_buf());
11871        let mut task = task();
11872        let run = "20261124-000000-dead";
11873        task.link_run(run);
11874        task.attempts = 2;
11875        task.status = TaskStatus::Running;
11876        task.sync_only = Some(crate::base_sync_only::Request {
11877            run: run.into(),
11878            at: Timestamp::now(),
11879        });
11880        queue.put(&mut task).unwrap();
11881        assert_eq!(
11882            reclaim_orphaned_running(&queue, 3, &Default::default()),
11883            vec![task.id.clone()]
11884        );
11885        let saved = queue.get(&task.id).unwrap();
11886        assert_eq!(saved.status, TaskStatus::Held);
11887        assert_eq!(saved.attempts, 2);
11888        assert_eq!(saved.execution_runs(), [run]);
11889        assert!(
11890            saved
11891                .last_error
11892                .unwrap()
11893                .contains("verification was not allowed")
11894        );
11895        assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
11896    }
11897
11898    #[test]
11899    fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
11900        use crate::base_sync_only::{Outcome, Pass, Request};
11901
11902        let mut state = run_state(RunStatus::Blocked);
11903        let mut task = task();
11904        let request = Request {
11905            run: state.id.clone(),
11906            at: Timestamp::now(),
11907        };
11908        task.start(state.id.clone());
11909        task.sync_only = Some(request.clone());
11910        // Dedicated dispatch saves Running with the pre-pass attempt count.
11911        task.attempts = 2;
11912        let mut pass = Pass::new(request, &state);
11913        pass.result = Outcome::AlreadyCurrent;
11914        state.sync_only_passes.push(pass);
11915        state.begin_pass();
11916
11917        reclaim(&mut task, Some(state), 3, "en");
11918
11919        assert_eq!(task.status, TaskStatus::Held);
11920        assert_eq!(task.attempts, 2);
11921        assert!(task.sync_only.is_none());
11922        let detail = task.hold_reason.unwrap();
11923        assert!(detail.contains("HEAD already contains the base"));
11924        assert!(detail.contains("verification was not allowed"));
11925    }
11926
11927    #[test]
11928    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
11929        let dir = tempfile::tempdir().unwrap();
11930        let queue = Queue::at(dir.path().to_path_buf());
11931
11932        // No run recorded, so this never has to touch `RunState::load`.
11933        let mut orphaned = task();
11934        orphaned.id = "20260904-000000-orph".to_owned();
11935        orphaned.status = TaskStatus::Running;
11936        orphaned.attempts = 1;
11937        queue.put(&mut orphaned).unwrap();
11938
11939        let mut alive = task();
11940        alive.id = "20260904-000000-live".to_owned();
11941        alive.status = TaskStatus::Running;
11942        alive.attempts = 1;
11943        queue.put(&mut alive).unwrap();
11944        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
11945
11946        let mut queued = task();
11947        queued.id = "20260904-000000-wait".to_owned();
11948        queue.put(&mut queued).unwrap();
11949
11950        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
11951        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
11952
11953        assert_eq!(
11954            queue.get(&orphaned.id).unwrap().status,
11955            TaskStatus::Held,
11956            "nothing was driving it and there was no run to recover"
11957        );
11958        assert_eq!(
11959            queue.get(&alive.id).unwrap().status,
11960            TaskStatus::Running,
11961            "a live claim must protect the task it belongs to"
11962        );
11963        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
11964    }
11965
11966    /// Read a run.json back from an explicit `home`, the same way
11967    /// `reclaim_abandoned_runs` itself does - never through the
11968    /// process-global `RunState::load`, which this test's own `home` (an
11969    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
11970    /// use at all.
11971    fn read_run_under(home: &Path, id: &str) -> RunState {
11972        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
11973        serde_json::from_str(&body).unwrap()
11974    }
11975
11976    #[test]
11977    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
11978        let dir = tempfile::tempdir().unwrap();
11979        let home = dir.path().to_path_buf();
11980        let now = Timestamp::now();
11981        let overrun_seat = || crate::run::ActiveSeat {
11982            node: "implement".to_owned(),
11983            started_at: now - jiff::SignedDuration::new(21_000, 0),
11984            timeout_secs: 3_600,
11985            attempt: 0,
11986            task: None,
11987            command: None,
11988            index: None,
11989            total: None,
11990        };
11991
11992        let mut dead = run_state(RunStatus::Implementing);
11993        dead.id = "20260101-000000-dead".to_owned();
11994        dead.active.insert("impl-A".to_owned(), overrun_seat());
11995        // A `driver_pid` the injected query below confirms gone outright —
11996        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
11997        dead.driver_pid = Some(4242);
11998        dead.save_under(&home).unwrap();
11999
12000        // Same shape, but a live daemon's heartbeat names it: must be left
12001        // exactly alone, however far past its own timeout the seat sits.
12002        let mut alive = run_state(RunStatus::Implementing);
12003        alive.id = "20260101-000000-aliv".to_owned();
12004        alive.active.insert("impl-A".to_owned(), overrun_seat());
12005        alive.save_under(&home).unwrap();
12006        let mut status = Status::new();
12007        status.current = vec![Current {
12008            worker: None,
12009            task: "20260101-000000-task".to_owned(),
12010            run: alive.id.clone(),
12011        }];
12012        write_status_to(&home.join("daemon.json"), &status).unwrap();
12013
12014        // The abandoned seat left an open question behind: nobody is left to
12015        // read an answer once the run is failed, and this must not wait for
12016        // some later daemon startup's own sweep to notice that.
12017        let questions = Questions::at(home.join("questions"));
12018        let mut q = ask::Question::new(
12019            dead.id.clone(),
12020            "implement".to_owned(),
12021            "impl-A".to_owned(),
12022            "Which storage backend?".to_owned(),
12023            String::new(),
12024            vec!["SQLite".to_owned(), "Redis".to_owned()],
12025        );
12026        questions.put(&mut q).unwrap();
12027
12028        let abandoned = reclaim_abandoned_runs_with(
12029            &home,
12030            now,
12031            |pid| if pid == 4242 { Some(false) } else { None },
12032            |_| panic!("a query answering Dead outright needs no identity corroboration"),
12033        );
12034        assert_eq!(abandoned, vec![dead.id.clone()]);
12035
12036        let reloaded = read_run_under(&home, &dead.id);
12037        assert_eq!(reloaded.status, RunStatus::Failed);
12038        assert!(reloaded.active.is_empty());
12039        assert!(
12040            !questions.get(&q.id).unwrap().status.open(),
12041            "the failed run's own open question must be settled in the same pass"
12042        );
12043
12044        let still_alive = read_run_under(&home, &alive.id);
12045        assert_eq!(
12046            still_alive.status,
12047            RunStatus::Implementing,
12048            "a live daemon's claim protects it"
12049        );
12050        assert!(!still_alive.active.is_empty());
12051    }
12052
12053    /// The exact shape a review round flagged as broken: `magi serve` running
12054    /// in this same `home` scans *every* run on disk, including a manual
12055    /// `magi review` / `magi run` this daemon never started and that
12056    /// therefore claims no heartbeat of its own. Before this scan asked
12057    /// `liveness` rather than just `is_working_on`, a manual run whose active
12058    /// seat merely ran a little past its own timeout — the CLI finishing up,
12059    /// its result still being collected — got wiped and failed by a daemon
12060    /// that had nothing to do with it, out from under a process that was
12061    /// still very much running.
12062    #[test]
12063    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
12064        let dir = tempfile::tempdir().unwrap();
12065        let home = dir.path().to_path_buf();
12066        let now = Timestamp::now();
12067
12068        let mut manual = run_state(RunStatus::Reviewing);
12069        manual.id = "20260101-000000-manl".to_owned();
12070        manual.active.insert(
12071            "review-1".to_owned(),
12072            crate::run::ActiveSeat {
12073                node: "review".to_owned(),
12074                started_at: now - jiff::SignedDuration::new(21_000, 0),
12075                timeout_secs: 3_600,
12076                attempt: 0,
12077                task: None,
12078                command: None,
12079                index: None,
12080                total: None,
12081            },
12082        );
12083        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
12084        // but a real, still-running process: `liveness` must corroborate this
12085        // as `Live`, not read the missing daemon claim as death.
12086        manual.driver_pid = Some(4242);
12087        manual.driver_started_at = Some("1790000000".to_owned());
12088        manual.save_under(&home).unwrap();
12089
12090        let abandoned = reclaim_abandoned_runs_with(
12091            &home,
12092            now,
12093            |pid| if pid == 4242 { Some(true) } else { None },
12094            |pid| {
12095                if pid == 4242 {
12096                    Some("1790000000".to_owned())
12097                } else {
12098                    None
12099                }
12100            },
12101        );
12102        assert!(
12103            abandoned.is_empty(),
12104            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
12105        );
12106
12107        let reloaded = read_run_under(&home, &manual.id);
12108        assert_eq!(reloaded.status, RunStatus::Reviewing);
12109        assert!(!reloaded.active.is_empty());
12110    }
12111
12112    #[test]
12113    fn an_already_claimed_task_is_skipped_rather_than_failed() {
12114        let dir = tempfile::tempdir().unwrap();
12115        let queue = Queue::at(dir.path().to_path_buf());
12116        let mut only = task();
12117        queue.put(&mut only).unwrap();
12118
12119        let _elsewhere = queue.claim(&only.id).unwrap();
12120        let candidates = runnable(&queue);
12121        assert_eq!(candidates.len(), 1, "the task is still runnable");
12122        assert!(
12123            queue.claim(&candidates[0].id).is_err(),
12124            "the loop cannot take a claim somebody else holds"
12125        );
12126
12127        let after = queue.get(&only.id).unwrap();
12128        assert_eq!(after.status, TaskStatus::Queued);
12129        assert_eq!(
12130            after.attempts, 0,
12131            "losing the race is not an attempt at the task"
12132        );
12133        assert_eq!(after.last_error, None);
12134    }
12135
12136    #[test]
12137    fn the_status_file_round_trips_and_its_heartbeat_advances() {
12138        let dir = tempfile::tempdir().unwrap();
12139        let path = dir.path().join("daemon.json");
12140
12141        let mut status = Status::new();
12142        status.idle = false;
12143        status.completed = 7;
12144        status.current = vec![Current {
12145            worker: None,
12146            task: "20260902-000000-t111".to_owned(),
12147            run: "20260902-000001-r111".to_owned(),
12148        }];
12149        write_status_to(&path, &status).unwrap();
12150        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
12151        assert_eq!(first.schema, SCHEMA);
12152        assert_eq!(first.pid, std::process::id());
12153        assert!(!first.idle);
12154        assert_eq!(first.completed, 7);
12155        assert_eq!(first.current, status.current);
12156        assert!(
12157            !path.with_extension("json.tmp").exists(),
12158            "the temp file is renamed, not left behind"
12159        );
12160
12161        std::thread::sleep(Duration::from_millis(5));
12162        status.updated_at = Timestamp::now();
12163        status.polls = 3;
12164        write_status_to(&path, &status).unwrap();
12165        let second: Status =
12166            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
12167        assert!(
12168            second.updated_at > first.updated_at,
12169            "a reader can only detect staleness if the heartbeat moves"
12170        );
12171        assert_eq!(
12172            second.started_at, first.started_at,
12173            "the start time is not a heartbeat"
12174        );
12175        assert_eq!(second.polls, 3);
12176    }
12177
12178    #[test]
12179    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
12180        let dir = tempfile::tempdir().unwrap();
12181
12182        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
12183
12184        let mut status = Status::new();
12185        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
12186        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12187        let stale = read_status(dir.path()).unwrap();
12188        assert!(
12189            !stale.running(Timestamp::now()),
12190            "a minute without a heartbeat is a dead daemon, not a busy one"
12191        );
12192        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
12193
12194        status.updated_at = Timestamp::now();
12195        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12196        let fresh = read_status(dir.path()).unwrap();
12197        assert!(fresh.running(Timestamp::now()));
12198    }
12199
12200    #[test]
12201    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
12202        let dir = tempfile::tempdir().unwrap();
12203        let now = Timestamp::now();
12204        let mine = "20260903-080619-01c2";
12205
12206        assert!(
12207            !is_working_on(dir.path(), mine, now),
12208            "no status file means nobody is working on anything"
12209        );
12210
12211        let mut status = Status::new();
12212        status.current = vec![Current {
12213            worker: None,
12214            task: "20260903-080340-0167".to_owned(),
12215            run: mine.to_owned(),
12216        }];
12217        status.updated_at = now;
12218        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12219        assert!(is_working_on(dir.path(), mine, now));
12220        assert!(
12221            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
12222            "a daemon busy with one run is not working on another"
12223        );
12224
12225        // A killed daemon stops writing heartbeats but leaves the file behind
12226        // naming the run it died in. That run must not be undeletable forever.
12227        status.updated_at = now - jiff::SignedDuration::from_secs(600);
12228        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12229        assert!(
12230            !is_working_on(dir.path(), mine, now),
12231            "a stale heartbeat is a dead daemon, so its run is a leftover"
12232        );
12233    }
12234
12235    #[test]
12236    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
12237        let dir = tempfile::tempdir().unwrap();
12238        let now = Timestamp::now();
12239
12240        assert!(
12241            !is_working_on_short(dir.path(), "01c2", now),
12242            "no status file means nobody is working on anything"
12243        );
12244
12245        let mut status = Status::new();
12246        status.current = vec![Current {
12247            worker: None,
12248            task: "20260903-080340-0167".to_owned(),
12249            run: "20260903-080619-01c2".to_owned(),
12250        }];
12251        status.updated_at = now;
12252        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12253        assert!(
12254            is_working_on_short(dir.path(), "01c2", now),
12255            "the run's short id is the last block of its full id"
12256        );
12257        assert!(
12258            !is_working_on_short(dir.path(), "3cbf", now),
12259            "a daemon busy with one worktree bay is not working on another"
12260        );
12261    }
12262
12263    #[test]
12264    fn a_newer_status_file_still_yields_a_reading() {
12265        let dir = tempfile::tempdir().unwrap();
12266        // A field this build has never heard of must not turn the reading into
12267        // nothing at all; that is the whole reason the reader is permissive.
12268        std::fs::write(
12269            dir.path().join("daemon.json"),
12270            serde_json::json!({
12271                "schema": 2,
12272                "updated_at": Timestamp::now().to_string(),
12273                "idle": true,
12274                "surprise": { "nested": [1, 2, 3] },
12275            })
12276            .to_string(),
12277        )
12278        .unwrap();
12279
12280        let reading = read_status(dir.path()).expect("a forward-compatible read");
12281        assert!(reading.running(Timestamp::now()));
12282        assert!(reading.idle);
12283        assert!(reading.current.is_empty());
12284    }
12285
12286    #[test]
12287    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
12288        // A daemon started before `current` became a list keeps writing this
12289        // shape on every heartbeat until it is restarted. A rolling upgrade
12290        // - a newer `magi web` or `magi doctor` reading an older `magi
12291        // serve`'s heartbeat - must still see the run it is on, not "no
12292        // daemon" from a type mismatch failing the whole struct.
12293        let dir = tempfile::tempdir().unwrap();
12294        std::fs::write(
12295            dir.path().join("daemon.json"),
12296            serde_json::json!({
12297                "schema": 1,
12298                "pid": 4242,
12299                "updated_at": Timestamp::now().to_string(),
12300                "idle": false,
12301                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
12302                "completed": 3,
12303                "polls": 9,
12304            })
12305            .to_string(),
12306        )
12307        .unwrap();
12308
12309        let reading = read_status(dir.path()).expect("an older shape must still parse");
12310        assert!(reading.running(Timestamp::now()));
12311        assert_eq!(
12312            reading.current,
12313            vec![Current {
12314                worker: None,
12315                task: "20260902-140501-aaaa".to_owned(),
12316                run: "20260902-140502-bbbb".to_owned(),
12317            }]
12318        );
12319    }
12320
12321    #[test]
12322    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
12323        let dir = tempfile::tempdir().unwrap();
12324        std::fs::write(
12325            dir.path().join("daemon.json"),
12326            serde_json::json!({
12327                "schema": 1,
12328                "updated_at": Timestamp::now().to_string(),
12329                "idle": true,
12330                "current": null,
12331            })
12332            .to_string(),
12333        )
12334        .unwrap();
12335        let with_null = read_status(dir.path()).expect("null must still parse");
12336        assert!(with_null.current.is_empty());
12337
12338        std::fs::write(
12339            dir.path().join("daemon.json"),
12340            serde_json::json!({
12341                "schema": 1,
12342                "updated_at": Timestamp::now().to_string(),
12343                "idle": true,
12344            })
12345            .to_string(),
12346        )
12347        .unwrap();
12348        let absent = read_status(dir.path()).expect("a missing field must still parse");
12349        assert!(absent.current.is_empty());
12350    }
12351
12352    #[test]
12353    fn a_task_without_a_repository_runs_in_the_daemons_default() {
12354        let fallback = Path::new("/default");
12355        let mut blank = task();
12356        blank.repo = PathBuf::new();
12357        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
12358        let mut dot = task();
12359        dot.repo = PathBuf::from(".");
12360        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
12361        assert_eq!(
12362            repo_for(&task(), fallback),
12363            PathBuf::from("/repo"),
12364            "a task that names a repository keeps it"
12365        );
12366    }
12367
12368    #[test]
12369    fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
12370        let dir = tempfile::tempdir().unwrap();
12371        let repo = dir.path();
12372        let path = repo.join("explicit.toml");
12373        std::fs::write(
12374            &path,
12375            "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
12376        )
12377        .unwrap();
12378        let opts = Opts {
12379            config: Some(path),
12380            ..Opts::default()
12381        };
12382        let queue = Queue::at(repo.join("queue"));
12383        let mut new = task();
12384        queue.put(&mut new).unwrap();
12385        let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
12386        assert_eq!(
12387            resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
12388            BuildCache::Isolated
12389        );
12390
12391        let mut old = task();
12392        old.schema = 22;
12393        queue.put(&mut old).unwrap();
12394        let mut old = queue.get(&old.id).unwrap();
12395        let config = resolved(&old);
12396        assert_eq!(config.verify.build_cache, BuildCache::Shared);
12397        assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
12398        old.hold_manual(Some("wait".into()));
12399        queue.put(&mut old).unwrap();
12400
12401        let mut saved = queue.get(&old.id).unwrap();
12402        assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
12403        saved
12404            .overrides
12405            .as_mut()
12406            .unwrap()
12407            .merge_over(&crate::queue::RunOverrides {
12408                build_cache: Some(BuildCache::Isolated),
12409                ..Default::default()
12410            });
12411        queue.put(&mut saved).unwrap();
12412        assert_eq!(
12413            resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
12414            BuildCache::Isolated
12415        );
12416    }
12417
12418    #[test]
12419    fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
12420        let dir = tempfile::tempdir().unwrap();
12421        let path = dir.path().join("explicit.toml");
12422        let write = |verify: &str| {
12423            std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
12424        };
12425        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
12426        let opts = Opts {
12427            config: Some(path.clone()),
12428            ..Opts::default()
12429        };
12430        let mut task = task();
12431        task.set_urgent(true).unwrap();
12432        let resolved = |task: &Task| {
12433            prepare_for(dir.path(), &opts, task)
12434                .unwrap()
12435                .verify
12436                .build_cache
12437        };
12438        assert_eq!(resolved(&task), BuildCache::Isolated);
12439        task.change_build_cache(Some(BuildCache::Shared)).unwrap();
12440        assert_eq!(resolved(&task), BuildCache::Shared);
12441        task.change_build_cache(None).unwrap();
12442        assert_eq!(resolved(&task), BuildCache::Isolated);
12443        task.set_urgent(false).unwrap();
12444        assert_eq!(resolved(&task), BuildCache::Shared);
12445
12446        // Urgent work must never be the one stopped by isolation: with no
12447        // shared cache to wait behind, or with a verification command isolated
12448        // mode cannot run, an urgent task keeps the configured mode.
12449        task.set_urgent(true).unwrap();
12450        write("e2e = [\"npm test\"]\n");
12451        assert_eq!(resolved(&task), BuildCache::Shared);
12452        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
12453        assert_eq!(resolved(&task), BuildCache::Shared);
12454        // An explicit choice stays strict and is applied as asked.
12455        task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
12456        assert_eq!(resolved(&task), BuildCache::Isolated);
12457    }
12458
12459    #[test]
12460    fn task_implementers_edit_inherits_daemon_config_and_merge() {
12461        let dir = tempfile::tempdir().unwrap();
12462        let path = dir.path().join("explicit.toml");
12463        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
12464        let opts = Opts {
12465            config: Some(path),
12466            merge: Some("none".into()),
12467            ..Default::default()
12468        };
12469        let mut t = task();
12470        t.set_implementers(
12471            2,
12472            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12473                .unwrap(),
12474        )
12475        .unwrap();
12476        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
12477        assert_eq!(cfg.graph.implementers, 2);
12478        assert_eq!(cfg.graph.judges, 1);
12479        assert_eq!(cfg.merge.mode, MergeMode::None);
12480        t.set_implementers(1, &cfg).unwrap();
12481        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
12482        apply_task_implementers(&mut cfg, &t);
12483        assert_eq!(cfg.graph.implementers, 1);
12484        assert_eq!(cfg.graph.judges, 1);
12485        assert_eq!(cfg.merge.mode, MergeMode::None);
12486    }
12487
12488    #[test]
12489    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
12490        let dir = tempfile::tempdir().unwrap();
12491        let repo = dir.path().join("repo");
12492        std::fs::create_dir(&repo).unwrap();
12493        std::fs::write(
12494            repo.join("magi.toml"),
12495            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
12496        )
12497        .unwrap();
12498        let daemon_config = dir.path().join("daemon.toml");
12499        std::fs::write(
12500            &daemon_config,
12501            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
12502        )
12503        .unwrap();
12504        let opts = Opts {
12505            config: Some(daemon_config),
12506            merge: Some("pr".into()),
12507            ..Default::default()
12508        };
12509        let q = Queue::at(dir.path().join("queue"));
12510        let validation: Config =
12511            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12512                .unwrap();
12513        // No provenance field on legacy direct tasks: both shapes stay isolated.
12514        for record in ["{}", r#"{"candidates":2}"#] {
12515            let overrides = serde_json::from_str(record).unwrap();
12516            let filing = crate::direct::Filing {
12517                instruction: "work".into(),
12518                title: "direct".into(),
12519                repo: repo.clone(),
12520                source: crate::queue::Source::Human,
12521                solo: false,
12522                overrides,
12523                review_of: None,
12524                sources: Default::default(),
12525            };
12526            let filed =
12527                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
12528            let crate::direct::Filed::Standalone {
12529                mut task,
12530                claim: _claim,
12531            } = filed
12532            else {
12533                panic!("local filing")
12534            };
12535            let before = prepare_for(&repo, &opts, &task).unwrap();
12536            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
12537            assert_eq!(
12538                before.merge.mode,
12539                MergeMode::None,
12540                "daemon --merge must not leak"
12541            );
12542            for n in [2, 1, 2] {
12543                task.set_implementers(n, &validation).unwrap();
12544                q.put(&mut task).unwrap();
12545                task = q.get(&task.id).unwrap();
12546                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
12547                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
12548                apply_task_implementers(&mut cfg, &task);
12549                assert_eq!(cfg.graph.implementers, usize::from(n));
12550                assert_eq!(cfg.graph.judges, 2);
12551                assert_eq!(cfg.merge.mode, MergeMode::None);
12552            }
12553        }
12554    }
12555
12556    #[test]
12557    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
12558        let cfg: Config =
12559            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12560                .unwrap();
12561        let mut t = task();
12562        t.review_of = Some("review-target".into());
12563        t.hold_manual(Some("retry".into()));
12564        let mut previous = RunState::new(
12565            PathBuf::from("/repo"),
12566            "main".into(),
12567            "abc1234".into(),
12568            "review".into(),
12569            cfg.clone(),
12570        );
12571        previous.config.graph.implementers = 2;
12572        for count in [1, 3] {
12573            t.set_implementers(count, &cfg).unwrap();
12574            t.release();
12575            assert_eq!(t.review_of.as_deref(), Some("review-target"));
12576            for proposed in [
12577                Starter::Resume(previous.id.clone()),
12578                Starter::Review("recovery-target".into()),
12579            ] {
12580                assert_eq!(
12581                    starter_with_implementers(&t, Some(&previous), proposed),
12582                    Starter::Review("review-target".into())
12583                );
12584            }
12585            let mut configured = cfg.clone();
12586            apply_task_implementers(&mut configured, &t);
12587            assert_eq!(configured.graph.implementers, usize::from(count));
12588            assert_eq!(previous.config.graph.implementers, 2);
12589        }
12590    }
12591
12592    #[test]
12593    fn task_implementers_dispatch_and_resume_agree() {
12594        let mut t = task();
12595        let cfg: crate::config::Config =
12596            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12597                .unwrap();
12598        let mut run = RunState::new(
12599            PathBuf::from("/repo"),
12600            "main".into(),
12601            "abc1234".into(),
12602            "work".into(),
12603            cfg.clone(),
12604        );
12605        run.config.graph.implementers = 2;
12606        for n in [2, 1, 3, 2] {
12607            t.set_implementers(n, &cfg).unwrap();
12608            let mut dispatched = cfg.clone();
12609            apply_task_implementers(&mut dispatched, &t);
12610            assert_eq!(dispatched.graph.implementers, usize::from(n));
12611            assert_eq!(implementers_match(&t, &run), n == 2);
12612            for proposed in [
12613                Starter::Resume(run.id.clone()),
12614                Starter::Review("old-branch".into()),
12615            ] {
12616                let expected = if n == 2 {
12617                    proposed.clone()
12618                } else {
12619                    Starter::Start
12620                };
12621                assert_eq!(
12622                    starter_with_implementers(&t, Some(&run), proposed),
12623                    expected
12624                );
12625            }
12626            assert_eq!(
12627                run.config.graph.implementers, 2,
12628                "history must not be rewritten"
12629            );
12630        }
12631        t.solo = false;
12632        t.overrides = None;
12633        assert!(implementers_match(&t, &run));
12634    }
12635
12636    #[test]
12637    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
12638        // Three seats said out loud. What `solo` promises is one candidate
12639        // *whatever the config asks for*, so the contrast has to be a number
12640        // this test owns - it used to be `Config::default()`'s, which became
12641        // 1 when one implementation became the default and left the two
12642        // halves of this test asserting the same thing.
12643        let mut solo_cfg = Config::default();
12644        solo_cfg.graph.implementers = 3;
12645        let mut solo_task = task();
12646        solo_task.solo = true;
12647        apply_task_implementers(&mut solo_cfg, &solo_task);
12648        assert_eq!(solo_cfg.graph.implementers, 1);
12649
12650        let mut plain_cfg = Config::default();
12651        plain_cfg.graph.implementers = 3;
12652        let plain_task = task();
12653        assert!(!plain_task.solo);
12654        apply_task_implementers(&mut plain_cfg, &plain_task);
12655        assert_eq!(
12656            plain_cfg.graph.implementers, 3,
12657            "a task that did not ask to run alone keeps the config's candidates"
12658        );
12659    }
12660
12661    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
12662        QuotaLoss {
12663            cause: crate::agent::QuotaCause::UsageLimit,
12664            agent: String::new(),
12665            seat: seat.into(),
12666            node: "judge".into(),
12667            at: at.parse().unwrap(),
12668            reset: reset.map(str::to_string),
12669        }
12670    }
12671
12672    #[test]
12673    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
12674        let now = Timestamp::now();
12675        for reset in [None, Some("in 1h")] {
12676            let auth = crate::agent::Quota {
12677                cause: crate::agent::QuotaCause::Authentication,
12678                agent: "alpha".into(),
12679                reset: reset.map(str::to_owned),
12680            };
12681            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
12682            assert_eq!(cooldown_until(&[loss], now), None);
12683        }
12684    }
12685
12686    #[test]
12687    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
12688        let old: Vec<QuotaLoss> = (1..=4)
12689            .map(|i| {
12690                loss(
12691                    &format!("judge-{i}"),
12692                    "2026-09-23T05:23:00Z",
12693                    Some("2:40pm (Asia/Tokyo)"),
12694                )
12695            })
12696            .collect();
12697        let fresh = losses_this_attempt(&old, &old);
12698        assert!(fresh.is_empty());
12699        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
12700        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
12701    }
12702
12703    #[test]
12704    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
12705        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
12706        let now = Timestamp::now();
12707        let mut after = old.clone();
12708        after.push(loss("judge-2", &now.to_string(), None));
12709        let fresh = losses_this_attempt(&old, &after);
12710        assert_eq!(fresh, vec![after[1].clone()]);
12711        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
12712        assert_eq!(
12713            until,
12714            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
12715        );
12716    }
12717
12718    #[test]
12719    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
12720        // `recover_stall` removes judge-1's loss and the retry then hits quota
12721        // again: the vector is the same length, so an index diff sees nothing.
12722        let before = vec![
12723            loss("judge-1", "2026-09-23T05:23:00Z", None),
12724            loss("judge-2", "2026-09-23T05:24:00Z", None),
12725        ];
12726        let after = vec![
12727            loss("judge-2", "2026-09-23T05:24:00Z", None),
12728            loss("judge-1", "2026-09-24T01:00:00Z", None),
12729        ];
12730        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
12731    }
12732
12733    #[test]
12734    fn merge_overrides_are_parsed_or_refused() {
12735        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
12736        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
12737        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
12738        assert!(merge_mode("squash").is_err());
12739    }
12740
12741    #[test]
12742    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
12743        let now = Timestamp::now();
12744        let fallback = Duration::from_secs(300);
12745        let cap = Duration::from_secs(1800);
12746
12747        // No reset hint at all: the fallback.
12748        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
12749
12750        // A reset ten minutes out, well inside the cap: waited for exactly.
12751        let soon = now + jiff::SignedDuration::from_secs(600);
12752        assert_eq!(
12753            quota_wait(Some(soon), now, fallback, cap),
12754            Duration::from_secs(600)
12755        );
12756
12757        // A reset already in the past is not trusted: the fallback, not a
12758        // zero or negative wait that would spin the loop right back around.
12759        let past = now - jiff::SignedDuration::from_secs(60);
12760        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
12761
12762        // A reset further out than the cap is trusted for direction but not
12763        // for magnitude: a parsing slip must not sleep the loop for a day.
12764        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
12765        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
12766    }
12767
12768    #[test]
12769    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
12770        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
12771
12772        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
12773        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
12774
12775        // Same clock reading, but it has already gone by today: read as
12776        // tomorrow's, since the CLI would not still be reporting a limit past
12777        // its own stated reset.
12778        let already_past =
12779            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
12780        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
12781
12782        assert!(
12783            parse_reset_hint("session limit reached", now, now).is_none(),
12784            "free text with no recognised shape is not guessed at"
12785        );
12786        assert!(
12787            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
12788            "an unresolvable zone name is not guessed at either"
12789        );
12790    }
12791
12792    #[test]
12793    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
12794        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
12795
12796        let at = parse_reset_hint(
12797            "You've hit your usage limit. Visit \
12798             https://chatgpt.com/codex/settings/usage to purchase more \
12799             credits or try again at Sep 19th, 2026 5:10 PM.",
12800            now,
12801            now,
12802        )
12803        .expect("the codex reset wording is a recognised shape");
12804        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
12805
12806        // The month is explicit, so a date already earlier in the same
12807        // sentence-implied year than `now` is trusted as written rather than
12808        // rolled forward a year the way the bracketed shape rolls a
12809        // same-day clock reading to tomorrow.
12810        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
12811            .expect("an explicit year needs no rollover");
12812        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
12813
12814        assert!(
12815            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
12816            "a two-digit year is not the documented shape and is not guessed at"
12817        );
12818        assert!(
12819            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
12820            "a four-letter month name is not the documented three-letter abbreviation"
12821        );
12822        assert!(
12823            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
12824            "an explicit zone on the dated shape is a format nobody has \
12825             documented, and is refused rather than guessed at as UTC"
12826        );
12827    }
12828
12829    #[test]
12830    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
12831        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
12832        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
12833
12834        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
12835        assert_eq!(at.as_second() - recorded.as_second(), 3769);
12836
12837        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
12838        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
12839
12840        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
12841            assert!(
12842                parse_reset_hint(bad, now, recorded).is_none(),
12843                "{bad:?} must not be guessed at"
12844            );
12845        }
12846    }
12847
12848    /// A loop whose queue lives in a temp tree and whose poll interval is far
12849    /// longer than the test's patience, so anything that waits out a poll
12850    /// instead of noticing the stop fails rather than merely being slow.
12851    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
12852        let config = dir.join("magi.toml");
12853        std::fs::write(
12854            &config,
12855            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
12856        )
12857        .unwrap();
12858        let opts = Opts {
12859            poll: Duration::from_secs(30),
12860            config: Some(config),
12861            // The explicit fixture config keeps startup cleanup from reading
12862            // machine configuration. This fictional repository likewise
12863            // keeps any best-effort git cleanup away from this checkout.
12864            repo: dir.join("repo"),
12865            ..Opts::default()
12866        };
12867        // The status file goes in a directory that does not exist yet, so its
12868        // creation is itself evidence the loop published one. `worktrees`
12869        // must be just as fictional: the janitor reclaims worktrees under it
12870        // for real, and a test that let it fall through to
12871        // `crate::run::default_worktree_root()` would have it reclaim
12872        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
12873        // which is exactly what happened before this function took the
12874        // parameter at all.
12875        let home = dir.join("home");
12876        // These control-only fixtures do not launch native workers. Give the
12877        // independently tested maintenance services a fresh cadence receipt.
12878        let stamps = home.join("service-ticks");
12879        std::fs::create_dir_all(&stamps).unwrap();
12880        for service in ["waiter", "deputies", "release-watch"] {
12881            std::fs::write(
12882                stamps.join(service),
12883                Timestamp::now().as_second().to_string(),
12884            )
12885            .unwrap();
12886        }
12887        for operation in [
12888            "conductor",
12889            "maintenance",
12890            "housekeeping",
12891            "disk-pressure",
12892            "fold",
12893            "cache",
12894            "fetch",
12895            "chat-goals",
12896        ] {
12897            std::fs::write(
12898                stamps.join(format!("daemon-{operation}")),
12899                serde_json::to_vec(&Timestamp::now()).unwrap(),
12900            )
12901            .unwrap();
12902        }
12903        let worktrees = dir.join("wt");
12904        (
12905            opts,
12906            Queue::at(dir.join("queue")),
12907            home.join("daemon.json"),
12908            home,
12909            worktrees,
12910        )
12911    }
12912
12913    #[tokio::test]
12914    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
12915        let dir = tempfile::tempdir().unwrap();
12916        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12917        let mut waiting = task();
12918        waiting.repo = opts.repo.clone();
12919        waiting.hold_machine(crate::disk::gate(1, 100));
12920        waiting.mark_disk_capacity();
12921        waiting.attempts = 2;
12922        queue.put(&mut waiting).unwrap();
12923        let mut busy = task();
12924        busy.status = TaskStatus::Running;
12925        queue.put(&mut busy).unwrap();
12926        let payload = serde_json::to_value(ServiceWorker {
12927            opts,
12928            queue: queue.root().to_owned(),
12929            worktrees_root: worktrees,
12930            operation: "maintenance".into(),
12931        })
12932        .unwrap();
12933        run_service_worker(&home, payload.clone()).await.unwrap();
12934        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
12935        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
12936        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
12937        run_service_worker(&home, payload).await.unwrap();
12938        assert!(
12939            crate::worker::active(&home).unwrap().is_empty(),
12940            "monitoring only queues; normal dispatch owns launches"
12941        );
12942        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
12943    }
12944
12945    #[tokio::test]
12946    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
12947        let dir = tempfile::tempdir().unwrap();
12948        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12949        let cfg = Config::default();
12950        start_service(
12951            &home,
12952            &opts,
12953            &queue,
12954            &worktrees,
12955            "housekeeping",
12956            Some(&cfg),
12957            true,
12958        )
12959        .await
12960        .unwrap();
12961        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
12962        let read = |path: &Path| -> serde_json::Value {
12963            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
12964        };
12965        assert_eq!(read(&receipt)["detail"], "cadence not due");
12966        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
12967        start_service(
12968            &home,
12969            &opts,
12970            &queue,
12971            &worktrees,
12972            "housekeeping",
12973            Some(&cfg),
12974            true,
12975        )
12976        .await
12977        .unwrap();
12978        assert_eq!(
12979            read(&receipt)["detail"],
12980            "active work or runnable task queue"
12981        );
12982        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
12983        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
12984        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
12985        start_service(
12986            &home,
12987            &opts,
12988            &queue,
12989            &worktrees,
12990            "disk-pressure",
12991            Some(&cfg),
12992            false,
12993        )
12994        .await
12995        .unwrap();
12996        assert_eq!(
12997            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
12998            "no active work; idle housekeeping owns scan"
12999        );
13000        assert!(crate::worker::active(&home).unwrap().is_empty());
13001    }
13002
13003    /// The folding turn exists exactly where idle housekeeping does not: with
13004    /// work busy or runnable. On `origin/main` the only caller of
13005    /// `clean::fold_due` was housekeeping, so a queue that was never empty
13006    /// admitted no finished-run folding at all.
13007    #[test]
13008    fn the_fold_turn_is_admitted_exactly_where_housekeeping_is_not() {
13009        let on = Config::default();
13010        for busy in [false, true] {
13011            for runnable in [false, true] {
13012                assert_ne!(
13013                    housekeeping_eligible(busy, runnable),
13014                    fold_turn_eligible(busy, runnable, Some(&on)),
13015                    "busy={busy} runnable={runnable}"
13016                );
13017            }
13018        }
13019        assert!(!housekeeping_eligible(true, true), "the 1275 machine");
13020        assert!(!fold_turn_eligible(true, true, None));
13021        let mut off = Config::default();
13022        off.disk.auto_fold = false;
13023        assert!(!fold_turn_eligible(true, true, Some(&off)));
13024        assert!(fold_turn_eligible(true, true, Some(&Config::default())));
13025    }
13026
13027    #[tokio::test]
13028    async fn the_fold_service_says_why_it_skipped_a_dispatch() {
13029        let dir = tempfile::tempdir().unwrap();
13030        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13031        let read = || -> serde_json::Value {
13032            serde_json::from_slice(
13033                &std::fs::read(home.join("source-eviction-fold-dispatch.json")).unwrap(),
13034            )
13035            .unwrap()
13036        };
13037        let tick = home.join("service-ticks/daemon-fold");
13038        let cfg = Config::default();
13039        let dispatch = |busy: bool, cfg: Config| {
13040            let (home, opts, queue, worktrees) = (&home, &opts, &queue, &worktrees);
13041            async move {
13042                start_service(home, opts, queue, worktrees, "fold", Some(&cfg), busy)
13043                    .await
13044                    .unwrap();
13045            }
13046        };
13047        dispatch(true, cfg.clone()).await;
13048        assert_eq!(read()["detail"], "cadence not due");
13049
13050        std::fs::remove_file(&tick).unwrap();
13051        dispatch(false, cfg.clone()).await;
13052        assert_eq!(
13053            read()["detail"],
13054            "idle machine; housekeeping owns finished-run folding"
13055        );
13056        let mut off = cfg.clone();
13057        off.disk.auto_fold = false;
13058        dispatch(true, off).await;
13059        assert_eq!(read()["detail"], "auto_fold disabled");
13060        // An unreadable startup configuration is its own reason, not "idle".
13061        start_service(&home, &opts, &queue, &worktrees, "fold", None, true)
13062            .await
13063            .unwrap();
13064        assert_eq!(read()["detail"], "startup configuration unavailable");
13065
13066        // A housekeeping worker already folding: one folding service at a time.
13067        let directory = home.join("workers/jobs/abcdef");
13068        std::fs::create_dir_all(&directory).unwrap();
13069        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13070        crate::pr_head::try_lock_file(&lease).unwrap();
13071        let mut job = crate::worker::Job {
13072            id: "abcdef".into(),
13073            sequence: 1,
13074            kind: "daemon-service".into(),
13075            key: "service:daemon-housekeeping".into(),
13076            payload: serde_json::Value::Null,
13077            generation: "fixture".into(),
13078            version: None,
13079            status: crate::worker::Status::Running,
13080            result: None,
13081            pid: Some(std::process::id()),
13082            created_at: Timestamp::now().as_second() as u64,
13083            finished_at: None,
13084        };
13085        let record = directory.join("job.json");
13086        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13087        dispatch(true, cfg).await;
13088        assert_eq!(
13089            read()["detail"],
13090            "another finished-run folding service is active"
13091        );
13092        assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
13093        job.status = crate::worker::Status::Finished;
13094        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
13095        drop(lease);
13096    }
13097
13098    /// Issue 1275 through the scheduler's own admission: a leased task worker is
13099    /// busy, another task is runnable, and a confirmed merged run of the same
13100    /// repository is long past its grace. `poll` admits the fold service (the
13101    /// worker runs inline here: a unit test has no `magi` executable to exec),
13102    /// the historical worktree goes, the repository's active checkout stays and
13103    /// the merged run's evidence is kept. Removing `"fold"` from the operation
13104    /// list in `poll` leaves the worktree standing and fails this test.
13105    #[tokio::test]
13106    async fn the_scheduler_folds_a_merged_run_beside_a_busy_worker_and_a_runnable_task() {
13107        let dir = tempfile::tempdir().unwrap();
13108        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13109        let repo = dir.path().join("checkout");
13110        std::fs::create_dir_all(&repo).unwrap();
13111        crate::clean::tests::init_repo(&repo);
13112        std::fs::write(
13113            opts.config.as_ref().unwrap(),
13114            "[disk]\nmin_free_bytes = 0\nauto_fold = true\ncache_limit_bytes = 0\n",
13115        )
13116        .unwrap();
13117        let (id, historical) = crate::clean::tests::merged_run_with_worktree(
13118            &home,
13119            &repo,
13120            &worktrees,
13121            "20260801-000000-s001",
13122        )
13123        .await;
13124        let active = dir.path().join("active");
13125        crate::git::worktree_add_branch(&repo, &active, "magi/active", "main")
13126            .await
13127            .unwrap();
13128        // The busy worker belongs to the scheduler's own queue and owns a
13129        // recorded run of the same repository that is eligible on paper
13130        // (finished, past its grace). Its execution lease is held, as a
13131        // driving worker holds it.
13132        let (owned_id, owned_worktree) = crate::clean::tests::due_run_with_winner_worktree(
13133            &home.join("runs"),
13134            &worktrees,
13135            &repo,
13136            "20260801-000000-s002",
13137            RunStatus::Superseded,
13138        )
13139        .await;
13140        let owned_run = home.join("runs").join(&owned_id);
13141        let owned_record = std::fs::read(owned_run.join("run.json")).unwrap();
13142        let mut busy = task();
13143        busy.repo = repo.clone();
13144        busy.status = TaskStatus::Running;
13145        busy.link_run(&owned_id);
13146        queue.put(&mut busy).unwrap();
13147        let worker_lease = crate::worker::running_fixture(
13148            &home,
13149            &format!("task:{}", busy.id),
13150            serde_json::to_value(TaskWorker {
13151                opts: Opts::default(),
13152                queue: queue.root().to_owned(),
13153                task: busy.id.clone(),
13154                lane: PermitKind::default(),
13155                standalone: true,
13156            })
13157            .unwrap(),
13158        )
13159        .unwrap();
13160        let execution = crate::driver::maintenance(&home, &owned_id).unwrap();
13161        let mut waiting = task();
13162        waiting.repo = repo.clone();
13163        queue.put(&mut waiting).unwrap();
13164        std::fs::remove_file(home.join("service-ticks/daemon-fold")).unwrap();
13165
13166        let mut cfg = Config::default();
13167        cfg.disk.auto_fold = true;
13168        INLINE_SERVICES.with(|inline| inline.set(true));
13169        let status = Arc::new(Mutex::new(Status::new()));
13170        let stop = Stop::new();
13171        let mut dispatch = Box::pin(poll(
13172            &opts,
13173            &queue,
13174            &status,
13175            &home,
13176            &worktrees,
13177            &stop,
13178            DispatchLimits {
13179                max_concurrent: 0,
13180                pause_for_interrupts: false,
13181                recovery_cfg: Some(cfg),
13182            },
13183        ));
13184        let receipt = home.join("source-eviction-fold-worker.json");
13185        let completed = async {
13186            loop {
13187                let done = std::fs::read(&receipt)
13188                    .ok()
13189                    .and_then(|body| serde_json::from_slice::<serde_json::Value>(&body).ok())
13190                    .is_some_and(|receipt| receipt["outcome"] == "completed");
13191                if done {
13192                    break;
13193                }
13194                tokio::time::sleep(Duration::from_millis(25)).await;
13195            }
13196        };
13197        tokio::select! {
13198            result = &mut dispatch => panic!("the scheduler stopped before the fold service ran: {result:?}"),
13199            result = tokio::time::timeout(Duration::from_secs(120), completed) => {
13200                result.expect("the scheduler never admitted the fold service");
13201            }
13202        }
13203        stop.stop();
13204        dispatch.await.unwrap();
13205        INLINE_SERVICES.with(|inline| inline.set(false));
13206
13207        assert!(!historical.exists(), "the merged run's worktree is folded");
13208        assert!(
13209            active.join("README.md").is_file(),
13210            "the repository's active checkout is untouched"
13211        );
13212        let run = home.join("runs").join(&id);
13213        assert!(run.join("run.json").is_file());
13214        assert!(run.join("artifacts/fold-evidence/manifest.json").is_file());
13215        let read = |name: &str| -> serde_json::Value {
13216            serde_json::from_slice(&std::fs::read(home.join(name)).unwrap()).unwrap()
13217        };
13218        assert_eq!(
13219            read("source-eviction-fold-dispatch.json")["detail"],
13220            "eligible and cadence due"
13221        );
13222        let worker = read("source-eviction-fold-worker.json");
13223        assert_eq!(worker["fold"]["records"], 2);
13224        assert_eq!(worker["fold"]["folded"], 1);
13225        assert_eq!(worker["fold"]["invoked"], 1);
13226        assert_eq!(
13227            worker["fold"]["live"], 1,
13228            "the busy worker's own run is left alone: {worker}"
13229        );
13230        // The run the busy worker owns - eligible on paper (finished, past its
13231        // grace) - keeps its checkout, its candidate and its record, byte for byte.
13232        assert!(owned_worktree.exists());
13233        assert_eq!(
13234            std::fs::read(owned_run.join("run.json")).unwrap(),
13235            owned_record
13236        );
13237        assert!(
13238            !RunState::load_under(&owned_id, &home).unwrap().candidates[0].folded,
13239            "the owned run's candidate is not folded"
13240        );
13241        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
13242        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
13243        drop(execution);
13244        drop(worker_lease);
13245    }
13246
13247    /// On a platform without process containment the disk-pressure service
13248    /// refuses to reclaim, and says so in both places an operator looks: the
13249    /// persisted retention report and the worker receipt. Driven through the
13250    /// service handler itself, so removing either publication fails this test.
13251    #[tokio::test]
13252    async fn the_disk_pressure_service_reports_a_platform_without_containment() {
13253        let dir = tempfile::tempdir().unwrap();
13254        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13255        let payload = serde_json::to_value(ServiceWorker {
13256            opts,
13257            queue: queue.root().to_owned(),
13258            worktrees_root: worktrees,
13259            operation: "disk-pressure".into(),
13260        })
13261        .unwrap();
13262        let _platform = crate::retention::WithoutContainment::new();
13263        run_service_worker(&home, payload).await.unwrap();
13264
13265        let refusal = "Automatic output reclamation requires Unix process containment";
13266        let report: serde_json::Value =
13267            serde_json::from_slice(&std::fs::read(home.join("retention.json")).unwrap()).unwrap();
13268        assert_eq!(report["failures"], serde_json::json!([refusal]));
13269        let receipt: serde_json::Value = serde_json::from_slice(
13270            &std::fs::read(home.join("source-eviction-disk-pressure-worker.json")).unwrap(),
13271        )
13272        .unwrap();
13273        assert_eq!(receipt["outcome"], "retention swept");
13274        assert_eq!(receipt["retention"]["failure_count"], 1);
13275        assert_eq!(
13276            receipt["retention"]["failures"],
13277            serde_json::json!([refusal])
13278        );
13279    }
13280
13281    #[tokio::test]
13282    async fn goal_observation_service_does_not_block_scheduler_decisions() {
13283        let dir = tempfile::tempdir().unwrap();
13284        let (opts, _, _, home, worktrees) = idle_loop(dir.path());
13285        let queue = Queue::at(home.join("queue"));
13286        let mut task = task();
13287        task.repo = opts.repo.clone();
13288        task.chat = Some("decision-chat".into());
13289        task.hold_machine(Some("waiting for a decision".into()));
13290        queue.put(&mut task).unwrap();
13291        let questions = Questions::at(home.join("questions"));
13292        let mut question = action_question(&task.id, ask::ChoiceAction::Done);
13293        question.node = crate::conduct::NODE.into();
13294        question.status = ask::QuestionStatus::Open;
13295        question.answer = None;
13296        question.answered_at = None;
13297        questions.put(&mut question).unwrap();
13298        questions
13299            .update(&question.id, |q| {
13300                q.answer(ask::Answer::Choice("resume で続行する".into()))
13301            })
13302            .unwrap();
13303
13304        let talks = crate::talk::Talks::at(home.join("talks"));
13305        let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
13306        decision_chat.pending = "Keep this unsent status question".into();
13307        talks.put(&mut decision_chat).unwrap();
13308        let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
13309        talk.goals.push(serde_json::from_value(serde_json::json!({
13310            "id":"goal","purpose":"follow the retained job","scope":"one task",
13311            "condition":{"description":"land the result","kind":"runs_merged"},
13312            "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
13313            "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
13314            "started":1,"wakes":1,"last_checked":null,"fingerprint":""
13315        })).unwrap());
13316        talks.put(&mut talk).unwrap();
13317
13318        // A retained service lease models an observation still waiting on its
13319        // external dependency. Admission must neither await nor repeat it.
13320        let directory = home.join("workers/jobs/abcdef");
13321        std::fs::create_dir_all(&directory).unwrap();
13322        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13323        crate::pr_head::try_lock_file(&lease).unwrap();
13324        let mut job = crate::worker::Job {
13325            id: "abcdef".into(),
13326            sequence: 1,
13327            kind: "daemon-service".into(),
13328            key: "service:daemon-chat-goals".into(),
13329            payload: serde_json::Value::Null,
13330            generation: "fixture".into(),
13331            version: None,
13332            status: crate::worker::Status::Running,
13333            result: None,
13334            pid: Some(std::process::id()),
13335            created_at: Timestamp::now().as_second() as u64,
13336            finished_at: None,
13337        };
13338        let record = directory.join("job.json");
13339        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13340        let status = Arc::new(Mutex::new(Status::new()));
13341        let stop = Stop::new();
13342        let mut dispatch = Box::pin(poll(
13343            &opts,
13344            &queue,
13345            &status,
13346            &home,
13347            &worktrees,
13348            &stop,
13349            DispatchLimits {
13350                max_concurrent: 1,
13351                pause_for_interrupts: false,
13352                recovery_cfg: None,
13353            },
13354        ));
13355        std::future::poll_fn(|cx| {
13356            assert!(dispatch.as_mut().poll(cx).is_pending());
13357            std::task::Poll::Ready(())
13358        })
13359        .await;
13360        assert!(lock(&status).polls > 0);
13361        let saved = queue.get(&task.id).unwrap();
13362        assert_eq!(saved.status, TaskStatus::Done);
13363        assert!(saved.action_applied(&question.id));
13364        assert!(
13365            talks
13366                .get("decision-chat")
13367                .unwrap()
13368                .pending
13369                .contains("Keep this unsent status question")
13370        );
13371        let goal = talks.get(&talk.id).unwrap().goals.remove(0);
13372        assert_eq!(goal.state, crate::chat_goal::State::Runnable);
13373        assert_eq!(
13374            goal.started,
13375            Some(1),
13376            "only the observation worker may reconcile its goal"
13377        );
13378        assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
13379
13380        stop.stop();
13381        dispatch.await.unwrap();
13382        job.status = crate::worker::Status::Finished;
13383        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
13384        drop(lease);
13385    }
13386
13387    #[test]
13388    fn a_stop_is_idempotent_and_once_set_stays_set() {
13389        let stop = Stop::new();
13390        assert!(!stop.stopped());
13391
13392        stop.stop();
13393        assert!(stop.stopped());
13394        stop.stop();
13395        assert!(stop.stopped(), "a second stop is not a toggle");
13396
13397        let shared = stop.clone();
13398        assert!(
13399            shared.stopped(),
13400            "a clone is the same stop; that is how the loop and its caller share one"
13401        );
13402    }
13403
13404    #[tokio::test]
13405    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
13406        for operation in ["conductor", "maintenance", "housekeeping"] {
13407            let dir = tempfile::tempdir().unwrap();
13408            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
13409            opts.once = true;
13410            opts.poll = Duration::from_millis(1);
13411            // This test exercises answer scheduling, not explicit discard:
13412            // ordinary Done requires a completed retained execution.
13413            let mut state = run_state(RunStatus::Ready);
13414            state.reserve_under(&home).unwrap();
13415            state.save_under(&home).unwrap();
13416            let mut task = task();
13417            task.runs.push(state.id.clone());
13418            queue.put(&mut task).unwrap();
13419            let claim = queue.claim(&task.id).unwrap();
13420
13421            // Model a live service holding the task's claim across the
13422            // scheduler's dispatch scan. No real subprocess or timed race.
13423            let directory = home.join("workers/jobs/abcdef");
13424            std::fs::create_dir_all(&directory).unwrap();
13425            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13426            crate::pr_head::try_lock_file(&lease).unwrap();
13427            let mut job = crate::worker::Job {
13428                id: "abcdef".into(),
13429                sequence: 1,
13430                kind: "daemon-service".into(),
13431                key: format!("service:daemon-{operation}"),
13432                payload: serde_json::Value::Null,
13433                generation: "fixture".into(),
13434                version: None,
13435                status: crate::worker::Status::Running,
13436                result: None,
13437                pid: Some(std::process::id()),
13438                created_at: Timestamp::now().as_second() as u64,
13439                finished_at: None,
13440            };
13441            let record = directory.join("job.json");
13442            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13443
13444            let status = Arc::new(Mutex::new(Status::new()));
13445            let stop = Stop::new();
13446            let mut drain = Box::pin(poll(
13447                &opts,
13448                &queue,
13449                &status,
13450                &home,
13451                &worktrees,
13452                &stop,
13453                DispatchLimits {
13454                    max_concurrent: 1,
13455                    pause_for_interrupts: false,
13456                    recovery_cfg: None,
13457                },
13458            ));
13459            std::future::poll_fn(|cx| {
13460                use std::future::Future;
13461                assert!(
13462                    drain.as_mut().poll(cx).is_pending(),
13463                    "--once must wait for {operation} to release its queue claim"
13464                );
13465                std::task::Poll::Ready(())
13466            })
13467            .await;
13468            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
13469
13470            // An answer arrives while the service still owns the claim. A
13471            // fresh scheduling pass must apply it before declaring idle.
13472            let questions = Questions::at(home.join("questions"));
13473            let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13474            questions.put(&mut q).unwrap();
13475            drop(claim);
13476            // Model services that took longer than their cadence, without a
13477            // wall-clock sleep. The final scans must not respawn them even
13478            // though their receipts now permit another periodic invocation.
13479            let expired =
13480                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
13481            for service in [operation, "housekeeping"] {
13482                std::fs::write(
13483                    home.join("service-ticks").join(format!("daemon-{service}")),
13484                    &expired,
13485                )
13486                .unwrap();
13487            }
13488            job.status = crate::worker::Status::Finished;
13489            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13490            drop(lease);
13491            tokio::time::timeout(Duration::from_secs(2), drain)
13492                .await
13493                .expect("the settled service must allow the drain to finish")
13494                .unwrap();
13495            let after = queue.get(&task.id).unwrap();
13496            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
13497            assert!(after.action_applied(&q.id));
13498            for service in [operation, "housekeeping"] {
13499                assert_eq!(
13500                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
13501                        .unwrap(),
13502                    expired,
13503                    "the final once rescan must not restart {service}"
13504                );
13505            }
13506        }
13507    }
13508
13509    #[test]
13510    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
13511        let stop = Stop::new();
13512        stop.busy.store(1, Ordering::SeqCst);
13513        assert!(
13514            !stop.finishing(),
13515            "a busy loop nobody has asked to stop is just running"
13516        );
13517
13518        stop.stop();
13519        assert!(
13520            stop.finishing(),
13521            "a stop asked for mid-run has not landed until the run is settled"
13522        );
13523
13524        stop.busy.store(0, Ordering::SeqCst);
13525        assert!(
13526            !stop.finishing(),
13527            "once the run is settled the stop has landed and there is nothing to finish"
13528        );
13529    }
13530
13531    #[test]
13532    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
13533        let stop = Stop::new();
13534        stop.busy.store(2, Ordering::SeqCst);
13535        stop.stop();
13536        assert!(stop.finishing(), "two runs still in flight");
13537
13538        stop.busy.store(1, Ordering::SeqCst);
13539        assert!(
13540            stop.finishing(),
13541            "one run finished, but a sibling is still working"
13542        );
13543
13544        stop.busy.store(0, Ordering::SeqCst);
13545        assert!(
13546            !stop.finishing(),
13547            "the last run out is what actually lands the stop"
13548        );
13549    }
13550
13551    #[tokio::test]
13552    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
13553        let dir = tempfile::tempdir().unwrap();
13554        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13555        let stop = Stop::new();
13556        stop.stop();
13557
13558        let began = std::time::Instant::now();
13559        tokio::time::timeout(
13560            Duration::from_secs(2),
13561            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13562        )
13563        .await
13564        .expect("a stopped loop must return, not sit out its poll interval")
13565        .expect("the loop's own setup and teardown must not fail");
13566        assert!(
13567            began.elapsed() < opts.poll,
13568            "returned only after {:?}, which is a poll interval, not a stop",
13569            began.elapsed()
13570        );
13571    }
13572
13573    #[tokio::test]
13574    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
13575        let dir = tempfile::tempdir().unwrap();
13576        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13577        let stop = Stop::new();
13578
13579        // Asked for after the loop is already parked on its empty queue, which
13580        // is the case an operator tapping stop on a phone actually hits.
13581        let asker = {
13582            let stop = stop.clone();
13583            tokio::spawn(async move {
13584                tokio::time::sleep(Duration::from_millis(20)).await;
13585                stop.stop();
13586            })
13587        };
13588
13589        let began = std::time::Instant::now();
13590        tokio::time::timeout(
13591            Duration::from_secs(2),
13592            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13593        )
13594        .await
13595        .expect("a stop asked for while idle must wake the wait")
13596        .expect("the loop's own setup and teardown must not fail");
13597        asker.await.unwrap();
13598        assert!(
13599            began.elapsed() < opts.poll,
13600            "returned only after {:?}, so the stop waited on the sleep",
13601            began.elapsed()
13602        );
13603    }
13604
13605    #[tokio::test]
13606    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
13607        let dir = tempfile::tempdir().unwrap();
13608        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13609        let stop = Stop::new();
13610        stop.stop();
13611
13612        tokio::time::timeout(
13613            Duration::from_secs(2),
13614            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13615        )
13616        .await
13617        .expect("a stopped loop must return")
13618        .expect("the loop's own setup and teardown must not fail");
13619
13620        assert!(
13621            home.is_dir(),
13622            "the loop did publish a status file, so its removal is the teardown and not an absence"
13623        );
13624        assert!(
13625            !status_file.exists(),
13626            "a stopped loop clears its status file"
13627        );
13628        assert!(
13629            read_status(&home).is_none(),
13630            "a reader must see no daemon at all, not a heartbeat that merely stopped"
13631        );
13632    }
13633
13634    #[tokio::test]
13635    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
13636        let dir = tempfile::tempdir().unwrap();
13637        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13638
13639        let mut settled = RunState::new(
13640            dir.path().join("repo"),
13641            "main".to_owned(),
13642            "abc1234".to_owned(),
13643            "fixture".to_owned(),
13644            Config::default(),
13645        );
13646        settled.status = RunStatus::Ready;
13647        let run_dir = home.join("runs").join(&settled.id);
13648        std::fs::create_dir_all(&run_dir).unwrap();
13649        std::fs::write(
13650            run_dir.join("run.json"),
13651            serde_json::to_string_pretty(&settled).unwrap(),
13652        )
13653        .unwrap();
13654        let questions = Questions::at(home.join("questions"));
13655        let mut question = ask::Question::new(
13656            settled.id.clone(),
13657            "review".to_owned(),
13658            "reviewer-1".to_owned(),
13659            "Continue?".to_owned(),
13660            String::new(),
13661            Vec::new(),
13662        );
13663        questions.put(&mut question).unwrap();
13664
13665        run_service_worker(
13666            &home,
13667            serde_json::to_value(ServiceWorker {
13668                opts,
13669                queue: queue.root().to_path_buf(),
13670                worktrees_root: worktrees,
13671                operation: "housekeeping".to_owned(),
13672            })
13673            .unwrap(),
13674        )
13675        .await
13676        .unwrap();
13677
13678        assert_eq!(
13679            questions.get(&question.id).unwrap().status,
13680            ask::QuestionStatus::Abandoned,
13681            "the independent housekeeping worker settles ended-run questions"
13682        );
13683    }
13684
13685    #[test]
13686    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
13687        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13688
13689        assert!(
13690            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
13691            "never checked before: due at once"
13692        );
13693
13694        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
13695        assert!(
13696            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
13697            "well inside the interval: not due yet"
13698        );
13699
13700        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
13701        assert!(
13702            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
13703            "exactly at the edge: not yet due, same convention as `clean::due`"
13704        );
13705
13706        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
13707        assert!(
13708            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
13709            "past the interval: due again"
13710        );
13711    }
13712
13713    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
13714    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
13715    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
13716    /// and the congestion test below both need, and must not drift apart.
13717    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
13718        let config = dir.join("magi.toml");
13719        // A literal (single-quoted) TOML string, not a basic one: the cache
13720        // path is a Windows path full of backslashes, and a basic string
13721        // would have TOML try to interpret `\U` (from `\Users\...`) as a
13722        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
13723        // `{{ vars.cache }}` rendering documents.
13724        std::fs::write(
13725            &config,
13726            format!(
13727                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
13728                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
13729                cache_dir.display()
13730            ),
13731        )
13732        .unwrap();
13733        Opts {
13734            config: Some(config),
13735            repo: dir.join("repo"),
13736            ..Opts::default()
13737        }
13738    }
13739
13740    #[tokio::test]
13741    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
13742        let dir = tempfile::tempdir().unwrap();
13743        let home = dir.path().join("home");
13744        let cache_dir = dir.path().join("cache");
13745        std::fs::create_dir_all(&cache_dir).unwrap();
13746        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
13747        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
13748
13749        // Nobody has asked this daemon to stop, which is the ordinary case;
13750        // the skip that a stop buys is asserted by its own test below.
13751        let running = Stop::new();
13752        let mut last_checked = None;
13753        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13754        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
13755            .await;
13756        assert_eq!(
13757            crate::disk::dir_size(&cache_dir),
13758            0,
13759            "over the cap on the first check ever: pruned at once, no idle queue required"
13760        );
13761        assert_eq!(last_checked, Some(t0));
13762
13763        // A fresh oversized file lands, but the next check is not due yet.
13764        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
13765        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
13766        maybe_prune_cache_between_runs(
13767            &opts.repo,
13768            &opts,
13769            &home,
13770            &running,
13771            &mut last_checked,
13772            too_soon,
13773        )
13774        .await;
13775        assert_eq!(
13776            crate::disk::dir_size(&cache_dir),
13777            10,
13778            "too soon since the last check: left alone rather than rescanned every call"
13779        );
13780        assert_eq!(
13781            last_checked,
13782            Some(t0),
13783            "an idle check does not reset the clock"
13784        );
13785
13786        // Once the interval elapses, the same oversized cache is caught again.
13787        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
13788        maybe_prune_cache_between_runs(
13789            &opts.repo,
13790            &opts,
13791            &home,
13792            &running,
13793            &mut last_checked,
13794            due_again,
13795        )
13796        .await;
13797        assert_eq!(
13798            crate::disk::dir_size(&cache_dir),
13799            0,
13800            "due again: pruned back under the cap"
13801        );
13802    }
13803
13804    /// A stop must not queue behind housekeeping. The prune below is a
13805    /// synchronous walk of the whole cache with no await point in it, so a
13806    /// loop that entered it could not get back to its own `stopped()` test
13807    /// until the walk finished - and because no run is in flight at this
13808    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
13809    /// the stop had already landed. The idle branch has always made this same
13810    /// check before reaching `janitor`; the between-runs path makes it too.
13811    #[tokio::test]
13812    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
13813        let dir = tempfile::tempdir().unwrap();
13814        let home = dir.path().join("home");
13815        let cache_dir = dir.path().join("cache");
13816        std::fs::create_dir_all(&cache_dir).unwrap();
13817        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
13818        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
13819
13820        let stop = Stop::new();
13821        stop.stop();
13822        assert!(
13823            !stop.finishing(),
13824            "no run is in flight at a between-runs boundary, so nothing else \
13825             would tell the operator this stop had not taken effect yet"
13826        );
13827
13828        let mut last_checked = None;
13829        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13830        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
13831            .await;
13832        assert_eq!(
13833            crate::disk::dir_size(&cache_dir),
13834            10,
13835            "over its cap, and due for the first check ever, but a stop outranks \
13836             it: the cap is a standing policy the next start measures again"
13837        );
13838        assert_eq!(
13839            last_checked, None,
13840            "a check that never happened must not claim the interval"
13841        );
13842    }
13843
13844    /// A backlog must not starve cache pruning. The finite cache worker runs
13845    /// independently of queue drain and must not consume any task attempts.
13846    #[tokio::test]
13847    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
13848        let dir = tempfile::tempdir().unwrap();
13849        let cache_dir = dir.path().join("cache");
13850        std::fs::create_dir_all(&cache_dir).unwrap();
13851        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
13852
13853        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
13854        opts.poll = Duration::from_millis(20);
13855        opts.max_attempts = 1_000;
13856
13857        let queue = Queue::at(dir.path().join("queue"));
13858        for i in 0..128 {
13859            let mut task = Task::new(
13860                format!("queued work {i}"),
13861                format!("queued work {i}"),
13862                opts.repo.clone(),
13863                Source::Human,
13864            );
13865            queue.put(&mut task).unwrap();
13866        }
13867
13868        let home = dir.path().join("home");
13869        let worktrees = dir.path().join("wt");
13870        run_service_worker(
13871            &home,
13872            serde_json::to_value(ServiceWorker {
13873                opts,
13874                queue: queue.root().to_path_buf(),
13875                worktrees_root: worktrees,
13876                operation: "cache".to_owned(),
13877            })
13878            .unwrap(),
13879        )
13880        .await
13881        .unwrap();
13882        let after = queue.list();
13883        assert_eq!(after.len(), 128);
13884        assert!(
13885            after
13886                .iter()
13887                .all(|task| task.status.runnable() && task.attempts == 0)
13888        );
13889
13890        assert_eq!(
13891            crate::disk::dir_size(&cache_dir),
13892            0,
13893            "an oversized cache must not be left to grow unboundedly just because the \
13894             queue kept the loop busy the whole time"
13895        );
13896    }
13897
13898    #[test]
13899    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
13900        let dir = tempfile::tempdir().unwrap();
13901        let queue = Queue::at(dir.path().join("queue"));
13902        let questions = Questions::at(dir.path().join("questions"));
13903        let mut task = task();
13904        queue.put(&mut task).unwrap();
13905
13906        let mut task_question = ask::Question::new(
13907            task.id.clone(),
13908            crate::conduct::NODE.to_owned(),
13909            "conduct".to_owned(),
13910            "Which backend?".to_owned(),
13911            String::new(),
13912            Vec::new(),
13913        );
13914        questions.put(&mut task_question).unwrap();
13915        task.block(vec![task_question.id.clone()], None);
13916        queue.put(&mut task).unwrap();
13917
13918        let mut run_question = ask::Question::new(
13919            "20260101-000000-run1".to_owned(),
13920            "review".to_owned(),
13921            "reviewer-1".to_owned(),
13922            "Run question".to_owned(),
13923            String::new(),
13924            Vec::new(),
13925        );
13926        questions.put(&mut run_question).unwrap();
13927
13928        // A question from another node whose `run` happens to equal this
13929        // task's id — the same field, filled in for an unrelated reason. Only
13930        // `crate::conduct::NODE` questions use `run` as a task id; this one
13931        // must never be touched by this reconciliation, even after release.
13932        let mut coincidental = ask::Question::new(
13933            task.id.clone(),
13934            "review".to_owned(),
13935            "reviewer-1".to_owned(),
13936            "Unrelated review question".to_owned(),
13937            String::new(),
13938            Vec::new(),
13939        );
13940        questions.put(&mut coincidental).unwrap();
13941
13942        reconcile_task_questions(&queue, &questions);
13943        assert!(questions.get(&task_question.id).unwrap().status.open());
13944        assert!(questions.get(&run_question.id).unwrap().status.open());
13945        assert!(questions.get(&coincidental.id).unwrap().status.open());
13946
13947        task.release();
13948        queue.put(&mut task).unwrap();
13949        reconcile_task_questions(&queue, &questions);
13950        assert_eq!(
13951            questions.get(&task_question.id).unwrap().status,
13952            ask::QuestionStatus::Abandoned
13953        );
13954        assert!(
13955            questions.get(&run_question.id).unwrap().status.open(),
13956            "run questions remain the run janitor's responsibility"
13957        );
13958        assert!(
13959            questions.get(&coincidental.id).unwrap().status.open(),
13960            "a non-conductor question must not be abandoned just because its \
13961             run id coincides with a task id"
13962        );
13963    }
13964
13965    #[test]
13966    fn a_freshly_started_running_task_is_never_stalled() {
13967        let dir = tempfile::tempdir().unwrap();
13968        let mut t = task();
13969        t.start("run-1".to_owned());
13970        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
13971        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
13972        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
13973    }
13974
13975    #[test]
13976    fn a_long_running_task_with_no_live_daemon_is_stalled() {
13977        let dir = tempfile::tempdir().unwrap();
13978        let mut t = task();
13979        t.start("run-1".to_owned());
13980        t.updated_at = Timestamp::now()
13981            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
13982        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
13983        assert_eq!(
13984            stalled_tasks(
13985                &Queue::at(dir.path().join("q")),
13986                dir.path(),
13987                Timestamp::now()
13988            )
13989            .len(),
13990            0,
13991            "the task was never written to this queue"
13992        );
13993    }
13994
13995    #[test]
13996    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
13997        let dir = tempfile::tempdir().unwrap();
13998        let mut t = task();
13999        t.id = "20260903-080340-0167".to_owned();
14000        t.start("20260903-080619-01c2".to_owned());
14001        t.updated_at = Timestamp::now()
14002            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
14003
14004        let mut status = Status::new();
14005        status.current = vec![Current {
14006            worker: None,
14007            task: t.id.clone(),
14008            run: "20260903-080619-01c2".to_owned(),
14009        }];
14010        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
14011
14012        assert!(
14013            !is_stalled(&t, dir.path(), Timestamp::now()),
14014            "a live daemon's own heartbeat rules out stalled, however long the task has run"
14015        );
14016    }
14017
14018    /// Rewrite a task's `updated_at` on disk directly, bypassing
14019    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
14020    /// a fixture look like it has genuinely been `running` for a while.
14021    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
14022        let path = queue.path_of(id);
14023        let body = std::fs::read_to_string(&path).unwrap();
14024        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
14025        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
14026        v["updated_at"] = serde_json::Value::String(old.to_string());
14027        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
14028    }
14029
14030    #[test]
14031    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
14032        // The realistic `poll()` ordering, not `is_stalled` in isolation:
14033        // `reclaim_orphaned_running` runs first, on every poll, and settles
14034        // any `running` task whose claim it can actually take. For most
14035        // crashes that is immediate - a dead pid is proof enough for
14036        // `sweep_stale_claims` to drop the lock the same tick, and the very
14037        // next claim attempt succeeds. But a lock whose pid cannot be parsed
14038        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
14039        // `sweep_stale_claims`'s own doc), so the lock - and the claim
14040        // failure behind it - can legitimately outlive many polls. This is
14041        // exactly the gap `stalled_tasks` exists to surface well before that
14042        // six-hour sweep would: reclaim leaves the task `running`, and it
14043        // must still reach the conductor as stalled.
14044        let dir = tempfile::tempdir().unwrap();
14045        let queue = Queue::at(dir.path().join("queue"));
14046        let home = dir.path().join("home");
14047
14048        let mut t = task();
14049        t.id = "20260101-000001-lock".to_owned();
14050        t.start("run-1".to_owned());
14051        queue.put(&mut t).unwrap();
14052        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
14053        std::fs::write(
14054            dir.path().join("queue").join(format!("{}.lock", t.id)),
14055            "not a pid",
14056        )
14057        .unwrap();
14058
14059        let now = Timestamp::now();
14060        assert!(
14061            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
14062            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
14063             and reclaim must leave the task alone"
14064        );
14065        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14066
14067        let stalled = stalled_tasks(&queue, &home, now);
14068        assert_eq!(
14069            stalled.len(),
14070            1,
14071            "reclaim's inability to claim it yet must not hide it from the conductor"
14072        );
14073        assert_eq!(stalled[0].id, t.id);
14074    }
14075
14076    #[test]
14077    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
14078        let dir = tempfile::tempdir().unwrap();
14079        crate::run::set_home(dir.path().join("run-home"));
14080        let queue = Queue::at(dir.path().join("queue"));
14081        let home = dir.path().join("home");
14082        let questions = Questions::at(dir.path().join("questions"));
14083
14084        let mut t = task();
14085        t.id = "20260101-000003-dead".to_owned();
14086        t.start("missing-run".to_owned());
14087        queue.put(&mut t).unwrap();
14088        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
14089
14090        // This is the real poll ordering: retain the deterministic stalled
14091        // input before a claim proves the owner is gone and reclaims it.
14092        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
14093        assert_eq!(
14094            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
14095            [&t.id]
14096        );
14097        assert_eq!(
14098            reclaim_orphaned_running(&queue, 2, &Default::default()),
14099            [t.id.clone()]
14100        );
14101        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14102
14103        // Reclaim drops its guard before conductor decisions are applied, so
14104        // the decision for the captured stalled input has a real write path.
14105        crate::conduct::apply(
14106            &queue,
14107            &questions,
14108            &crate::conduct::Verdict {
14109                decisions: vec![crate::conduct::Decision {
14110                    id: t.id.clone(),
14111                    recovery: Some(crate::conduct::Recovery::Requeue),
14112                    ..crate::conduct::Decision::default()
14113                }],
14114            },
14115        )
14116        .unwrap();
14117        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14118    }
14119
14120    #[test]
14121    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
14122        let dir = tempfile::tempdir().unwrap();
14123        let queue = Queue::at(dir.path().join("queue"));
14124        let home = dir.path().join("home");
14125
14126        let mut fresh = task();
14127        fresh.id = "20260101-000001-aaaa".to_owned();
14128        fresh.start("run-1".to_owned());
14129        queue.put(&mut fresh).unwrap();
14130
14131        let mut old = task();
14132        old.id = "20260101-000002-bbbb".to_owned();
14133        old.start("run-2".to_owned());
14134        queue.put(&mut old).unwrap();
14135        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
14136
14137        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
14138        assert_eq!(stalled.len(), 1);
14139        assert_eq!(stalled[0].id, old.id);
14140    }
14141
14142    #[test]
14143    fn queued_and_finished_task_views_partition_by_status() {
14144        let dir = tempfile::tempdir().unwrap();
14145        let queue = Queue::at(dir.path().join("queue"));
14146
14147        let mut queued = task();
14148        queued.id = "20260101-000001-aaaa".to_owned();
14149        queue.put(&mut queued).unwrap();
14150
14151        let mut failed = task();
14152        failed.id = "20260101-000002-bbbb".to_owned();
14153        failed.start("run-1".to_owned());
14154        failed.fail("gate red", 5);
14155        queue.put(&mut failed).unwrap();
14156
14157        let mut held = task();
14158        held.id = "20260101-000003-cccc".to_owned();
14159        held.hold_machine(None);
14160        queue.put(&mut held).unwrap();
14161
14162        let mut running = task();
14163        running.id = "20260101-000004-dddd".to_owned();
14164        running.start("run-2".to_owned());
14165        queue.put(&mut running).unwrap();
14166
14167        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
14168        assert_eq!(queued_ids, [queued.id.clone()]);
14169
14170        let mut finished_ids: Vec<String> =
14171            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
14172        finished_ids.sort_unstable();
14173        let mut want = vec![failed.id.clone(), held.id.clone()];
14174        want.sort_unstable();
14175        assert_eq!(finished_ids, want);
14176    }
14177
14178    #[test]
14179    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
14180        for short in [false, true] {
14181            let dir = tempfile::tempdir().unwrap();
14182            let queue = Queue::at(dir.path().join("queue"));
14183            let questions = ask::Questions::at(dir.path().join("questions"));
14184            let mut running = task();
14185            running.id = "20261013-192213-feb2".into();
14186            running.start("existing-run".into());
14187            queue.put(&mut running).unwrap();
14188            let mut middle = task();
14189            middle.id = "20261013-193611-ca5b".into();
14190            middle.block(
14191                vec![if short {
14192                    "feb2".into()
14193                } else {
14194                    running.id.clone()
14195                }],
14196                None,
14197            );
14198            queue.put(&mut middle).unwrap();
14199            let mut waiting = task();
14200            waiting.id = "20261013-202849-ee37".into();
14201            waiting.block(
14202                vec![if short {
14203                    "ca5b".into()
14204                } else {
14205                    middle.id.clone()
14206                }],
14207                Some("wait for implementation".into()),
14208            );
14209            queue.put(&mut waiting).unwrap();
14210            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
14211            let inv = crate::blockers::Inventory::load(&queue, &questions);
14212            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
14213            assert!(inv.stuck().is_empty());
14214            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14215            assert!(report.quarantined.is_empty());
14216            assert!(report.asked.is_empty());
14217            resolve_blockers(&queue, &questions);
14218            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14219            assert!(questions.list().is_empty());
14220            // Finishing the transitive prerequisite alone does not satisfy
14221            // the task's direct dependency.
14222            running.succeed(CompletionContext::new(
14223                CompletionActor::DaemonSettle,
14224                None,
14225                dir.path(),
14226                &running,
14227            ));
14228            queue.put(&mut running).unwrap();
14229            resolve_blockers(&queue, &questions);
14230            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
14231            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14232            middle = queue.get(&middle.id).unwrap();
14233            middle.succeed(CompletionContext::new(
14234                CompletionActor::DaemonSettle,
14235                None,
14236                dir.path(),
14237                &middle,
14238            ));
14239            queue.put(&mut middle).unwrap();
14240            resolve_blockers(&queue, &questions);
14241            let after = queue.get(&waiting.id).unwrap();
14242            assert_eq!(after.status, TaskStatus::Queued);
14243            assert!(after.blocked_by.is_empty());
14244            assert_eq!(after.instruction, waiting.instruction);
14245        }
14246    }
14247
14248    #[test]
14249    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
14250        for future_schema in [false, true] {
14251            let name = "20261013-193611-ca5b";
14252            let mut future = task();
14253            future.id = name.into();
14254            future.schema = crate::queue::SCHEMA + 1;
14255            let contents = if future_schema {
14256                serde_json::to_string(&future).unwrap()
14257            } else {
14258                "corrupt".into()
14259            };
14260            let dir = tempfile::tempdir().unwrap();
14261            let queue = Queue::at(dir.path().join("queue"));
14262            let questions = ask::Questions::at(dir.path().join("questions"));
14263            let mut waiting = task();
14264            waiting.id = "20261013-202849-ee37".into();
14265            waiting.block(vec!["ca5b".into()], None);
14266            queue.put(&mut waiting).unwrap();
14267            std::fs::write(queue.path_of(name), contents).unwrap();
14268            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
14269            assert!(
14270                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
14271            );
14272            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14273            assert!(report.asked.is_empty());
14274            resolve_blockers(&queue, &questions);
14275            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14276            assert!(questions.list().is_empty());
14277        }
14278        let dir = tempfile::tempdir().unwrap();
14279        let queue = Queue::at(dir.path().join("queue"));
14280        let questions = ask::Questions::at(dir.path().join("questions"));
14281        let mut waiting = task();
14282        waiting.id = "20261013-202849-ee37".into();
14283        waiting.block(vec!["ca5b".into()], None);
14284        queue.put(&mut waiting).unwrap();
14285        let mut done = task();
14286        done.id = "20261013-193611-ca5b".into();
14287        done.succeed(CompletionContext::new(
14288            CompletionActor::Cli,
14289            None,
14290            dir.path(),
14291            &done,
14292        ));
14293        queue.put(&mut done).unwrap();
14294        // An unreadable second match must not disappear from uniqueness
14295        // checks just because Queue::list skips it.
14296        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
14297        assert!(queue.get("ca5b").is_err());
14298        assert_eq!(
14299            crate::queue::dependency(&queue, &questions, "ca5b"),
14300            crate::queue::Dependency::Ambiguous
14301        );
14302        resolve_blockers(&queue, &questions);
14303        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14304        assert!(report.asked.is_empty());
14305        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14306        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
14307    }
14308
14309    #[test]
14310    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
14311        for held in [false, true] {
14312            for question in [false, true] {
14313                for reference in ["ca5b", "20261013-193611-ca5b"] {
14314                    let dir = tempfile::tempdir().unwrap();
14315                    let queue = Queue::at(dir.path().join("queue"));
14316                    let questions = ask::Questions::at(dir.path().join("questions"));
14317                    let mut prerequisite = task();
14318                    prerequisite.id = "20261013-193611-ca5b".into();
14319                    prerequisite.start("existing-run".into());
14320                    queue.put(&mut prerequisite).unwrap();
14321                    let mut waiting = task();
14322                    waiting.id = "20261013-202849-ee37".into();
14323                    if held {
14324                        waiting.hold_machine(Some("waiting for separate consent".into()));
14325                    }
14326                    queue.put(&mut waiting).unwrap();
14327                    let reason = "Deleting saved data requires separate owner consent";
14328                    crate::conduct::apply(
14329                        &queue,
14330                        &questions,
14331                        &crate::conduct::Verdict {
14332                            decisions: vec![crate::conduct::Decision {
14333                                id: waiting.id.clone(),
14334                                blocked_by: vec![reference.into()],
14335                                question: question.then(|| "May the saved data be deleted?".into()),
14336                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
14337                                reason: Some(reason.into()),
14338                                ..crate::conduct::Decision::default()
14339                            }],
14340                        },
14341                    )
14342                    .unwrap();
14343                    let before = queue.get(&waiting.id).unwrap();
14344                    if question {
14345                        assert_eq!(before.status, TaskStatus::Blocked);
14346                        let q = questions.get(&before.blocked_by[0]).unwrap();
14347                        assert_eq!(q.summary, "May the saved data be deleted?");
14348                        assert!(q.status.open());
14349                    } else {
14350                        assert_eq!(before.status, TaskStatus::Held);
14351                        let recorded_reason = before.hold_reason.as_deref().unwrap();
14352                        assert!(recorded_reason.starts_with(reason));
14353                        if held {
14354                            assert!(recorded_reason.contains("waiting for separate consent"));
14355                        }
14356                    }
14357                    prerequisite.succeed(CompletionContext::new(
14358                        CompletionActor::DaemonSettle,
14359                        None,
14360                        dir.path(),
14361                        &prerequisite,
14362                    ));
14363                    queue.put(&mut prerequisite).unwrap();
14364                    resolve_blockers(&queue, &questions);
14365                    let after = queue.get(&waiting.id).unwrap();
14366                    assert_eq!(after.status, before.status);
14367                    assert_eq!(after.blocked_by, before.blocked_by);
14368                    assert_eq!(after.hold_reason, before.hold_reason);
14369                    assert_eq!(after.instruction, waiting.instruction);
14370                    if question {
14371                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
14372                    }
14373                    assert!(
14374                        queue.next_runnable().is_none(),
14375                        "dependency completion is not consent"
14376                    );
14377                }
14378            }
14379        }
14380    }
14381
14382    #[test]
14383    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
14384        let dir = tempfile::tempdir().unwrap();
14385        let queue = Queue::at(dir.path().join("queue"));
14386        let questions = ask::Questions::at(dir.path().join("questions"));
14387
14388        let mut dep = task();
14389        dep.id = "20260101-000001-dep0".to_owned();
14390        dep.succeed(CompletionContext::new(
14391            CompletionActor::DaemonSettle,
14392            None,
14393            dir.path(),
14394            &dep,
14395        ));
14396        queue.put(&mut dep).unwrap();
14397
14398        let mut still_going = task();
14399        still_going.id = "20260101-000002-dep1".to_owned();
14400        queue.put(&mut still_going).unwrap();
14401
14402        let mut blocked = task();
14403        blocked.id = "20260101-000003-main".to_owned();
14404        blocked.block(
14405            vec![dep.id.clone(), still_going.id.clone()],
14406            Some("waits on both".to_owned()),
14407        );
14408        queue.put(&mut blocked).unwrap();
14409
14410        resolve_blockers(&queue, &questions);
14411
14412        let after = queue.get(&blocked.id).unwrap();
14413        assert_eq!(
14414            after.status,
14415            TaskStatus::Blocked,
14416            "one dependency is still outstanding"
14417        );
14418        assert_eq!(after.blocked_by, [still_going.id.clone()]);
14419    }
14420
14421    #[test]
14422    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
14423        let dir = tempfile::tempdir().unwrap();
14424        let queue = Queue::at(dir.path().join("queue"));
14425        let questions = ask::Questions::at(dir.path().join("questions"));
14426
14427        let mut q = crate::ask::Question::new(
14428            "20260101-000001-main".to_owned(),
14429            crate::conduct::NODE.to_owned(),
14430            "conduct".to_owned(),
14431            "Which backend?".to_owned(),
14432            String::new(),
14433            Vec::new(),
14434        );
14435        questions.put(&mut q).unwrap();
14436        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
14437            .unwrap();
14438        questions.put(&mut q).unwrap();
14439
14440        let mut blocked = task();
14441        blocked.id = "20260101-000001-main".to_owned();
14442        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
14443        queue.put(&mut blocked).unwrap();
14444
14445        resolve_blockers(&queue, &questions);
14446
14447        let after = queue.get(&blocked.id).unwrap();
14448        assert_eq!(
14449            after.status,
14450            TaskStatus::Queued,
14451            "the only blocker resolved"
14452        );
14453        assert_eq!(after.answers.len(), 1);
14454        assert_eq!(after.answers[0].question, "Which backend?");
14455        assert_eq!(after.answers[0].answer, "SQLite");
14456
14457        // And the run this task starts next is told about it.
14458        let instruction = instruction_for(&after);
14459        assert!(instruction.contains("Which backend?"));
14460        assert!(instruction.contains("SQLite"));
14461    }
14462
14463    #[test]
14464    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
14465        let dir = tempfile::tempdir().unwrap();
14466        let queue = Queue::at(dir.path().join("queue"));
14467        let questions = ask::Questions::at(dir.path().join("questions"));
14468
14469        let mut q = crate::ask::Question::new(
14470            "20260101-000001-main".to_owned(),
14471            crate::conduct::NODE.to_owned(),
14472            "conduct".to_owned(),
14473            "Is the setup done?".to_owned(),
14474            String::new(),
14475            Vec::new(),
14476        );
14477        q.abandon("no answer within 60s of asking");
14478        questions.put(&mut q).unwrap();
14479
14480        let mut blocked = task();
14481        blocked.id = "20260101-000001-main".to_owned();
14482        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
14483        queue.put(&mut blocked).unwrap();
14484
14485        resolve_blockers(&queue, &questions);
14486
14487        let after = queue.get(&blocked.id).unwrap();
14488        assert_eq!(
14489            after.status,
14490            TaskStatus::Held,
14491            "never left blocked on nothing"
14492        );
14493        assert!(!after.operator_held(), "a machine hold, for triage");
14494        assert!(
14495            after
14496                .hold_reason
14497                .as_deref()
14498                .unwrap_or_default()
14499                .contains("went unanswered")
14500        );
14501    }
14502
14503    #[test]
14504    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
14505        // Reproduces the reported bug (task 3958): a task held out of
14506        // attempts, blocked on a `crate::conduct` follow-up question, must
14507        // come back `held` once that question is answered - never `queued`,
14508        // whatever the answer said - or it silently re-enters the
14509        // competition queue with its attempts already exhausted.
14510        let dir = tempfile::tempdir().unwrap();
14511        let queue = Queue::at(dir.path().join("queue"));
14512        let questions = ask::Questions::at(dir.path().join("questions"));
14513
14514        let mut q = crate::ask::Question::new(
14515            "20260101-000001-main".to_owned(),
14516            crate::conduct::NODE.to_owned(),
14517            "conduct".to_owned(),
14518            "How should this be handled?".to_owned(),
14519            String::new(),
14520            Vec::new(),
14521        );
14522        questions.put(&mut q).unwrap();
14523        q.answer(crate::ask::Answer::Text(
14524            "leave it held, a human will look at it later".to_owned(),
14525        ))
14526        .unwrap();
14527        questions.put(&mut q).unwrap();
14528
14529        let mut held = task();
14530        held.id = "20260101-000001-main".to_owned();
14531        held.hold_machine(Some("out of attempts".to_owned()));
14532        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
14533        queue.put(&mut held).unwrap();
14534
14535        resolve_blockers(&queue, &questions);
14536
14537        let after = queue.get(&held.id).unwrap();
14538        assert_eq!(after.status, TaskStatus::Held);
14539        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
14540        assert_eq!(
14541            after.answers[0].answer,
14542            "leave it held, a human will look at it later"
14543        );
14544    }
14545
14546    #[test]
14547    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
14548        let dir = tempfile::tempdir().unwrap();
14549        let queue = Queue::at(dir.path().join("queue"));
14550        let questions = ask::Questions::at(dir.path().join("questions"));
14551        let mut dep = task();
14552        dep.id = "20260101-000001-gone".to_owned();
14553        queue.put(&mut dep).unwrap();
14554        let mut blocked = task();
14555        blocked.id = "20260101-000003-main".to_owned();
14556        blocked.block(vec![dep.id.clone()], None);
14557        queue.put(&mut blocked).unwrap();
14558
14559        // Claimed, so `remove` cannot rewrite it and the resolver must.
14560        let claim = queue.claim(&blocked.id).unwrap();
14561        queue.remove(&dep.id, false, &questions).unwrap();
14562        drop(claim);
14563        resolve_blockers(&queue, &questions);
14564
14565        let after = queue.get(&blocked.id).unwrap();
14566        assert_eq!(after.status, TaskStatus::Queued);
14567        assert!(after.blocked_by.is_empty());
14568    }
14569
14570    #[test]
14571    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
14572        // Reproduces the reported bug: a task blocked on a task id that was
14573        // removed (`magi task rm`, or deleted by hand) can never see that id
14574        // reach `Done`, so the ordinary per-id loop has nothing to notice and
14575        // would otherwise leave the task `blocked` forever with no way for an
14576        // operator to find out why.
14577        let dir = tempfile::tempdir().unwrap();
14578        let queue = Queue::at(dir.path().join("queue"));
14579        let questions = ask::Questions::at(dir.path().join("questions"));
14580
14581        let mut still_going = task();
14582        still_going.id = "20260101-000002-dep1".to_owned();
14583        queue.put(&mut still_going).unwrap();
14584
14585        let mut blocked = task();
14586        blocked.id = "20260101-000003-main".to_owned();
14587        blocked.block(
14588            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
14589            Some("waits on both".to_owned()),
14590        );
14591        queue.put(&mut blocked).unwrap();
14592
14593        resolve_blockers(&queue, &questions);
14594
14595        let after = queue.get(&blocked.id).unwrap();
14596        assert_eq!(
14597            after.status,
14598            TaskStatus::Held,
14599            "a missing dependency must not leave the task blocked forever"
14600        );
14601        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
14602        assert!(after.blocked_by.is_empty());
14603        let reason = after.hold_reason.as_deref().unwrap_or_default();
14604        assert!(
14605            reason.contains("20260101-000001-gone"),
14606            "the missing id must be named so an operator can tell what happened: {reason}"
14607        );
14608        assert!(
14609            reason.contains(&still_going.id),
14610            "the still-valid dependency must not silently vanish from the record: {reason}"
14611        );
14612    }
14613
14614    #[test]
14615    fn instruction_for_is_unchanged_without_any_answers() {
14616        let t = task();
14617        assert_eq!(instruction_for(&t), t.instruction);
14618    }
14619
14620    #[test]
14621    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
14622        let dir = tempfile::tempdir().unwrap();
14623        let q = Queue::at(dir.path().join("queue"));
14624        let src = dir.path().join("shot.png");
14625        std::fs::write(&src, "x").unwrap();
14626        let mut t = task();
14627        q.attach(&mut t, &[src]).unwrap();
14628        let paths = task_attachments(&q, &t).unwrap();
14629        assert_eq!(paths.len(), 1);
14630        assert!(paths[0].is_absolute() && paths[0].is_file());
14631        std::fs::remove_file(&paths[0]).unwrap();
14632        let err = task_attachments(&q, &t).unwrap_err().to_string();
14633        assert!(err.contains("shot.png"), "{err}");
14634    }
14635
14636    #[tokio::test]
14637    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
14638        let dir = tempfile::tempdir().unwrap();
14639        let queue_path = dir.path().join("queue");
14640        let queue = Queue::at(queue_path.clone());
14641        let mut t = task();
14642        t.source = Source::Agent {
14643            run: "originating-chat".into(),
14644            node: crate::queue::CHAT_NODE.into(),
14645        };
14646        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
14647            stage: "config-fetch",
14648            target: "origin/main".into(),
14649        });
14650        record_config_failure(&mut t, &fetch);
14651        t.hold_machine(Some(format!("{fetch:#}")));
14652        let fetch_key = t.chat_notice_due().unwrap();
14653        t.chat_notices.push(fetch_key.clone());
14654        queue.put(&mut t).unwrap();
14655
14656        let queue = Queue::at(queue_path);
14657        let mut t = queue.get(&t.id).unwrap();
14658        let a = dir.path().join("a.toml");
14659        let b = dir.path().join("b.toml");
14660        for (path, text, new_cause) in [
14661            (&a, "[graph", true),
14662            (&a, "[verify", false),
14663            (&a, "[graph]\nimplementers = 'invalid-type'", true),
14664            (&b, "[graph]\nimplementers = 'invalid-type'", true),
14665        ] {
14666            t.release_operator("test", None);
14667            std::fs::write(path, text).unwrap();
14668            let error = Config::discover_fetched(dir.path(), Some(path))
14669                .await
14670                .unwrap_err();
14671            record_config_failure(&mut t, &error);
14672            t.hold_machine(Some(format!("{error:#}")));
14673            let due = t.chat_notice_due();
14674            assert_eq!(due.is_some(), new_cause, "{error:#}");
14675            if let Some(key) = due {
14676                assert_ne!(key, fetch_key);
14677                t.chat_notices.push(key);
14678            }
14679        }
14680        t.succeed(CompletionContext::new(
14681            CompletionActor::DaemonSettle,
14682            None,
14683            dir.path(),
14684            &t,
14685        ));
14686        assert_eq!(
14687            t.chat_notice_due(),
14688            Some(format!(
14689                "done:{}",
14690                t.completion_history.last().unwrap().occurrence
14691            ))
14692        );
14693    }
14694
14695    #[test]
14696    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
14697        let dir = tempfile::tempdir().unwrap();
14698        let queue_path = dir.path().join("queue");
14699        let queue = Queue::at(queue_path.clone());
14700        let mut t = task();
14701        t.source = crate::queue::Source::Agent {
14702            run: "originating-chat".into(),
14703            node: crate::queue::CHAT_NODE.into(),
14704        };
14705        let a = dir.path().join("a.png");
14706        let b = dir.path().join("b.png");
14707        std::fs::write(&a, "a").unwrap();
14708        std::fs::write(&b, "b").unwrap();
14709        queue.attach(&mut t, &[a, b]).unwrap();
14710        let paths = task_attachments(&queue, &t).unwrap();
14711        for path in &paths {
14712            std::fs::remove_file(path).unwrap();
14713        }
14714        let missing = task_attachments(&queue, &t).unwrap_err();
14715        t.attempts += 1;
14716        let reason = missing.to_string();
14717        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
14718        let first = t.chat_notice_due().expect("first attachment notice");
14719        t.chat_notices.push(first.clone());
14720        queue.put(&mut t).unwrap();
14721
14722        let queue = Queue::at(queue_path.clone());
14723        let mut t = queue.get(&t.id).unwrap();
14724        assert!(t.chat_notice_due().is_none(), "restart does not replay");
14725        t.release_operator("test", None);
14726        t.attempts += 1;
14727        let missing = task_attachments(&queue, &t).unwrap_err();
14728        t.fail_startup_target(
14729            "startup-attachments",
14730            missing.name,
14731            "same missing attachment with regenerated wording",
14732            1,
14733        );
14734        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
14735
14736        std::fs::write(&paths[0], "restored").unwrap();
14737        t.release_operator("test", None);
14738        t.attempts += 1;
14739        let missing = task_attachments(&queue, &t).unwrap_err();
14740        let reason = missing.to_string();
14741        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
14742        let second = t
14743            .chat_notice_due()
14744            .expect("different attachment must notify");
14745        assert_ne!(first, second);
14746        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
14747    }
14748
14749    #[test]
14750    fn resumed_instruction_is_unchanged_without_any_answers() {
14751        let t = task();
14752        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
14753    }
14754
14755    #[test]
14756    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
14757        let mut t = task();
14758        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14759        // The run's own instruction on disk predates the answer: it is the
14760        // plain original text `Runner::start` saved before the operator was
14761        // ever asked anything.
14762        let old = t.instruction.clone();
14763
14764        let refreshed = resumed_instruction(&old, &t);
14765        assert!(refreshed.starts_with(&old), "the original text is kept");
14766        assert!(refreshed.contains("Which backend?"));
14767        assert!(refreshed.contains("SQLite"));
14768    }
14769
14770    #[test]
14771    fn resumed_instruction_keeps_an_original_answers_heading() {
14772        let mut t = task();
14773        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
14774        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14775
14776        let refreshed = resumed_instruction(&t.instruction, &t);
14777
14778        assert!(
14779            refreshed.starts_with(&t.instruction),
14780            "an answers heading in the original instruction is not the appended block"
14781        );
14782        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
14783        assert!(refreshed.contains("Which backend?"));
14784        assert!(refreshed.contains("SQLite"));
14785
14786        let repeated = resumed_instruction(&refreshed, &t);
14787        assert_eq!(
14788            repeated, refreshed,
14789            "only the final appended block is refreshed"
14790        );
14791    }
14792
14793    #[test]
14794    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
14795        let mut t = task();
14796        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14797
14798        // A first resume appends the block; a second resume of the same run,
14799        // with no new answer in between, must reproduce exactly the same
14800        // text rather than appending the block a second time.
14801        let once = resumed_instruction(&t.instruction, &t);
14802        let twice = resumed_instruction(&once, &t);
14803        assert_eq!(once, twice);
14804        assert_eq!(once.matches("Which backend?").count(), 1);
14805
14806        // A later answer replaces the block wholesale rather than growing it.
14807        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
14808        let refreshed = resumed_instruction(&once, &t);
14809        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
14810        assert!(refreshed.contains("Which backend?"));
14811        assert!(refreshed.contains("Which cache?"));
14812    }
14813
14814    #[test]
14815    fn prepare_instruction_covers_all_three_starters() {
14816        let mut t = task();
14817        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14818
14819        // Start: a fresh run gets the task text plus every answer so far —
14820        // exactly `instruction_for`.
14821        assert_eq!(
14822            prepare_instruction(&Starter::Start, None, &t),
14823            Some(instruction_for(&t))
14824        );
14825
14826        // Resume: the run's prior instruction is refreshed with the answer,
14827        // not discarded and not left stale.
14828        let old = t.instruction.clone();
14829        assert_eq!(
14830            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
14831            Some(resumed_instruction(&old, &t))
14832        );
14833
14834        // Review: a review-only pass builds its own instruction from the
14835        // branch's history in `crate::graph`, with no task statement at all -
14836        // this boundary must leave it alone.
14837        assert_eq!(
14838            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
14839            None
14840        );
14841    }
14842
14843    #[test]
14844    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
14845        assert_eq!(
14846            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
14847            Starter::Review("magi/eba2/A".to_owned())
14848        );
14849    }
14850
14851    #[test]
14852    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
14853        assert_eq!(
14854            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
14855            Starter::Start,
14856            "a vanished review branch must not fall back to resuming the old run either"
14857        );
14858    }
14859
14860    #[test]
14861    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
14862        let mut t = task();
14863        t.start("old-run".to_owned());
14864        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
14865        t.release();
14866        let branch = t.review_branch.take();
14867        assert_eq!(
14868            choose_starter(branch.as_deref(), true, Some("old-run")),
14869            Starter::Review("magi/eba2/A".to_owned()),
14870            "a review wins over resuming the old run"
14871        );
14872    }
14873
14874    #[test]
14875    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
14876        assert_eq!(
14877            choose_starter(None, false, Some("some-run")),
14878            Starter::Resume("some-run".to_owned())
14879        );
14880        assert_eq!(choose_starter(None, false, None), Starter::Start);
14881    }
14882
14883    #[test]
14884    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
14885        let mut released = task();
14886        released.start("stalled-run".to_owned());
14887        released.requeue();
14888        let unfinished = (!released.fresh_start)
14889            .then(|| Some("stalled-run".to_owned()))
14890            .flatten();
14891        assert_eq!(
14892            choose_starter(None, false, unfinished.as_deref()),
14893            Starter::Start,
14894            "release keeps run history but must not resume it"
14895        );
14896        assert_eq!(released.runs, ["stalled-run"]);
14897    }
14898
14899    #[test]
14900    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
14901        let dir = tempfile::tempdir().unwrap();
14902        let queue = Queue::at(dir.path().join("queue"));
14903        let mut state = run_state(RunStatus::Blocked);
14904        state.merge_decision = Some(crate::merge_decision::Decision {
14905            question: "hold-inquiry".into(),
14906            target: crate::merge_decision::Target {
14907                pr: "https://example.test/pull/1".into(),
14908                head: "reviewed-head".into(),
14909                language: "en".into(),
14910            },
14911            choice: land::HOLD.into(),
14912            closed: false,
14913            replacement_run: None,
14914            replacement_pr: None,
14915        });
14916        let mut t = task();
14917        t.start(state.id.clone());
14918        settle_and_diagnose(
14919            &mut t,
14920            Verdict {
14921                status: RunStatus::Blocked,
14922                left_pr: true,
14923                quota_hit: false,
14924                parked: false,
14925                no_viable_candidates: false,
14926            },
14927            "held",
14928            2,
14929            &state,
14930        );
14931        queue.put(&mut t).unwrap();
14932        t.release_operator("chat", None);
14933        t.edit("revised".into(), "revised instruction".into())
14934            .unwrap();
14935        queue.put(&mut t).unwrap();
14936        drop(state);
14937        assert_eq!(
14938            queue
14939                .get(&t.id)
14940                .unwrap()
14941                .decision_effects
14942                .get("hold-inquiry"),
14943            Some(&format!("decision: {}", land::HOLD))
14944        );
14945    }
14946
14947    fn stopped_public_run(status: RunStatus) -> RunState {
14948        let mut state = run_state(status);
14949        state.driver_exited = true;
14950        state.config.graph.land = true;
14951        state.config.graph.review_rounds = 1;
14952        state.reviews = vec![review_round(1)];
14953        state.merge = Some(crate::run::MergeOutcome {
14954            mode: MergeMode::Pr,
14955            ok: false,
14956            detail: "landing stopped".into(),
14957            empty: false,
14958        });
14959        state.pr = Some(crate::run::PrRecord {
14960            url: "https://example.test/pull/1".into(),
14961            number: 1,
14962            state: "open".into(),
14963            checks: "red".into(),
14964            round: 1,
14965            rounds: 1,
14966            red_at_merge: Vec::new(),
14967        });
14968        state
14969    }
14970
14971    #[test]
14972    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
14973        for status in [RunStatus::Blocked, RunStatus::Gating] {
14974            let home = tempfile::tempdir().unwrap();
14975            let mut state = stopped_public_run(status);
14976            state.save_under(home.path()).unwrap();
14977            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
14978            assert!(!exhausted_review_budget(&state));
14979            let mut task = held_task_with(&state.id);
14980            task.release();
14981            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
14982            assert_eq!(
14983                choose_starter(None, false, unfinished.as_deref()),
14984                Starter::Resume(state.id.clone())
14985            );
14986            let question = action_question(&state.id, resume_action(&state.id));
14987            assert_eq!(
14988                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
14989                    state.clone()
14990                )),
14991                ActionDecision::Resume(state.id.clone())
14992            );
14993            // The control-plane command uses this same preflight before pinning.
14994            assert_eq!(
14995                crate::resume::validate(home.path(), &state.id).unwrap().id,
14996                state.id
14997            );
14998            let queue = Queue::at(home.path().join("queue"));
14999            let mut controlled = Task::new(
15000                "resume land".into(),
15001                state.instruction.clone(),
15002                state.repo.clone(),
15003                Source::Agent {
15004                    run: "talk".into(),
15005                    node: crate::queue::CHAT_NODE.into(),
15006                },
15007            );
15008            controlled.runs.push(state.id.clone());
15009            controlled.hold_machine(Some("land stopped".into()));
15010            queue.put(&mut controlled).unwrap();
15011            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
15012            assert_eq!(resumed.status, TaskStatus::Queued);
15013            assert_eq!(
15014                resumed.resume_override.unwrap().pinned_run,
15015                Some(state.id.clone())
15016            );
15017            assert_eq!(resumed.attempts, 0);
15018        }
15019    }
15020
15021    #[test]
15022    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
15023        for review_rounds in [0, 1] {
15024            let home = tempfile::tempdir().unwrap();
15025            let mut state = run_state(RunStatus::Blocked);
15026            state.config.graph.review_rounds = review_rounds;
15027            if review_rounds > 0 {
15028                let mut review = review_round(1);
15029                review.clean = true;
15030                state.reviews = vec![review];
15031            }
15032            state.gate_ran = true;
15033            state.gate = vec![crate::run::CommandOutcome {
15034                command: "verify".into(),
15035                code: Some(1),
15036                output_tail: "gate failed after repair budget exhausted".into(),
15037                duration_ms: 0,
15038                resource_blocked: false,
15039                ..Default::default()
15040            }];
15041            state.save_under(home.path()).unwrap();
15042            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
15043            assert!(exhausted_review_budget(&state));
15044            let mut task = held_task_with(&state.id);
15045            task.release();
15046            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
15047            let question = action_question(&state.id, resume_action(&state.id));
15048            assert_ne!(
15049                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15050                    state.clone()
15051                )),
15052                ActionDecision::Resume(state.id.clone())
15053            );
15054            let error = crate::resume::validate(home.path(), &state.id)
15055                .unwrap_err()
15056                .to_string();
15057            assert!(!error.contains("review budget exhausted"), "{error}");
15058            assert!(
15059                error.contains(if review_rounds == 0 {
15060                    "review is disabled"
15061                } else {
15062                    "gate already ran"
15063                }),
15064                "{error}"
15065            );
15066
15067            // An unexecuted gate still has work to do with or without reviews.
15068            state.gate_ran = false;
15069            state.gate.clear();
15070            assert!(!exhausted_review_budget(&state));
15071            assert_eq!(
15072                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
15073                Some(state.id)
15074            );
15075        }
15076    }
15077
15078    #[test]
15079    fn sequencer_resource_resume_keeps_the_reserved_run_after_review_exhaustion() {
15080        let home = tempfile::tempdir().unwrap();
15081        let mut state = run_state(RunStatus::Blocked);
15082        state.config.graph.review_rounds = 1;
15083        let mut unresolved = review_round(1);
15084        unresolved.blocking = 1;
15085        unresolved.e2e.push(crate::run::CommandOutcome {
15086            command: "verify".into(),
15087            code: Some(1),
15088            output_tail: "previous verification failed".into(),
15089            duration_ms: 0,
15090            resource_blocked: false,
15091            artifact: None,
15092            failure_evidence: None,
15093            rerun_comparison: None,
15094        });
15095        state.reviews.push(unresolved);
15096        state.base_sync = Some(crate::run::BaseSync {
15097            tip: "base".into(),
15098            behind: 1,
15099            attempts: 0,
15100            conflict: None,
15101            already_in: None,
15102        });
15103        state.reserve_base_operation("winner", "base");
15104        state.resource_block = Some(crate::run::ResourceBlock {
15105            cause: crate::run::ResourceBlockCause::Other,
15106            node: "rebase".into(),
15107            kind: crate::rebase::SEQUENCER_INFRASTRUCTURE.into(),
15108            detail: "recording exec failed".into(),
15109            at: jiff::Timestamp::now(),
15110        });
15111        state.save_under(home.path()).unwrap();
15112        assert_eq!(
15113            crate::resume::validate(home.path(), &state.id).unwrap().id,
15114            state.id
15115        );
15116        assert_eq!(
15117            crate::repair_budget::legacy::classify(&state, "winner", "base").class,
15118            crate::repair_budget::legacy::Class::SequencerInfrastructure
15119        );
15120        state.finish_base_operation(None);
15121        state.save_under(home.path()).unwrap();
15122        assert!(crate::resume::validate(home.path(), &state.id).is_err());
15123    }
15124
15125    #[test]
15126    fn resource_blocked_verification_resumes_the_same_run() {
15127        for (kind, stage) in [
15128            ("cache", "clean"),
15129            ("coordination", "clean"),
15130            ("cache", "review-e2e"),
15131            ("coordination", "no-reviews"),
15132            ("coordination", "handoff"),
15133        ] {
15134            let home = tempfile::tempdir().unwrap();
15135            let mut state = run_state(RunStatus::Blocked);
15136            state.config.graph.review_rounds = 1;
15137            let mut review = review_round(1);
15138            review.clean = true;
15139            state.reviews = vec![review];
15140            if stage == "review-e2e" {
15141                let review = &mut state.reviews[0];
15142                review.clean = false;
15143                review.blocking = 1;
15144                review.e2e = vec![crate::run::CommandOutcome {
15145                    command: "verify".into(),
15146                    code: None,
15147                    output_tail: "resource wait expired".into(),
15148                    duration_ms: 0,
15149                    resource_blocked: true,
15150                    ..Default::default()
15151                }];
15152            } else if stage == "no-reviews" {
15153                state.config.graph.review_rounds = 0;
15154                state.reviews.clear();
15155            } else if stage == "handoff" {
15156                // A completed final verification can hand off to the gate
15157                // even when the review still carries contested findings.
15158                let review = &mut state.reviews[0];
15159                review.clean = false;
15160                review.blocking = 1;
15161                review.e2e = vec![crate::run::CommandOutcome {
15162                    command: "verify".into(),
15163                    code: Some(0),
15164                    output_tail: String::new(),
15165                    duration_ms: 0,
15166                    resource_blocked: false,
15167                    ..Default::default()
15168                }];
15169            }
15170            state.gate_ran = false;
15171            state.resource_block = Some(crate::run::ResourceBlock {
15172                cause: crate::run::ResourceBlockCause::Other,
15173                node: if stage == "review-e2e" {
15174                    "review"
15175                } else {
15176                    "gate"
15177                }
15178                .into(),
15179                kind: kind.into(),
15180                detail: "resource wait expired".into(),
15181                at: jiff::Timestamp::now(),
15182            });
15183            state.save_under(home.path()).unwrap();
15184            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
15185            assert!(!exhausted_review_budget(&state));
15186            let mut task = held_task_with(&state.id);
15187            task.release();
15188            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
15189            assert_eq!(
15190                choose_starter(None, false, unfinished.as_deref()),
15191                Starter::Resume(state.id.clone())
15192            );
15193            let question = action_question(&state.id, resume_action(&state.id));
15194            assert_eq!(
15195                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15196                    state.clone()
15197                )),
15198                ActionDecision::Resume(state.id.clone())
15199            );
15200            assert_eq!(
15201                crate::resume::validate(home.path(), &state.id).unwrap().id,
15202                state.id
15203            );
15204            let queue = Queue::at(home.path().join("queue"));
15205            let mut controlled = Task::new(
15206                "resume verification".into(),
15207                state.instruction.clone(),
15208                state.repo.clone(),
15209                Source::Agent {
15210                    run: "talk".into(),
15211                    node: crate::queue::CHAT_NODE.into(),
15212                },
15213            );
15214            controlled.runs.push(state.id.clone());
15215            controlled.hold_machine(Some("verification resource unavailable".into()));
15216            queue.put(&mut controlled).unwrap();
15217            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
15218            assert_eq!(resumed.status, TaskStatus::Queued);
15219            assert_eq!(
15220                resumed.resume_override.unwrap().pinned_run,
15221                Some(state.id.clone())
15222            );
15223            assert_eq!(resumed.attempts, 0);
15224
15225            // A genuinely unresolved final review still exhausts the budget.
15226            state.config.graph.review_rounds = 1;
15227            let mut unresolved = review_round(1);
15228            unresolved.blocking = 1;
15229            state.reviews = vec![unresolved];
15230            state.resource_block = None;
15231            state.save_under(home.path()).unwrap();
15232            assert!(exhausted_review_budget(&state));
15233            assert!(crate::resume::validate(home.path(), &state.id).is_err());
15234        }
15235    }
15236
15237    #[tokio::test]
15238    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
15239        if !crate::standalone_test(
15240            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
15241        ) {
15242            return;
15243        }
15244        let home = tempfile::tempdir().unwrap();
15245        let mut owner = stopped_public_run(RunStatus::Blocked);
15246        owner.save_under(home.path()).unwrap();
15247        let history = vec![owner.id.clone()];
15248        let repo = owner.repo.clone();
15249        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
15250        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
15251        let initial =
15252            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
15253        assert!(
15254            initial.is_pending(),
15255            "a busy record must not hold or resume the task"
15256        );
15257        owner.retired_to = Some("20260101-000001-bbbb".into());
15258        owner.save_under(home.path()).unwrap();
15259        drop(lock);
15260        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
15261            .await
15262            .expect("ownership lock released")
15263            .expect("read settled owner");
15264        assert!(
15265            result.is_none(),
15266            "the retired owner must not be resumed from a stale read"
15267        );
15268    }
15269
15270    #[tokio::test]
15271    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
15272        if !crate::standalone_test(
15273            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
15274        ) {
15275            return;
15276        }
15277        let home = tempfile::tempdir().unwrap();
15278        let mut owner = stopped_public_run(RunStatus::Blocked);
15279        let repo = tempfile::tempdir().unwrap();
15280        crate::git::git(repo.path(), &["init"]).await.unwrap();
15281        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
15282        owner.id = "20260101-000000-aaaa".into();
15283        owner.save_under(home.path()).unwrap();
15284        let mut successor = run_state(RunStatus::Blocked);
15285        successor.id = "20260101-000001-bbbb".into();
15286        successor.save_under(home.path()).unwrap();
15287        let runs = vec![owner.id.clone(), successor.id.clone()];
15288        assert_eq!(
15289            public_resume_owner(home.path(), &runs, &owner.repo)
15290                .await
15291                .unwrap()
15292                .unwrap()
15293                .id,
15294            owner.id
15295        );
15296        let subdir = owner.repo.join("nested");
15297        std::fs::create_dir(&subdir).unwrap();
15298        assert_eq!(
15299            public_resume_owner(home.path(), &runs, &subdir)
15300                .await
15301                .unwrap()
15302                .unwrap()
15303                .id,
15304            owner.id
15305        );
15306        #[cfg(unix)]
15307        {
15308            let alias = home.path().join("repo-alias");
15309            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
15310            assert_eq!(
15311                public_resume_owner(home.path(), &runs, &alias.join("nested"))
15312                    .await
15313                    .unwrap()
15314                    .unwrap()
15315                    .id,
15316                owner.id
15317            );
15318        }
15319        let different = tempfile::tempdir().unwrap();
15320        crate::git::git(different.path(), &["init"]).await.unwrap();
15321        assert!(
15322            public_resume_owner(home.path(), &runs, different.path())
15323                .await
15324                .is_err()
15325        );
15326        std::fs::remove_file(
15327            home.path()
15328                .join("runs")
15329                .join(&successor.id)
15330                .join("run.json"),
15331        )
15332        .unwrap();
15333        assert!(
15334            public_resume_owner(home.path(), &runs, &owner.repo)
15335                .await
15336                .is_err()
15337        );
15338    }
15339
15340    #[test]
15341    fn an_ordinary_release_keeps_a_resumable_run_available() {
15342        let mut released = task();
15343        released.start("stalled-run".to_owned());
15344        released.release();
15345        let unfinished = (!released.fresh_start)
15346            .then(|| Some("stalled-run".to_owned()))
15347            .flatten();
15348        assert_eq!(
15349            choose_starter(None, false, unfinished.as_deref()),
15350            Starter::Resume("stalled-run".to_owned()),
15351            "manual release must preserve the normal resume path"
15352        );
15353    }
15354
15355    #[test]
15356    fn resume_refusals_explain_admission_without_changing_task_or_run() {
15357        use crate::handover::{ResumeRefusal, resume_refusal_under};
15358        let home = tempfile::tempdir().unwrap();
15359        let mut exhausted = run_state(RunStatus::Blocked);
15360        exhausted.driver_exited = true;
15361        exhausted.config.graph.review_rounds = 3;
15362        exhausted.reviews = (1..=3).map(review_round).collect();
15363        for refusal in [
15364            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
15365            ResumeRefusal::Status(RunStatus::Ready),
15366            ResumeRefusal::Released("20261022-000000-aaaa".into()),
15367            ResumeRefusal::Retired("retirement-successor".into()),
15368            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
15369        ] {
15370            let mut state = exhausted.clone();
15371            let expected = match refusal {
15372                ResumeRefusal::Status(_) => {
15373                    state.status = RunStatus::Ready;
15374                    "status `ready`"
15375                }
15376                ResumeRefusal::Released(ref target) => {
15377                    state.released_to = Some(target.clone());
15378                    "execution was released"
15379                }
15380                ResumeRefusal::Retired(ref target) => {
15381                    state.retired_to = Some(target.clone());
15382                    "execution was retired"
15383                }
15384                ResumeRefusal::OwnershipTransferred(ref target) => {
15385                    state.pr_taken_over_by = Some(target.clone());
15386                    "PR ownership was transferred"
15387                }
15388                _ => "review budget exhausted (3/3 rounds used)",
15389            };
15390            assert_eq!(
15391                resume_refusal_under(&state, Some(home.path())),
15392                Some(refusal.clone())
15393            );
15394            assert_eq!(
15395                refusal.successor(),
15396                state
15397                    .released_to
15398                    .as_deref()
15399                    .or(state.retired_to.as_deref())
15400                    .or(state.pr_taken_over_by.as_deref())
15401            );
15402            state.save_under(home.path()).unwrap();
15403            let queue = Queue::at(home.path().join("queue"));
15404            let mut task = Task::new(
15405                "retained implementation".into(),
15406                state.instruction.clone(),
15407                state.repo.clone(),
15408                Source::Agent {
15409                    run: "talk".into(),
15410                    node: crate::queue::CHAT_NODE.into(),
15411                },
15412            );
15413            task.runs.push(state.id.clone());
15414            task.hold_machine(Some("stopped".into()));
15415            queue.put(&mut task).unwrap();
15416            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
15417            let before_run = serde_json::to_value(&state).unwrap();
15418            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
15419                .unwrap_err()
15420                .to_string();
15421            assert!(error.contains(expected), "{error}");
15422            assert!(!error.contains("only a stalled or blocked"), "{error}");
15423            if matches!(refusal, ResumeRefusal::Status(_)) {
15424                assert!(
15425                    error.contains("is final; there is nothing left to resume"),
15426                    "{error}"
15427                );
15428            }
15429            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
15430                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
15431                assert!(error.contains("review-only successor with a new review budget"));
15432                assert!(error.contains("does not resume this run"));
15433            }
15434            for target in [
15435                &state.released_to,
15436                &state.retired_to,
15437                &state.pr_taken_over_by,
15438            ]
15439            .into_iter()
15440            .flatten()
15441            {
15442                let short = if state.retired_to.as_ref() == Some(target) {
15443                    target.as_str()
15444                } else {
15445                    crate::run::short_of(target)
15446                };
15447                assert!(
15448                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
15449                    "{error}"
15450                );
15451                if short != target {
15452                    assert!(!error.contains(target), "full successor id leaked: {error}");
15453                }
15454            }
15455            assert_eq!(
15456                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
15457                before_task
15458            );
15459            assert_eq!(
15460                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
15461                    .unwrap(),
15462                before_run
15463            );
15464            let question = action_question(&state.id, resume_action(&state.id));
15465            for phrases in [&PHRASES_EN, &PHRASES_JA] {
15466                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
15467                    RunState::load_under(id, home.path())
15468                });
15469                let ActionDecision::Refuse(detail) = decision else {
15470                    panic!(
15471                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
15472                        state.id,
15473                        home.path().display()
15474                    );
15475                };
15476                assert!(detail.contains(expected), "{detail}");
15477            }
15478        }
15479        // Preserve predicate ordering, while keeping every recorded destination visible.
15480        exhausted.status = RunStatus::Ready;
15481        exhausted.released_to = Some("released".into());
15482        exhausted.retired_to = Some("retired".into());
15483        exhausted.pr_taken_over_by = Some("owner".into());
15484        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
15485        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
15486        let detail = reason.diagnostic(&exhausted);
15487        for target in ["released", "retired", "owner"] {
15488            assert!(detail.contains(&format!("magi show {target}")));
15489        }
15490    }
15491
15492    #[test]
15493    fn resume_action_ignores_question_checkpoints_in_another_home() {
15494        crate::run::pin_test_home();
15495        let home = tempfile::tempdir().unwrap();
15496        let mut state = run_state(RunStatus::Blocked);
15497        // The private directory reserves this fixture's identity even while
15498        // other tests write questions into the process-wide store.
15499        state.id = format!(
15500            "resume-context-{}",
15501            home.path().file_name().unwrap().to_str().unwrap()
15502        );
15503        state.driver_exited = true;
15504        state.config.graph.review_rounds = 1;
15505        state.reviews = vec![review_round(1)];
15506        state.save_under(home.path()).unwrap();
15507        let task = held_task_with(&state.id);
15508        let answer = action_question(&state.id, resume_action(&state.id));
15509        let mut checkpoint = approval_question(&state.id);
15510        let foreign = Questions::open();
15511        foreign.put(&mut checkpoint).unwrap();
15512        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
15513        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
15514            RunState::load_under(id, home.path())
15515        });
15516        let matching: Vec<_> = foreign
15517            .list()
15518            .into_iter()
15519            .filter(|q| q.run == state.id && q.status.open())
15520            .collect();
15521        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
15522        assert!(
15523            matches!(decision, ActionDecision::Refuse(_)),
15524            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
15525            state.id,
15526            home.path().display(),
15527            crate::run::test_home().display()
15528        );
15529        assert_eq!(
15530            refusal,
15531            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
15532        );
15533        let local = Questions::at(home.path().join("questions"));
15534        for status in [
15535            ask::QuestionStatus::Open,
15536            ask::QuestionStatus::Answered,
15537            ask::QuestionStatus::Abandoned,
15538        ] {
15539            let mut question = checkpoint.clone();
15540            match status {
15541                ask::QuestionStatus::Open => {}
15542                ask::QuestionStatus::Answered => {
15543                    question
15544                        .answer(ask::Answer::Choice(question.choices[0].clone()))
15545                        .unwrap();
15546                }
15547                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
15548            }
15549            local.put(&mut question).unwrap();
15550            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
15551                RunState::load_under(id, home.path())
15552            });
15553            if status.open() {
15554                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
15555            } else {
15556                assert!(
15557                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
15558                    "status={status:?}, decision={decision:?}"
15559                );
15560            }
15561        }
15562    }
15563
15564    #[test]
15565    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
15566        let home = tempfile::tempdir().unwrap();
15567        let mut state = run_state(RunStatus::Stalled);
15568        state.id = format!(
15569            "resume-driver-{}",
15570            home.path().file_name().unwrap().to_str().unwrap()
15571        );
15572        state.driver_claimed = Some(false);
15573        state.save_under(home.path()).unwrap();
15574        let task = held_task_with(&state.id);
15575        let question = action_question(&state.id, resume_action(&state.id));
15576        let decide = || {
15577            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
15578                RunState::load_under(id, home.path())
15579            })
15580        };
15581        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
15582        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
15583        let expected_lock = home.path().join("runs").join(&state.id).join("driver.lock");
15584        match decide() {
15585            ActionDecision::Refuse(detail) => {
15586                assert!(
15587                    detail.starts_with("run already has a live driver: "),
15588                    "{detail}"
15589                );
15590                assert!(
15591                    detail.contains(&expected_lock.display().to_string()),
15592                    "{detail}"
15593                );
15594            }
15595            other => panic!("expected live driver refusal, got {other:?}"),
15596        }
15597        drop(lease);
15598        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
15599    }
15600
15601    #[test]
15602    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
15603        let home = tempfile::tempdir().unwrap();
15604        let mut state = run_state(RunStatus::Blocked);
15605        state.driver_exited = true;
15606        state.config.graph.review_rounds = 1;
15607        state.reviews = vec![review_round(1)];
15608        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
15609        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
15610            let mut saved = state.clone();
15611            match checkpoint {
15612                "publication" => saved.pr_publication_pending = true,
15613                "approval" => {
15614                    saved.land_approval = Some(crate::run::LandApproval {
15615                        question: "approval".into(),
15616                        head: "head".into(),
15617                    })
15618                }
15619                "armed" => saved.land_armed_head = Some("head".into()),
15620                "landing" => saved.status = RunStatus::Landing,
15621                _ => {
15622                    let mut question = ask::Question::new(
15623                        saved.id.clone(),
15624                        "review".into(),
15625                        "review-1".into(),
15626                        "continue?".into(),
15627                        String::new(),
15628                        vec!["continue".into()],
15629                    );
15630                    ask::Questions::at(home.path().join("questions"))
15631                        .put(&mut question)
15632                        .unwrap();
15633                }
15634            }
15635            saved.save_under(home.path()).unwrap();
15636            assert!(
15637                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
15638                "{checkpoint}"
15639            );
15640            assert!(
15641                crate::resume::validate(home.path(), &saved.id).is_ok(),
15642                "{checkpoint}"
15643            );
15644        }
15645    }
15646
15647    #[test]
15648    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
15649        let mut state = run_state(RunStatus::Blocked);
15650        state.config.graph.review_rounds = 3;
15651        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
15652        assert!(exhausted_review_budget(&state));
15653
15654        // One round still unused: resuming can still ask a reviewer something.
15655        state.reviews.pop();
15656        assert!(!exhausted_review_budget(&state));
15657
15658        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
15659        // count: only a `Blocked` run re-enters the review loop on resume.
15660        let mut stalled = run_state(RunStatus::Stalled);
15661        stalled.config.graph.review_rounds = 1;
15662        stalled.reviews = vec![review_round(1)];
15663        assert!(!exhausted_review_budget(&stalled));
15664    }
15665
15666    fn review_round(round: usize) -> crate::run::ReviewRound {
15667        crate::run::ReviewRound {
15668            round,
15669            head: "deadbeef".to_owned(),
15670            verified_head: None,
15671            verified_at: None,
15672            reviews: Vec::new(),
15673            e2e: Vec::new(),
15674            verify_retried: false,
15675            e2e_deferred: false,
15676            e2e_defer_reason: None,
15677            fix: None,
15678            blocking: 0,
15679            answered: 1,
15680            expected: 1,
15681            clean: false,
15682            progressed: true,
15683            vote_split: false,
15684            reconsideration: Vec::new(),
15685            verdict: None,
15686        }
15687    }
15688
15689    #[test]
15690    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
15691        let mut run = RunState::new(
15692            PathBuf::from("/repo"),
15693            "main".to_owned(),
15694            "abc1234def".to_owned(),
15695            "add retries".to_owned(),
15696            Config::default(),
15697        );
15698        run.status = RunStatus::Judging;
15699        run.parked = true;
15700        let mut task = Task::new(
15701            "add retries".to_owned(),
15702            "add retries".to_owned(),
15703            PathBuf::from("/repo"),
15704            crate::queue::Source::Human,
15705        );
15706        task.status = TaskStatus::Failed;
15707        task.runs = vec![run.id.clone()];
15708        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
15709        assert!(with(&task, &run), "parked after judging is the case");
15710        let mut parked_task = task.clone();
15711        parked_task.status = TaskStatus::Parked;
15712        assert!(with(&parked_task, &run), "the Parked status is the case");
15713
15714        let mut not_parked = run.clone();
15715        not_parked.parked = false;
15716        not_parked.status = RunStatus::Stalled;
15717        assert!(!with(&task, &not_parked), "a stall is the conductor's");
15718
15719        let mut fresh = task.clone();
15720        fresh.fresh_start = true;
15721        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
15722
15723        let mut review = task.clone();
15724        review.review_branch = Some("magi/x/A".to_owned());
15725        assert!(!with(&review, &run), "review is ranked before resume");
15726
15727        let mut held = task.clone();
15728        held.status = TaskStatus::Held;
15729        assert!(!with(&held, &run), "a hold stays visible to the conductor");
15730
15731        let mut released = run.clone();
15732        released.released_to = Some("20260901-000000-new1".to_owned());
15733        assert!(!with(&task, &released), "nothing left to resume into");
15734
15735        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
15736            "unreadable"
15737        )));
15738    }
15739
15740    #[test]
15741    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
15742        let mut released = RunState::new(
15743            PathBuf::from("/repo"),
15744            "main".to_owned(),
15745            "abc1234def".to_owned(),
15746            "add retries".to_owned(),
15747            Config::default(),
15748        );
15749        released.status = RunStatus::Blocked;
15750        assert_eq!(
15751            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
15752            Some(released.id.clone())
15753        );
15754        released.released_to = Some("20260901-000000-new1".to_owned());
15755        assert_eq!(
15756            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
15757            None,
15758            "there is nothing left to resume it into"
15759        );
15760    }
15761
15762    #[test]
15763    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
15764        // Mirrors the failure this exists to close: a task's last run ended
15765        // `Blocked` with the review budget spent, `crate::conduct` chose
15766        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
15767        // evidence), and without this check `attempt` would go on treating
15768        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
15769        // review loop iterates zero times over an already-spent budget, so
15770        // the resumed run settles right back to `Blocked` having asked nobody
15771        // anything, and `Requeue`'s promised fresh competition never happens.
15772        let mut exhausted = RunState::new(
15773            PathBuf::from("/repo"),
15774            "main".to_owned(),
15775            "abc1234def".to_owned(),
15776            "add retries".to_owned(),
15777            Config::default(),
15778        );
15779        exhausted.status = RunStatus::Blocked;
15780        exhausted.config.graph.review_rounds = 1;
15781        exhausted.reviews = vec![review_round(1)];
15782
15783        assert_eq!(
15784            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
15785            None,
15786            "an exhausted `Blocked` run must not be offered as resumable"
15787        );
15788
15789        // A `Blocked` run with rounds still unused is genuinely worth
15790        // resuming, and must still be found.
15791        let mut has_budget_left = RunState::new(
15792            PathBuf::from("/repo"),
15793            "main".to_owned(),
15794            "abc1234def".to_owned(),
15795            "add retries".to_owned(),
15796            Config::default(),
15797        );
15798        has_budget_left.status = RunStatus::Blocked;
15799        has_budget_left.config.graph.review_rounds = 3;
15800        has_budget_left.reviews = vec![review_round(1)];
15801
15802        assert_eq!(
15803            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
15804                Ok(has_budget_left.clone())
15805            }),
15806            Some(has_budget_left.id.clone())
15807        );
15808    }
15809
15810    #[test]
15811    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
15812        let mut run = RunState::new(
15813            PathBuf::from("/repo"),
15814            "main".to_owned(),
15815            "abc1234def".to_owned(),
15816            "add retries".to_owned(),
15817            Config::default(),
15818        );
15819        run.status = RunStatus::Blocked;
15820        run.config.graph.review_rounds = 1;
15821        run.reviews = vec![review_round(1)];
15822        run.pr_publication_pending = true;
15823        assert_eq!(
15824            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
15825            Some(run.id.clone()),
15826            "a spent review budget must not turn a failed publication into a re-competition"
15827        );
15828    }
15829
15830    #[test]
15831    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
15832        let mut task = Task::new(
15833            "recover work".into(),
15834            "recover work".into(),
15835            PathBuf::from("/repo"),
15836            crate::queue::Source::Human,
15837        );
15838        let mut history = std::collections::BTreeMap::new();
15839        for index in 0..8 {
15840            let mut run = run_state(RunStatus::Blocked);
15841            run.id = format!("20260101-000000-{index:04}");
15842            run.base_commit = format!("upstream-{index}");
15843            // Seven empty newer attempts must not erase the old recovery owner.
15844            if index > 0 {
15845                run.candidates.clear();
15846            }
15847            task.runs.extend([run.id.clone(), run.id.clone()]);
15848            history.insert(run.id.clone(), run);
15849            task.requeue();
15850        }
15851        let check = |task: &Task, starter: &Starter, limit| {
15852            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
15853        };
15854        assert!(
15855            check(&task, &Starter::Start, 8)
15856                .unwrap()
15857                .contains("8 unretired")
15858        );
15859        assert!(check(&task, &Starter::Start, 9).is_none());
15860        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
15861        task.release_operator("owner", None);
15862        assert_eq!(task.attempts, 0);
15863        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
15864        assert!(check(&restored, &Starter::Start, 8).is_some());
15865        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
15866        assert!(check(&restored, &Starter::Start, 0).is_none());
15867    }
15868
15869    #[test]
15870    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
15871        let tmp = tempfile::tempdir().unwrap();
15872        let mut task = Task::new(
15873            "recover selected PR".into(),
15874            "preserve implementation".into(),
15875            tmp.path().join("repo"),
15876            crate::queue::Source::Human,
15877        );
15878        let mut failed = run_state(RunStatus::Failed);
15879        failed.id = "20260101-000000-fail".into();
15880        failed.candidates.clear();
15881        failed.prep_complete = Some(false);
15882        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15883        failed.startup = Some(crate::run::Startup {
15884            kind: "pr-recovery".into(),
15885            branch: Some("selected-public-head".into()),
15886            stage: "worktree-setup".into(),
15887            complete: false,
15888            failure: Some("setup modified a tracked file and failed".into()),
15889        });
15890        // Setup may fail before a candidate is recorded; its dirty worktree
15891        // still needs protection and consumes the independent retained bound.
15892        let worktree = failed.worktree_root().join("under-review");
15893        std::fs::create_dir_all(&worktree).unwrap();
15894        let retained_edit = worktree.join("implementation");
15895        std::fs::write(&retained_edit, "retained setup edit").unwrap();
15896        task.record_startup_failure(crate::run::StartupFailure {
15897            run: failed.id.clone(),
15898            stage: "worktree-setup".into(),
15899        });
15900        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
15901        assert!(task.runs.is_empty() && task.passes.is_empty());
15902        assert_eq!(task.attempts, 0);
15903        let starter = Starter::Review("selected-public-head".into());
15904        assert!(
15905            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
15906                .unwrap()
15907                .contains("1 unretired")
15908        );
15909        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
15910        assert!(
15911            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
15912                .unwrap()
15913                .contains("Cannot verify")
15914        );
15915        // Older or mixed writers can link the same reservation in both lists.
15916        let mut mixed = task.clone();
15917        mixed.runs.push(failed.id.clone());
15918        mixed
15919            .startup_failures
15920            .push(task.startup_failures[0].clone());
15921        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
15922        failed.retired_to = Some("verified-recovery-owner".into());
15923        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
15924        assert!(
15925            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
15926                panic!("resuming the existing owner must not allocate a new attempt")
15927            })
15928            .is_none()
15929        );
15930        assert_eq!(
15931            std::fs::read_to_string(retained_edit).unwrap(),
15932            "retained setup edit"
15933        );
15934        assert!(task.runs.is_empty() && task.passes.is_empty());
15935        assert_eq!(task.attempts, 0);
15936    }
15937
15938    #[test]
15939    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
15940        let mut task = Task::new(
15941            "recover work".into(),
15942            "recover work".into(),
15943            PathBuf::from("/repo"),
15944            crate::queue::Source::Human,
15945        );
15946        let mut run = run_state(RunStatus::Superseded);
15947        run.candidates.clear();
15948        task.runs.push(run.id.clone());
15949        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
15950        run.retired_to = Some("authority".into());
15951        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
15952        run.retired_to = None;
15953        run.released_to = Some("authority".into());
15954        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
15955        assert!(
15956            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
15957                .unwrap()
15958                .contains("Cannot verify")
15959        );
15960        // Resuming an existing owner needs no new inventory or worktree budget.
15961        assert!(
15962            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
15963                panic!("resume must not load historical attempts")
15964            })
15965            .is_none()
15966        );
15967    }
15968
15969    #[test]
15970    fn retired_resume_requires_a_valid_same_repository_authority() {
15971        let mut source = run_state(RunStatus::Blocked);
15972        let mut empty = run_state(RunStatus::Blocked);
15973        empty.retired_to = Some(source.id.clone());
15974        let runs = vec![source.id.clone(), empty.id.clone()];
15975        let resolve = |source: &RunState, empty: &RunState| {
15976            unfinished_run_with(&runs, "fixture", |id| {
15977                if id == source.id {
15978                    Ok(source.clone())
15979                } else if id == empty.id {
15980                    Ok(empty.clone())
15981                } else {
15982                    bail!("unreadable authority")
15983                }
15984            })
15985        };
15986        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
15987        assert_eq!(
15988            choose_starter(None, false, resolve(&source, &empty).as_deref()),
15989            Starter::Resume(source.id.clone())
15990        );
15991        source.retired_to = Some(empty.id.clone());
15992        assert!(
15993            resolve(&source, &empty).is_none(),
15994            "cycles do not revive obsolete runs"
15995        );
15996        source.retired_to = None;
15997        source.repo = PathBuf::from("/another-repository");
15998        assert!(resolve(&source, &empty).is_none());
15999        source.repo = empty.repo.clone();
16000        source.released_to = Some("later".into());
16001        assert!(resolve(&source, &empty).is_none());
16002        empty.retired_to = Some("unlisted-run".into());
16003        assert!(resolve(&source, &empty).is_none());
16004    }
16005
16006    #[test]
16007    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
16008        // A task whose history holds an *older* run that still looks
16009        // resumable (say, a competition `Runner::review` was started
16010        // alongside after that older run went `Stalled`) and a *newest* run
16011        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
16012        // on this task must mean a fresh competition — falling back to the
16013        // stale, superseded `Stalled` run instead would resurrect history
16014        // nothing asked to revisit and silently defeat the requeue.
16015        let mut older_stalled = RunState::new(
16016            PathBuf::from("/repo"),
16017            "main".to_owned(),
16018            "abc1234def".to_owned(),
16019            "add retries".to_owned(),
16020            Config::default(),
16021        );
16022        older_stalled.status = RunStatus::Stalled;
16023
16024        let mut newest_exhausted = RunState::new(
16025            PathBuf::from("/repo"),
16026            "main".to_owned(),
16027            "abc1234def".to_owned(),
16028            "add retries".to_owned(),
16029            Config::default(),
16030        );
16031        newest_exhausted.status = RunStatus::Blocked;
16032        newest_exhausted.config.graph.review_rounds = 1;
16033        newest_exhausted.reviews = vec![review_round(1)];
16034
16035        assert_eq!(
16036            unfinished_run_with(
16037                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
16038                "t",
16039                |_| Ok(newest_exhausted.clone())
16040            ),
16041            None,
16042            "the newest run is exhausted, so nothing here is worth resuming - \
16043             least of all the older, already-superseded run"
16044        );
16045    }
16046
16047    #[test]
16048    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
16049        assert_eq!(
16050            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
16051                Err(anyhow::anyhow!("fixture is absent"))
16052            }),
16053            None
16054        );
16055    }
16056
16057    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
16058        let mut q = ask::Question::new(
16059            run.to_owned(),
16060            "implement".to_owned(),
16061            "impl-A".to_owned(),
16062            "continue?".to_owned(),
16063            String::new(),
16064            vec!["resume で続行する".to_owned(), "other".to_owned()],
16065        );
16066        q.actions.insert("resume で続行する".to_owned(), action);
16067        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
16068            .unwrap();
16069        q
16070    }
16071
16072    fn held_task_with(run: &str) -> Task {
16073        let mut t = task();
16074        t.runs = vec![run.to_owned()];
16075        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
16076        t
16077    }
16078
16079    fn resume_action(run: &str) -> ask::ChoiceAction {
16080        ask::ChoiceAction::Resume { run: run.into() }
16081    }
16082
16083    #[test]
16084    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
16085        let home = crate::run::test_home();
16086        for parked in [false, true] {
16087            let mut t = task();
16088            t.start("A".into());
16089            t.start("B".into());
16090            assert_eq!(t.runs, vec!["A", "B"]);
16091            t.start("A".into());
16092            let mut resumed = run_state(RunStatus::Blocked);
16093            resumed.id = "A".into();
16094            resumed.parked = parked;
16095            resumed.driver_exited = true;
16096            t.hold_machine(Some("resumed run stopped".into()));
16097            let q = action_question("A", resume_action("A"));
16098            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
16099            assert_eq!(
16100                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
16101                    assert_eq!(id, "A");
16102                    Ok(resumed.clone())
16103                }),
16104                ActionDecision::Resume("A".into())
16105            );
16106            assert_eq!(
16107                action_standing(&t, &action_question("B", resume_action("B"))),
16108                ActionStanding::Stale
16109            );
16110            t.release_operator("cli", None);
16111            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
16112                assert_eq!(id, "A");
16113                Ok(resumed.clone())
16114            });
16115            assert_eq!(
16116                choose_starter(None, false, unfinished.as_deref()),
16117                Starter::Resume("A".into())
16118            );
16119            assert_eq!(t.runs, vec!["B", "A"]);
16120        }
16121    }
16122
16123    #[test]
16124    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
16125        let home = crate::run::test_home();
16126        let mut state = crate::land::tests::repair_state(true, true);
16127        state.status = RunStatus::Landing;
16128        state.parked = true;
16129        state.driver_exited = true;
16130        let mut q = ask::Question::new(
16131            state.id.clone(),
16132            land::APPROVAL_NODE.into(),
16133            "land".into(),
16134            "Merge?".into(),
16135            String::new(),
16136            vec![land::APPROVE.into(), land::HOLD.into()],
16137        );
16138        q.id = state.id.clone();
16139        state.land_approval = Some(crate::run::LandApproval {
16140            question: q.id.clone(),
16141            head: "current-head".into(),
16142        });
16143        assert!(land::upgrade_repair_choice(&mut q, &state));
16144        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16145        let mut task = held_task_with(&state.id);
16146        task.status = TaskStatus::Parked;
16147        assert_eq!(
16148            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
16149            ActionDecision::Resume(state.id.clone())
16150        );
16151        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
16152        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
16153        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
16154        assert_eq!(
16155            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
16156            ActionDecision::Resume(state.id.clone()),
16157            "a repair answer newer than the manual hold resumes the existing owner"
16158        );
16159        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
16160        for answered_at in [q.answered_at, None] {
16161            let mut older = q.clone();
16162            older.answered_at = answered_at;
16163            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
16164                panic!("a later manual hold must prevent dispatch")
16165            });
16166            let ActionDecision::Refuse(reason) = refused else {
16167                panic!("expected an actionable refusal, got {refused:?}");
16168            };
16169            assert!(reason.contains("later operator decision"));
16170            assert!(reason.contains(&format!("magi task release {}", task.id)));
16171        }
16172        task.operator_decided_at = None;
16173        let mut superseded = state.clone();
16174        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
16175        assert_eq!(
16176            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
16177            ActionDecision::Stale
16178        );
16179        for case in 1..4 {
16180            let mut changed = state.clone();
16181            match case {
16182                1 => changed.status = RunStatus::Blocked,
16183                2 => changed.released_to = Some("new-owner".into()),
16184                _ => changed.land_approval.as_mut().unwrap().head.clear(),
16185            }
16186            assert!(matches!(
16187                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
16188                ActionDecision::Refuse(_)
16189            ));
16190        }
16191        assert!(matches!(
16192            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
16193                "missing owner"
16194            )),
16195            ActionDecision::Refuse(_)
16196        ));
16197        task.runs.push("replacement".into());
16198        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
16199        assert_eq!(
16200            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
16201                "old owner must not load"
16202            )),
16203            ActionDecision::Stale
16204        );
16205    }
16206
16207    #[test]
16208    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
16209        let mut state = crate::land::tests::repair_state(true, true);
16210        state.status = RunStatus::Landing;
16211        state.parked = true;
16212        state.driver_exited = true;
16213        let mut q = ask::Question::new(
16214            state.id.clone(),
16215            land::APPROVAL_NODE.into(),
16216            "land".into(),
16217            "Merge?".into(),
16218            String::new(),
16219            vec![land::APPROVE.into(), land::HOLD.into()],
16220        );
16221        q.id = state.id.clone();
16222        state.land_approval = Some(crate::run::LandApproval {
16223            question: q.id.clone(),
16224            head: "current-head".into(),
16225        });
16226        state.save().unwrap();
16227        land::upgrade_repair_choice(&mut q, &state);
16228        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16229        Questions::open().put(&mut q).unwrap();
16230        let tmp = tempfile::tempdir().unwrap();
16231        let queue = Queue::at(tmp.path().join("queue"));
16232        let mut task = held_task_with(&state.id);
16233        task.status = TaskStatus::Parked;
16234        queue.put(&mut task).unwrap();
16235        let empty = Arc::new(tokio::sync::Semaphore::new(0));
16236        let free = Arc::new(tokio::sync::Semaphore::new(1));
16237        assert!(matches!(
16238            claim_dispatch(&queue, &task, false, &empty, &free),
16239            Err(SkipReason::OrdinaryCapacity)
16240        ));
16241        assert!(matches!(
16242            claim_dispatch(&queue, &task, true, &free, &free),
16243            Err(SkipReason::CoolingDown)
16244        ));
16245        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
16246        assert!(claim.permit.is_some());
16247        assert!(matches!(
16248            claim_dispatch(&queue, &task, false, &free, &free),
16249            Err(SkipReason::ClaimUnavailable)
16250        ));
16251        drop(claim);
16252        Questions::open()
16253            .update(&q.id, |q| {
16254                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
16255                Ok(())
16256            })
16257            .unwrap();
16258        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
16259        assert!(claim.permit.is_none());
16260        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
16261    }
16262
16263    #[test]
16264    fn decide_action_resumes_only_the_latest_resumable_run() {
16265        let home = crate::run::test_home();
16266        let t = held_task_with("r1");
16267        let q = action_question("r1", resume_action("r1"));
16268        let load = |s: RunState| move |_: &str| Ok(s);
16269        assert_eq!(
16270            decide_action(
16271                &home,
16272                &t,
16273                &q,
16274                &PHRASES_EN,
16275                load(run_state(RunStatus::Blocked))
16276            ),
16277            ActionDecision::Resume("r1".into())
16278        );
16279        // Not the latest run of the task.
16280        let q_other = action_question("r1", resume_action("r0"));
16281        assert!(matches!(
16282            decide_action(
16283                &home,
16284                &t,
16285                &q_other,
16286                &PHRASES_EN,
16287                load(run_state(RunStatus::Blocked))
16288            ),
16289            ActionDecision::Refuse(_)
16290        ));
16291        // A finished run cannot make progress.
16292        assert!(matches!(
16293            decide_action(
16294                &home,
16295                &t,
16296                &q,
16297                &PHRASES_EN,
16298                load(run_state(RunStatus::Ready))
16299            ),
16300            ActionDecision::Refuse(_)
16301        ));
16302        // A released one either.
16303        let mut released = run_state(RunStatus::Blocked);
16304        released.released_to = Some("elsewhere".into());
16305        assert!(matches!(
16306            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
16307            ActionDecision::Refuse(_)
16308        ));
16309        // Unreadable state is a refusal, never a fresh competition.
16310        assert!(matches!(
16311            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
16312            ActionDecision::Refuse(_)
16313        ));
16314    }
16315
16316    #[test]
16317    fn decide_action_ignores_a_question_about_an_earlier_run() {
16318        let home = crate::run::test_home();
16319        let mut t = held_task_with("r1");
16320        t.runs.push("r2".to_owned());
16321        let never = |_: &str| -> Result<RunState> { bail!("not read") };
16322        assert_eq!(
16323            decide_action(
16324                &home,
16325                &t,
16326                &action_question("r1", ask::ChoiceAction::Done),
16327                &PHRASES_EN,
16328                never
16329            ),
16330            ActionDecision::Stale
16331        );
16332    }
16333
16334    #[test]
16335    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
16336        let home = crate::run::test_home();
16337        let mut t = held_task_with("r1");
16338        let never = |_: &str| -> Result<RunState> { bail!("not read") };
16339        assert_eq!(
16340            decide_action(
16341                &home,
16342                &t,
16343                &action_question("r1", ask::ChoiceAction::Requeue),
16344                &PHRASES_EN,
16345                never
16346            ),
16347            ActionDecision::Requeue
16348        );
16349        let done_q = action_question("r1", ask::ChoiceAction::Done);
16350        assert_eq!(
16351            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
16352            ActionDecision::Done
16353        );
16354        t.mark_action_applied(&done_q.id);
16355        assert_eq!(
16356            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
16357            ActionDecision::Skip
16358        );
16359
16360        // A plain answer (no action for that label) does nothing.
16361        let mut plain = action_question("r1", ask::ChoiceAction::Done);
16362        plain.actions.clear();
16363        assert_eq!(
16364            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
16365            ActionDecision::Skip
16366        );
16367        // A running task is left alone.
16368        let mut running = held_task_with("r1");
16369        running.status = TaskStatus::Running;
16370        assert_eq!(
16371            decide_action(
16372                &home,
16373                &running,
16374                &action_question("r1", ask::ChoiceAction::Done),
16375                &PHRASES_EN,
16376                never
16377            ),
16378            ActionDecision::Skip
16379        );
16380    }
16381
16382    #[test]
16383    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
16384        crate::run::pin_test_home();
16385        for legacy in [false, true] {
16386            let dir = tempfile::tempdir().unwrap();
16387            let queue = Queue::at(dir.path().join("queue"));
16388            let questions = Questions::at(dir.path().join("questions"));
16389            let run = "20260101-000000-hold";
16390            let mut task = held_task_with(run);
16391            task.status = TaskStatus::Parked;
16392            let mut q = ask::Question::new(
16393                run.into(),
16394                land::APPROVAL_NODE.into(),
16395                "land".into(),
16396                "Repair?".into(),
16397                String::new(),
16398                vec![land::REPAIR.into()],
16399            );
16400            q.actions.insert(land::REPAIR.into(), resume_action(run));
16401            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16402            // Deterministically order the answer before the actual manual hold.
16403            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
16404            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
16405            questions.put(&mut q).unwrap();
16406            task.hold_manual(Some("Keep this PR paused".into()));
16407            if legacy {
16408                task.hold_source = None;
16409            }
16410            queue.put(&mut task).unwrap();
16411
16412            apply_task_choice_actions(&queue, &questions, dir.path());
16413            let after = queue.get(&task.id).unwrap();
16414            assert!(after.operator_held());
16415            assert_eq!(after.hold_source, task.hold_source);
16416            assert_eq!(after.operator_decided_at, task.operator_decided_at);
16417            assert_eq!(after.runs, task.runs);
16418            assert_eq!(after.instruction, task.instruction);
16419            assert!(after.resume_override.is_none());
16420            assert!(after.action_applied(&q.id));
16421            let reason = after.hold_reason.as_deref().unwrap();
16422            assert!(reason.starts_with("Keep this PR paused"));
16423            assert!(reason.contains("later operator decision"));
16424            assert!(reason.contains(&format!("magi task release {}", task.id)));
16425
16426            for recovery in [
16427                crate::conduct::Recovery::Review,
16428                crate::conduct::Recovery::Requeue,
16429            ] {
16430                crate::conduct::apply(
16431                    &queue,
16432                    &questions,
16433                    &crate::conduct::Verdict {
16434                        decisions: vec![crate::conduct::Decision {
16435                            id: task.id.clone(),
16436                            recovery: Some(recovery),
16437                            ..Default::default()
16438                        }],
16439                    },
16440                )
16441                .unwrap();
16442            }
16443            // Reconciliation is idempotent, and automatic recovery cannot
16444            // reopen this owner after it observes the rejected repair answer.
16445            apply_task_choice_actions(&queue, &questions, dir.path());
16446            let still_held = queue.get(&task.id).unwrap();
16447            assert!(still_held.operator_held());
16448            assert_eq!(still_held.hold_reason, after.hold_reason);
16449            assert_eq!(still_held.runs, task.runs);
16450            assert!(still_held.review_branch.is_none());
16451            assert!(!still_held.fresh_start);
16452            assert!(queue.next_runnable().is_none());
16453        }
16454    }
16455
16456    #[test]
16457    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
16458        for held in [false, true] {
16459            for retry in [false, true] {
16460                let dir = tempfile::tempdir().unwrap();
16461                let queue = Queue::at(dir.path().join("queue"));
16462                let questions = Questions::at(dir.path().join("questions"));
16463                let home = dir.path().join("home");
16464                let mut t = task();
16465                if held {
16466                    t.hold_machine(Some("driver state unknown".into()));
16467                }
16468                queue.put(&mut t).unwrap();
16469                let verdict = serde_json::from_value(serde_json::json!({
16470                    "decisions": [{
16471                        "id": t.id,
16472                        "question": "Driver state unknown; retry the checks or hold?",
16473                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
16474                        "actions": {
16475                            "daemon: recheck and retry": {"do": "requeue"},
16476                            "daemon: hold the task": {"do": "hold"}
16477                        }
16478                    }]
16479                }))
16480                .unwrap();
16481                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
16482                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
16483                let mut q = questions.list().pop().unwrap();
16484                let choice = if retry {
16485                    "daemon: recheck and retry"
16486                } else {
16487                    "daemon: hold the task"
16488                };
16489                assert_eq!(q.actions.len(), 2);
16490                q.answer(ask::Answer::Choice(choice.into())).unwrap();
16491                questions.put(&mut q).unwrap();
16492
16493                // A Web answer does not remove the deputy's fresh lease.
16494                questions.beat(&q.id, ask::WaiterKind::Deputy);
16495                for _ in 0..2 {
16496                    resolve_blockers(&queue, &questions);
16497                    apply_task_choice_actions(&queue, &questions, &home);
16498                    let waiting = queue.get(&t.id).unwrap();
16499                    assert_eq!(waiting.status, TaskStatus::Blocked);
16500                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
16501                    assert!(waiting.answers.is_empty());
16502                    assert!(!waiting.action_applied(&q.id));
16503                    assert!(runnable(&queue).is_empty());
16504                    let free = Arc::new(tokio::sync::Semaphore::new(1));
16505                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
16506                }
16507                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
16508
16509                // Releasing the blocker and applying the operation share one save.
16510                resolve_blockers(&queue, &questions);
16511                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
16512                apply_task_choice_actions(&queue, &questions, &home);
16513                let after = queue.get(&t.id).unwrap();
16514                assert_eq!(
16515                    after.status,
16516                    if retry {
16517                        TaskStatus::Queued
16518                    } else {
16519                        TaskStatus::Held
16520                    }
16521                );
16522                assert!(after.action_applied(&q.id));
16523                assert_eq!(after.operator_held(), !retry);
16524                assert_eq!(after.answers.len(), 1);
16525
16526                // A later operator decision must not replay this answer.
16527                let mut changed = after;
16528                if retry {
16529                    changed.hold_manual(Some("later hold".into()));
16530                } else {
16531                    changed.release_operator("test", None);
16532                }
16533                let expected = changed.status;
16534                queue.put(&mut changed).unwrap();
16535                apply_task_choice_actions(&queue, &questions, &home);
16536                assert_eq!(queue.get(&t.id).unwrap().status, expected);
16537            }
16538        }
16539    }
16540
16541    #[test]
16542    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
16543        let dir = tempfile::tempdir().unwrap();
16544        let queue = Queue::at(dir.path().join("queue"));
16545        let questions = Questions::at(dir.path().join("questions"));
16546        let home = dir.path().join("home");
16547        let mut state = run_state(RunStatus::Blocked);
16548        state.id = "20260101-000000-act1".to_owned();
16549        state.save_under(&home).unwrap();
16550
16551        let mut t = held_task_with(&state.id);
16552        queue.put(&mut t).unwrap();
16553        let mut q = action_question(&state.id, resume_action(&state.id));
16554        questions.put(&mut q).unwrap();
16555
16556        apply_task_choice_actions(&queue, &questions, &home);
16557        let after = queue.get(&t.id).unwrap();
16558        assert_eq!(after.status, TaskStatus::Queued);
16559        assert!(!after.fresh_start);
16560        assert!(after.action_applied(&q.id));
16561        let pin = after.resume_override.clone().unwrap();
16562        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
16563        assert!(pin.forced);
16564
16565        // Held again later: the same answer does not release it a second time.
16566        let mut again = queue.get(&t.id).unwrap();
16567        again.hold_machine(Some("later".into()));
16568        queue.put(&mut again).unwrap();
16569        apply_task_choice_actions(&queue, &questions, &home);
16570        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16571    }
16572
16573    #[test]
16574    fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
16575        let dir = tempfile::tempdir().unwrap();
16576        let home = dir.path();
16577        let queue = Queue::at(home.join("queue"));
16578        let questions = Questions::at(home.join("questions"));
16579        let mut state = run_state(RunStatus::Blocked);
16580        state.save_under(home).unwrap();
16581        let mut task = held_task_with(&state.id);
16582        queue.put(&mut task).unwrap();
16583        let mut question = action_question(&state.id, ask::ChoiceAction::Done);
16584        questions.put(&mut question).unwrap();
16585
16586        apply_task_choice_actions(&queue, &questions, home);
16587
16588        let after = queue.get(&task.id).unwrap();
16589        assert_eq!(after.status, TaskStatus::Held);
16590        assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
16591        assert_eq!(after.runs, task.runs);
16592        assert!(after.completion_history.is_empty());
16593        assert!(!after.decision_effects.contains_key(&question.id));
16594        assert_eq!(
16595            RunState::load_under(&state.id, home).unwrap().status,
16596            RunStatus::Blocked
16597        );
16598    }
16599
16600    #[test]
16601    fn a_delivered_answer_is_still_acted_on_exactly_once() {
16602        let dir = tempfile::tempdir().unwrap();
16603        let queue = Queue::at(dir.path().join("queue"));
16604        let questions = Questions::at(dir.path().join("questions"));
16605        let home = dir.path().join("home");
16606        let mut state = run_state(RunStatus::Blocked);
16607        state.id = "20260101-000000-act2".to_owned();
16608        state.save_under(&home).unwrap();
16609
16610        let mut t = held_task_with(&state.id);
16611        queue.put(&mut t).unwrap();
16612        let mut q = action_question(&state.id, resume_action(&state.id));
16613        q.answer_delivered = true;
16614        questions.put(&mut q).unwrap();
16615
16616        // Delivered, and the agent then died: the task is still held, so the
16617        // chosen action applies.
16618        apply_task_choice_actions(&queue, &questions, &home);
16619        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
16620        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
16621
16622        // Held again: the same answer does nothing a second time.
16623        let mut again = queue.get(&t.id).unwrap();
16624        again.hold_machine(Some("later".into()));
16625        queue.put(&mut again).unwrap();
16626        apply_task_choice_actions(&queue, &questions, &home);
16627        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16628    }
16629
16630    #[test]
16631    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
16632        let dir = tempfile::tempdir().unwrap();
16633        let queue = Queue::at(dir.path().join("queue"));
16634        let questions = Questions::at(dir.path().join("questions"));
16635        let home = dir.path().join("home");
16636        let mut state = run_state(RunStatus::Blocked);
16637        state.id = "20260101-000000-act3".to_owned();
16638        state.save_under(&home).unwrap();
16639        let mut t = held_task_with(&state.id);
16640        queue.put(&mut t).unwrap();
16641        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
16642        questions.put(&mut q).unwrap();
16643
16644        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
16645        apply_task_choice_actions(&queue, &questions, &home);
16646        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16647
16648        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
16649        apply_task_choice_actions(&queue, &questions, &home);
16650        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
16651    }
16652
16653    #[test]
16654    fn action_standing_tells_the_reasons_apart() {
16655        let mut t = held_task_with("r1");
16656        let q = action_question("r1", ask::ChoiceAction::Requeue);
16657        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
16658        let mut plain = q.clone();
16659        plain.actions.clear();
16660        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
16661
16662        // Applied wins over everything, even a running task.
16663        t.mark_action_applied(&q.id);
16664        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
16665
16666        // A newer attempt running: the old question is Stale, not Busy.
16667        let mut t = held_task_with("r1");
16668        t.start("r2".to_owned());
16669        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
16670        // The same question about the latest run just waits.
16671        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
16672        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
16673        t.status = TaskStatus::Blocked;
16674        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
16675
16676        // A conductor question is keyed by the task, never stale.
16677        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
16678        c.node = crate::conduct::NODE.to_owned();
16679        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
16680        assert!(!ActionStanding::Busy.daemon_owns());
16681    }
16682
16683    #[test]
16684    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
16685        let dir = tempfile::tempdir().unwrap();
16686        let queue = Queue::at(dir.path().join("queue"));
16687        let questions = Questions::at(dir.path().join("questions"));
16688        let home = dir.path().join("home");
16689        // Execution finished before task settlement; Done is not a discard.
16690        let mut state = run_state(RunStatus::Ready);
16691        state.id = "20260101-000000-act4".to_owned();
16692        state.save_under(&home).unwrap();
16693        let mut t = held_task_with(&state.id);
16694        t.status = TaskStatus::Running;
16695        queue.put(&mut t).unwrap();
16696        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
16697        q.cwd = Some(dir.path().display().to_string());
16698        questions.put(&mut q).unwrap();
16699
16700        // While the task runs the daemon will not act, so the waiter still
16701        // delivers the word to the dead asker's seat ...
16702        let running = queue.get(&t.id).unwrap();
16703        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
16704        assert!(matches!(
16705            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
16706            crate::waiter::Action::Deliver(_)
16707        ));
16708        // ... and the daemon waits while the task runs, then applies once.
16709        apply_task_choice_actions(&queue, &questions, &home);
16710        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
16711        let mut back = queue.get(&t.id).unwrap();
16712        back.hold_machine(Some("later".into()));
16713        queue.put(&mut back).unwrap();
16714        apply_task_choice_actions(&queue, &questions, &home);
16715        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
16716        let mut again = queue.get(&t.id).unwrap();
16717        again.hold_machine(Some("again".into()));
16718        queue.put(&mut again).unwrap();
16719        apply_task_choice_actions(&queue, &questions, &home);
16720        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16721    }
16722
16723    #[test]
16724    fn stale_heartbeat_pointing_to_terminal_worker_does_not_block_resume_while_unproven_claims_stay_protected()
16725     {
16726        let dir = tempfile::tempdir().unwrap();
16727        let home = dir.path();
16728        let queue = Queue::at(home.join("queue"));
16729        let mut state = run_state(RunStatus::Blocked);
16730        state.id = "20261125-084544-669a".to_owned();
16731        state.driver_exited = true;
16732        state.driver_pid = None;
16733        state.driver_started_at = None;
16734        state.save_under(home).unwrap();
16735
16736        let mut t = held_task_with(&state.id);
16737        queue.put(&mut t).unwrap();
16738
16739        // Simulate a task worker that finished and was archived to results/,
16740        // while daemon.json still has a fresh heartbeat referencing that worker.
16741        let worker_id = "fc769e65-0000-4000-8000-000000000001";
16742        let retained_dir = home.join("workers").join("results").join(worker_id);
16743        std::fs::create_dir_all(&retained_dir).unwrap();
16744        let finished_job = crate::worker::Job {
16745            id: worker_id.to_owned(),
16746            sequence: 1,
16747            kind: "task".to_owned(),
16748            key: format!("task:{}", t.id),
16749            payload: serde_json::json!({
16750                "queue": home.join("queue"),
16751                "task": t.id,
16752                "opts": Opts::default(),
16753                "standalone": false,
16754            }),
16755            generation: "a".repeat(64),
16756            version: Some("0.260.0".to_owned()),
16757            status: crate::worker::Status::Finished,
16758            result: Some("completed".to_owned()),
16759            pid: Some(37456),
16760            created_at: 1,
16761            finished_at: Some(2),
16762        };
16763        std::fs::write(
16764            retained_dir.join("job.json"),
16765            serde_json::to_vec(&finished_job).unwrap(),
16766        )
16767        .unwrap();
16768
16769        let now = Timestamp::now();
16770        let mut status = Status::new();
16771        status.updated_at = now;
16772        status.current = vec![Current {
16773            worker: Some(worker_id.to_owned()),
16774            task: t.id.clone(),
16775            run: state.id.clone(),
16776        }];
16777        write_status_to(&home.join("daemon.json"), &status).unwrap();
16778
16779        assert!(
16780            claim_for_run(home, &state.id, now).is_none(),
16781            "a fresh heartbeat pointing to a confirmed terminal worker must not claim the run"
16782        );
16783        assert!(crate::resume::validate(home, &state.id).is_ok());
16784
16785        // Legacy heartbeat without worker id remains protected.
16786        status.current = vec![Current {
16787            worker: None,
16788            task: t.id.clone(),
16789            run: state.id.clone(),
16790        }];
16791        write_status_to(&home.join("daemon.json"), &status).unwrap();
16792        let legacy_err = crate::resume::validate(home, &state.id)
16793            .unwrap_err()
16794            .to_string();
16795        assert!(
16796            legacy_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16797            "{legacy_err}"
16798        );
16799        assert!(legacy_err.contains("worker=none"), "{legacy_err}");
16800
16801        // Heartbeat naming a missing/unreadable worker record remains protected.
16802        let missing_id = "fc769e65-0000-4000-8000-000000000002";
16803        status.current = vec![Current {
16804            worker: Some(missing_id.to_owned()),
16805            task: t.id.clone(),
16806            run: state.id.clone(),
16807        }];
16808        write_status_to(&home.join("daemon.json"), &status).unwrap();
16809        let missing_err = crate::resume::validate(home, &state.id)
16810            .unwrap_err()
16811            .to_string();
16812        assert!(
16813            missing_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16814            "{missing_err}"
16815        );
16816        assert!(missing_err.contains(missing_id), "{missing_err}");
16817        assert!(missing_err.contains("status=unknown"), "{missing_err}");
16818
16819        // Heartbeat naming a Running (non-terminal) worker whose lease is not held
16820        // still remains protected conservatively until fenced to a terminal status.
16821        let running_id = "fc769e65-0000-4000-8000-000000000003";
16822        let running_dir = home.join("workers").join("jobs").join(running_id);
16823        std::fs::create_dir_all(&running_dir).unwrap();
16824        let running_job = crate::worker::Job {
16825            id: running_id.to_owned(),
16826            status: crate::worker::Status::Running,
16827            pid: Some(42424),
16828            finished_at: None,
16829            result: None,
16830            ..finished_job
16831        };
16832        std::fs::write(
16833            running_dir.join("job.json"),
16834            serde_json::to_vec(&running_job).unwrap(),
16835        )
16836        .unwrap();
16837        std::fs::write(running_dir.join("live.lock"), b"").unwrap();
16838        status.current = vec![Current {
16839            worker: Some(running_id.to_owned()),
16840            task: t.id.clone(),
16841            run: state.id.clone(),
16842        }];
16843        write_status_to(&home.join("daemon.json"), &status).unwrap();
16844        let running_err = crate::resume::validate(home, &state.id)
16845            .unwrap_err()
16846            .to_string();
16847        assert!(
16848            running_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16849            "{running_err}"
16850        );
16851        assert!(running_err.contains(running_id), "{running_err}");
16852        assert!(running_err.contains("pid=42424"), "{running_err}");
16853        assert!(running_err.contains("status=running"), "{running_err}");
16854    }
16855
16856    #[test]
16857    fn resume_validate_refusals_include_concrete_evidence_for_every_live_path() {
16858        let dir = tempfile::tempdir().unwrap();
16859        let home = dir.path();
16860        let queue = Queue::at(home.join("queue"));
16861        let mut state = run_state(RunStatus::Blocked);
16862        state.id = "20261125-090000-evid".to_owned();
16863        state.driver_exited = true;
16864        state.save_under(home).unwrap();
16865        let mut t = held_task_with(&state.id);
16866        queue.put(&mut t).unwrap();
16867
16868        // 1. Live task worker holding live.lock.
16869        let payload = serde_json::json!({
16870            "queue": home.join("queue"),
16871            "task": t.id,
16872            "opts": Opts::default(),
16873            "standalone": false,
16874        });
16875        let (job, lease) =
16876            crate::worker::running_fixture(home, &format!("task:{}", t.id), payload).unwrap();
16877        let worker_err = crate::resume::validate(home, &state.id)
16878            .unwrap_err()
16879            .to_string();
16880        assert!(
16881            worker_err.starts_with("run already has a live driver: worker claim"),
16882            "{worker_err}"
16883        );
16884        assert!(worker_err.contains(&job.id), "{worker_err}");
16885        assert!(
16886            worker_err.contains(&format!("pid={}", std::process::id())),
16887            "{worker_err}"
16888        );
16889        assert!(worker_err.contains("status=running"), "{worker_err}");
16890        assert!(worker_err.contains("live.lock held"), "{worker_err}");
16891        drop(lease);
16892        std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id)).unwrap();
16893
16894        // 2. Unfenced Starting worker reservation.
16895        let starting_id = "fc769e65-0000-4000-8000-000000000010";
16896        let starting_dir = home.join("workers").join("jobs").join(starting_id);
16897        std::fs::create_dir_all(&starting_dir).unwrap();
16898        let starting_job = crate::worker::Job {
16899            id: starting_id.to_owned(),
16900            sequence: 2,
16901            kind: "task".to_owned(),
16902            key: format!("task:{}", t.id),
16903            payload: serde_json::json!({
16904                "queue": home.join("queue"),
16905                "task": t.id,
16906                "opts": Opts::default(),
16907                "standalone": false,
16908            }),
16909            generation: "a".repeat(64),
16910            version: None,
16911            status: crate::worker::Status::Starting,
16912            result: None,
16913            pid: None,
16914            created_at: 1,
16915            finished_at: None,
16916        };
16917        std::fs::write(
16918            starting_dir.join("job.json"),
16919            serde_json::to_vec(&starting_job).unwrap(),
16920        )
16921        .unwrap();
16922        let starting_err = crate::resume::validate(home, &state.id)
16923            .unwrap_err()
16924            .to_string();
16925        assert!(
16926            starting_err.starts_with("run already has a live driver: worker claim"),
16927            "{starting_err}"
16928        );
16929        assert!(starting_err.contains(starting_id), "{starting_err}");
16930        assert!(starting_err.contains("status=starting"), "{starting_err}");
16931        assert!(
16932            starting_err.contains("unfenced starting reservation"),
16933            "{starting_err}"
16934        );
16935        std::fs::remove_dir_all(&starting_dir).unwrap();
16936
16937        // 3. Unrelated corrupt worker triggers conservative protection with distinct wording.
16938        let corrupt_id = "bad00000-0000-4000-8000-000000000099";
16939        let corrupt_dir = home.join("workers").join("jobs").join(corrupt_id);
16940        std::fs::create_dir_all(&corrupt_dir).unwrap();
16941        std::fs::write(corrupt_dir.join("job.json"), b"{not valid json").unwrap();
16942        let store_err = crate::resume::validate(home, &state.id)
16943            .unwrap_err()
16944            .to_string();
16945        assert!(
16946            store_err.starts_with(
16947                "run already has a live driver: worker store observation failed (conservative protection):"
16948            ),
16949            "{store_err}"
16950        );
16951        assert!(store_err.contains(corrupt_id), "{store_err}");
16952        std::fs::remove_dir_all(&corrupt_dir).unwrap();
16953
16954        // 4. Held execution lease (driver.lock path).
16955        state.driver_exited = false;
16956        state.driver_claimed = Some(false);
16957        state.driver_pid = None;
16958        state.driver_started_at = None;
16959        state.save_under(home).unwrap();
16960        let exec_lease = crate::driver::maintenance(home, &state.id).unwrap();
16961        let lease_err = crate::resume::validate(home, &state.id)
16962            .unwrap_err()
16963            .to_string();
16964        let lock_path = home.join("runs").join(&state.id).join("driver.lock");
16965        assert!(
16966            lease_err.starts_with("run already has a live driver: execution lease held"),
16967            "{lease_err}"
16968        );
16969        assert!(
16970            lease_err.contains(&lock_path.display().to_string()),
16971            "{lease_err}"
16972        );
16973        drop(exec_lease);
16974
16975        // 5. Live process identity (pid + identity).
16976        let pid = std::process::id();
16977        let identity = crate::proc::process_started_at(pid).expect("current process identity");
16978        state.driver_claimed = None;
16979        state.driver_pid = Some(pid);
16980        state.driver_started_at = Some(identity.clone());
16981        state.save_under(home).unwrap();
16982        let pid_err = crate::resume::validate(home, &state.id)
16983            .unwrap_err()
16984            .to_string();
16985        assert!(
16986            pid_err.starts_with("run already has a live driver: live driver process"),
16987            "{pid_err}"
16988        );
16989        assert!(pid_err.contains(&format!("pid={pid}")), "{pid_err}");
16990        assert!(
16991            pid_err.contains(&format!("identity={identity}")),
16992            "{pid_err}"
16993        );
16994
16995        // decide_action uses the exact same refusal format for process identity too.
16996        let question = action_question(&state.id, resume_action(&state.id));
16997        let decision = decide_action(home, &t, &question, &PHRASES_EN, |id| {
16998            RunState::load_under(id, home)
16999        });
17000        assert_eq!(decision, ActionDecision::Refuse(pid_err));
17001    }
17002}